Created
February 17, 2022 09:08
-
-
Save jerryan999/6fcdbc463c71a9d2086ad31308c7b74e to your computer and use it in GitHub Desktop.
AES-128-ECB PKCS7Padding
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| b64 "encoding/base64" | |
| "fmt" | |
| "github.com/andreburgaud/crypt2go/padding" | |
| "golang.org/x/crypto/blowfish" | |
| ecb "github.com/haowanxing/go-aes-ecb" | |
| ) | |
| func encrypt(pt, key []byte) []byte { | |
| block, err := blowfish.NewCipher(key) | |
| if err != nil { | |
| panic(err.Error()) | |
| } | |
| mode := ecb.NewECBEncrypter(block) | |
| padder := padding.NewPkcs5Padding() | |
| pt, err = padder.Pad(pt) // pad last block of plaintext if block size less than block cipher size | |
| if err != nil { | |
| panic(err.Error()) | |
| } | |
| ct := make([]byte, len(pt)) | |
| mode.CryptBlocks(ct, pt) | |
| return ct | |
| } | |
| func decrypt(ct, key []byte) []byte { | |
| block, err := blowfish.NewCipher(key) | |
| if err != nil { | |
| panic(err.Error()) | |
| } | |
| mode := ecb.NewECBDecrypter(block) | |
| pt := make([]byte, len(ct)) | |
| mode.CryptBlocks(pt, ct) | |
| padder := padding.NewPkcs7Padding(16) | |
| pt, err = padder.Unpad(pt) // unpad plaintext after decryption | |
| if err != nil { | |
| panic(err.Error()) | |
| } | |
| return pt | |
| } | |
| func main() { | |
| content := "hello" | |
| key := "0123456789abcdef" | |
| // 加密流程 | |
| // 使用PKCS#7对原文进行填充,BlockSize为16字节 | |
| ciphertext := ecb.PKCS7Padding([]byte(content), 16) | |
| // encrpy func | |
| crypted, err := ecb.AesEncrypt(ciphertext, []byte(key)) | |
| if err != nil { | |
| panic(err.Error()) | |
| } | |
| // base64 encode | |
| cryptedB64encoded := b64.StdEncoding.EncodeToString([]byte(crypted)) | |
| fmt.Println("crypted base64encode: ", cryptedB64encoded) | |
| // 解密流程 | |
| // base64 decode | |
| var tobedecode string = cryptedB64encoded | |
| crypted, _ = b64.StdEncoding.DecodeString(tobedecode) | |
| origin, err := ecb.AesDecrypt(crypted, []byte(key)) | |
| if err != nil { | |
| panic(err.Error()) | |
| } | |
| // 使用PKCS#7对解密后的内容去除填充 | |
| origin = ecb.PKCS7UnPadding(origin) | |
| // 打印原始文本 | |
| fmt.Println("row decrypted: ", string(origin)) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment