用Go加密AES字符串,用Crypto-js解密



我正在寻找加密字符串在我的Go应用程序和解密与Crypto-js编码字符串。

我已经尝试了几个小时没有成功,尝试了许多由Stackoverflow, github或gist提供的解决方案。

如果有人有解决办法,他们会把我从某种精神崩溃中拯救出来lol

My Go encrypt code:

func EncryptBody() (encodedmess string, err error) {
key := []byte("6368616e676520746869732070617373")
// Create the AES cipher
block, err := aes.NewCipher(key)
if err != nil {
panic(err)
}
plaintext, _ := pkcs7Pad([]byte("exampletext"), block.BlockSize())
// The IV needs to be unique, but not secure. Therefore it's common to
// include it at the beginning of the ciphertext.
ciphertext := make([]byte, aes.BlockSize+len(plaintext))
iv := ciphertext[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
panic(err)
}
bm := cipher.NewCBCEncrypter(block, iv)
bm.CryptBlocks(ciphertext[aes.BlockSize:], plaintext)
return fmt.Sprintf("%x", ciphertext), nil
}

My pkcs7Pad函数:

func pkcs7Pad(b []byte, blocksize int) ([]byte, error) {
if blocksize <= 0 {
return nil, errors.New("invalid blocksize")
}
if b == nil || len(b) == 0 {
return nil, errors.New("invalid PKCS7 data (empty or not padded)")
}
n := blocksize - (len(b) % blocksize)
pb := make([]byte, len(b)+n)
copy(pb, b)
copy(pb[len(b):], bytes.Repeat([]byte{byte(n)}, n))
return pb, nil
}

我的Crypto-JS解密代码:

public decryptData() {
const data = "3633fbef042b01da5fc4b69d8f038a83130994a898137bb0386604cf2c1cbbe6"

const key = "6368616e676520746869732070617373"
const decrypted = CryptoJS.AES.decrypt(data, key, {
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
})
console.log("Result : " + decrypted.toString(CryptoJS.enc.Hex))
return decrypted.toString(CryptoJS.enc.Hex)
}

感谢@Topaco的帮助!

解决方案:

Go code:

func EncryptBody(data string) (encodedmess string, err error) {
key := []byte("6368616e676520746869732070617373")
// Create the AES cipher
block, err := aes.NewCipher(key)
if err != nil {
panic(err)
}
plaintext, _ := pkcs7Pad([]byte(data), block.BlockSize())
// The IV needs to be unique, but not secure. Therefore it's common to
// include it at the beginning of the ciphertext.
ciphertext := make([]byte, aes.BlockSize+len(plaintext))
iv := ciphertext[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
panic(err)
}
bm := cipher.NewCBCEncrypter(block, iv)
bm.CryptBlocks(ciphertext[aes.BlockSize:], plaintext)

return fmt.Sprintf("%x", ciphertext), nil
}
NodeJS代码:
protected decryptData(data: string) {
const iv = CryptoJS.enc.Hex.parse(data.substr(0,32))
const ct = CryptoJS.enc.Hex.parse(data.substr(32))
const key = CryptoJS.enc.Utf8.parse("6368616e676520746869732070617373")
// @ts-ignore !!!!!!!! IMPORTANT IF YOU USE TYPESCRIPT COMPILER
const decrypted = CryptoJS.AES.decrypt({ciphertext: ct}, key, {
mode: CryptoJS.mode.CBC,
iv: iv
})
console.log("Result : " + decrypted.toString(CryptoJS.enc.Utf8))
return decrypted.toString(CryptoJS.enc.Utf8)
}

最新更新