我必须使用 golang 将数据发送到具有 nodejs 加密的现有(遗留)服务,该服务将使用 AES CTR 模式和 Crypto JS libray 解密数据。我做了一些代码如下(密钥加密是这个问题中的随机密钥)。
高朗加密:
func main() {
rawKey := "46ca2a49c8074dadb99843f6b86c5975"
data := "the quick brown fox jumps over the lazy dog"
encryptedData := encrypt(rawKey, data);
fmt.Println("encrypted data: ", encryptedData)
}
func encrypt(rawKey string, data string) string {
key := []byte(rawKey)
plainText := []byte(data)
// Create new AES cipher block
block, err := aes.NewCipher(key)
if err != nil {
return err.Error()
}
// The IV (Initialization Vector) need to be unique, but not secure.
// Therefore, it's common to include it at the beginning of the cipher text.
cipherText := make([]byte, aes.BlockSize+len(plainText))
// Creates IV.
iv := cipherText[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return err.Error()
}
// Encrypt.
encryptStream := cipher.NewCTR(block, iv)
encryptStream.XORKeyStream(cipherText[aes.BlockSize:], plainText)
ivHex := hex.EncodeToString(iv)
encryptedDataHex := hex.EncodeToString(cipherText)
return encryptedDataHex[0:len(ivHex)] + ":" + encryptedDataHex[len(ivHex):]
}
慕侠2389804
相关分类