angular - golang中AES解密的恐慌返回
问题描述
我已经在一个角度应用程序上实现了 AES 加密,它将加密的字符串发送到一个用 golang 编写的 REST api,然后解密它以验证它是否是有效的密钥。
加密和解密分别在 angular app 和 golang 上工作,但是当我们解密从 angular app 发送的字符串时,rest API 返回 Panic
以下是我在应用程序上的代码,用于在组件文件中加密
import * as CryptoJS from 'crypto-js';
var key = "NPZ8fvABP5pKwU3"; // passphrase used to encrypt
let encrypted_text = CryptoJS.AES.encrypt('Hello World', 'NPZ8fvABP5pKwU3');
当我使用以下代码对其进行解密时,它会在 Angular 应用程序上返回“Hello World”
var bytes = CryptoJS.AES.decrypt(encrypted_text.toString(), 'NPZ8fvABP5pKwU3');
var plaintext = bytes.toString(CryptoJS.enc.Utf8);
console.log(plaintext);
它无法在 main.go 文件中使用以下代码在 rest api 中返回相同的文本
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/md5"
"crypto/rand"
"encoding/hex"
"fmt"
"io"
)
func decrypt(data []byte, passphrase string) []byte {
key := []byte(createHash(passphrase))
block, err := aes.NewCipher(key)
if err != nil {
panic(err.Error())
}
gcm, err := cipher.NewGCM(block)
if err != nil {
panic(err.Error())
}
nonceSize := gcm.NonceSize()
nonce, ciphertext := data[:nonceSize], data[nonceSize:]
plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
panic(err.Error())
}
return plaintext
}
func main() {
key2 := "NPZ8fvABP5pKwU3"
key3 := []byte("encrypted string from angular app")
plaintext := decrypt(key3, key2)
fmt.Printf(string(plaintext))
}
func createHash(key string) string {
hasher := md5.New()
hasher.Write([]byte(key))
return hex.EncodeToString(hasher.Sum(nil))
}
https://play.golang.org/p/iGYyg0RB-Zi
返回错误
panic: cipher: message authentication failed
解决方案
您不需要使用 createHash 函数,只需使用密钥。问题是您的密钥长度为 15 个字节,而 aes.NewCipher 需要 16、24 或 32 个字节。只需更改您的密钥并使用此代码:
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/md5"
"encoding/hex"
"fmt"
)
func decrypt(data []byte, passphrase string) []byte {
key := []byte(passphrase)
block, err := aes.NewCipher(key)
if err != nil {
panic(err.Error())
}
gcm, err := cipher.NewGCM(block)
if err != nil {
panic(err.Error())
}
nonceSize := gcm.NonceSize()
nonce, ciphertext := data[:nonceSize], data[nonceSize:]
plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
panic(err.Error())
}
return plaintext
}
func main() {
key2 := "NPZ8fvABP5pKwU3"
key3 := []byte("encrypted string from angular app")
plaintext := decrypt(key3, key2)
fmt.Printf(string(plaintext))
}
推荐阅读
- linux - 使用固定种子随机播放 find 的输出
- javascript - 正则表达式不捕获多个字符
- android - 如何解决flutter_local_notifications PlatformException错误?
- firebase - 在 Firestore 控制台中按 id 查询
- xml - 如何使用 FLWOR 的 XQuery 返回一系列 XML 节点?
- alfresco - Alfresco 扩展类文件
- java - 使用 Java 流将对象列表拆分为多个字段值列表
- image - GDI+ Graphics.DrawImage() 方法中的半透明像素支持
- vba - 我收到运行时错误“429”。试图让 Excel 宏发送电子邮件
- image - 在 Flutter 中显示来自 RSS FEED元素的图像