使用AES加密在Golang和Flutter之间进行安全通信
时间:2024-02-18
浏览:131
作者:佚名
从现在开始,我们要努力学习啦!今天我给大家带来《使用AES加密在Golang和Flutter之间进行安全通信》,感兴趣的朋友请继续看下去吧!下文中的内容我们主要会涉及到等等知识点,如果在阅读本文过程中有遇到不清楚的地方,欢迎留言呀!我们一起讨论,一起学习!
我有一个 golang 代码,可以对给定数据进行 aes 加密并为其提供服务。下面是代码。
crypt.go
func encrypt(key []byte, text string) string {
plaintext := []byte(text)
block, err := aes.newcipher(key)
if err != nil {
panic(err)
}
ciphertext := make([]byte, aes.blocksize+len(plaintext))
iv := ciphertext[:aes.blocksize]
if _, err := io.readfull(rand.reader, iv); err != nil {
panic(err)
}
stream := cipher.newcfbencrypter(block, iv)
stream.xorkeystream(ciphertext[aes.blocksize:], plaintext)
return base64.urlencoding.encodetostring(ciphertext)
}
func decrypt(key []byte, cryptotext string) string {
ciphertext, _ := base64.urlencoding.decodestring(cryptotext)
block, err := aes.newcipher(key)
if err != nil {
panic(err)
}
if len(ciphertext) < aes.blocksize {
panic("ciphertext too short")
}
iv := ciphertext[:aes.blocksize]
ciphertext = ciphertext[aes.blocksize:]
stream := cipher.newcfbdecrypter(block, iv)
stream.xorkeystream(ciphertext, ciphertext)
return string(ciphertext)
}
我需要在 flutter 中处理相同的解密和加密。我使用 flutter 加密包尝试了以下代码。
crypt.dart
import 'package:encrypt/encrypt.dart';
String encryption(String plainText) {
final key = Key.fromBase64(ENCRYPTION_KEY);
final iv = IV.fromBase64(ENCRYPTION_IV);
final encrypter = Encrypter(AES(key, mode: AESMode.cfb64, padding: null));
final encrypted = encrypter.encrypt(plainText, iv: iv);
return encrypted.base64;
}
String decryption(String plainText) {
final key = Key.fromBase64(ENCRYPTION_KEY);
final iv = IV.fromBase64(ENCRYPTION_IV);
final encrypter = Encrypter(AES(key, mode: AESMode.cfb64, padding: null));
final decrypted = encrypter.decrypt(Encrypted.from64(plainText), iv: iv);
return decrypted;
}
但是我收到错误并且无法正常工作。我错过了什么吗? 如何在 flutter 端实现这一点。
提前致谢
正确答案
乍一看,您的 iv (初始化向量)似乎不匹配。在 Go 中加密时,您随机生成它并将其“放置”在加密文本前面,这很好,而在 Go 中解密时,您可以从那里取出它。
在 Dart 中(虽然我不习惯这种语言),似乎您从 ENCRYPTION_IV 获取静态 iv。该值与 Go 随机生成的值不匹配。
想象 iv 是某种谱号。它解释了如何处理加密的密钥。通常它不是秘密的,但应该是随机的。因此,可以使用适当的随机发生器生成它,并将其告知加密文本的接收者。一种常见的方法是把它放在前面 - 因为它的大小在 AES 中固定为 aes.BlockSize (16 字节),所以很清楚 iv 结束和真正的加密文本开始。
因此,在 Dart 中,您应该读取前 16 个字节,以从 Go 加密的密文中获取 iv。当您使用它时,我也建议在 Dart 加密方法中使用随机 iv。
好了,本文到此结束,带大家了解了《使用AES加密在Golang和Flutter之间进行安全通信》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
站内热门
最新文章
热门专题
