Golang 使用 AES 加密数据
来源:stackoverflow
时间:2024-04-03 21:12:35 346浏览 收藏
你在学习Golang相关的知识吗?本文《Golang 使用 AES 加密数据》,主要介绍的内容就涉及到,如果你想提升自己的开发能力,就不要错过这篇文章,大家要知道编程理论基础和实战操作都是不可或缺的哦!
问题内容
我不确定这是问这个问题的合适地方。但我没有 c# 经验,我的任务是将一段安全代码转换为 golang
我想知道我是否在这里错过了一些东西。
c# 代码使用 rijndael 类来加密一位数据。 key值和iv值在字节码中写出来是这样的
public static byte[] key = new byte[]{0xx, 0xx, 0xx, 0xx, 0xx,
0xx4, 0xxx, 0xxx, 0xxx, 0xxx, xxx, 0xxx,
0xxx, 0xxx, 0xxx, 0xxx};
public static byte[] iv = new byte[] // 保存结构如上,长度为16
然后有一些代码可以做到这一点
rijndael alg = rijndael.create();
alg.key = key;
alg.iv = iv;
cryptostream cs = new cryptostream(ms,
alg.createencryptor(), cryptostreammode.write);
cs.write(datawithoutheader, 0, datawithoutheader.length);
cs.close();
该函数发送 byte[] data 作为输出
我试图模仿这是 golang 像这样
func startencryption(message []byte) []byte {
var key = []byte {// same as c# }
var iv = []byte{ // same as c# }
var err error
fmt.printf("\n length of key %+v \n, \n length of iv \n %+v \n", len(key), len(iv))
// encrypt
encrypted := make([]byte, len(message))
err = encryptaescfb(encrypted, []byte(message), key, iv)
if err != nil {
panic(err)
}
return encrypted
}
加密函数
func encryptaescfb(dst, src, key, iv []byte) error {
aesblockencrypter, err := aes.newcipher([]byte(key))
if err != nil {
return err
}
aesencrypter := cipher.newcfbencrypter(aesblockencrypter, iv)
aesencrypter.xorkeystream(dst, src)
return nil
}
其输出是通过 api 发送的,其输出需要解密。我在下面使用这个
func decryptMessage(message []byte)error{
var key = []byte{ // same as C# }
var iv = []byte{ // same as C# }
// Remove the head part of the response (45 bytes)
responseBody := message[45:]
decrypted := make([]byte, len(responseBody))
err := DecryptAESCFB(decrypted, responseBody, key, iv)
if err != nil {
fmt.Printf("\n error : \n %+v \n", err)
}
return nil
}
func DecryptAESCFB(dst, src, key, iv []byte) error {
aesBlockDecrypter, err := aes.NewCipher([]byte(key))
if err != nil {
return nil
}
aesDecrypter := cipher.NewCFBDecrypter(aesBlockDecrypter, iv)
aesDecrypter.XORKeyStream(dst, src)
return nil
}
解密器给我乱码 - 我在某个地方出错了吗?
我的问题归结为两个问题
使用
rijndael类和 golang 函数的 c# 函数是否会产生相同的输出,或者我应该做更多/更少的事情字节数组是否是存储密钥 iv 的正确数据 - 即复制到 go 时它与 c# 中使用的不同
解决方案
您发布的代码存在一些问题。
- 不要将密钥存储在字节数组中,因为这意味着您正在对其进行硬编码。相反,生成一个随机 256 位密钥,将其编码为十六进制字符串,然后将其存储在程序外部,并使用 viper 等配置库读取它。
- 不要对 iv 进行硬编码。您应该为每条消息生成一个新的 iv。重复使用相同的 iv 会显着削弱您的加密能力。对于您加密的每条消息,生成一个随机 iv 并将其添加到消息前面。当您尝试解密时,请读取前 n 个字节的 iv,然后解密。
- 您应该使用经过身份验证的加密作为针对选定密文攻击的防护措施。 gcm 模式为您提供身份验证。
这是一个例子。 Playground Link
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/hex"
"fmt"
"os"
)
var (
key = randBytes(256 / 8)
gcm cipher.AEAD
nonceSize int
)
// Initilze GCM for both encrypting and decrypting on program start.
func init() {
block, err := aes.NewCipher(key)
if err != nil {
fmt.Printf("Error reading key: %s\n", err.Error())
os.Exit(1)
}
fmt.Printf("Key: %s\n", hex.EncodeToString(key))
gcm, err = cipher.NewGCM(block)
if err != nil {
fmt.Printf("Error initializing AEAD: %s\n", err.Error())
os.Exit(1)
}
nonceSize = gcm.NonceSize()
}
func randBytes(length int) []byte {
b := make([]byte, length)
rand.Read(b)
return b
}
func encrypt(plaintext []byte) (ciphertext []byte) {
nonce := randBytes(nonceSize)
c := gcm.Seal(nil, nonce, plaintext, nil)
return append(nonce, c...)
}
func decrypt(ciphertext []byte) (plaintext []byte, err error) {
if len(ciphertext) < nonceSize {
return nil, fmt.Errorf("Ciphertext too short.")
}
nonce := ciphertext[0:nonceSize]
msg := ciphertext[nonceSize:]
return gcm.Open(nil, nonce, msg, nil)
}
func main() {
fmt.Println("Encrypting...")
msg := []byte("The quick brown fox jumped over the lazy dog.")
ciphertext := encrypt(msg)
fmt.Printf("Encrypted message: %v\n", ciphertext)
fmt.Println("Decrypting...")
plaintext, err := decrypt(ciphertext)
if err != nil {
// Don't display this message to the end-user, as it could potentially
// give an attacker useful information. Just tell them something like "Failed to decrypt."
fmt.Printf("Error decryping message: %s\n", err.Error())
os.Exit(1)
}
fmt.Printf("Decrypted message: %s\n", string(plaintext))
}
以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。
声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
-
502 收藏
-
502 收藏
-
501 收藏
-
501 收藏
-
501 收藏
最新阅读
更多>
-
139 收藏
-
204 收藏
-
325 收藏
-
478 收藏
-
486 收藏
-
439 收藏
-
357 收藏
-
352 收藏
-
101 收藏
-
440 收藏
-
212 收藏
-
143 收藏
课程推荐
更多>
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 485次学习