登录
首页 >  Golang >  Go问答

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
}

解密器给我乱码 - 我在某个地方出错了吗?

我的问题归结为两个问题

  1. 使用 rijndael 类和 golang 函数的 c# 函数是否会产生相同的输出,或者我应该做更多/更少的事情

  2. 字节数组是否是存储密钥 iv 的正确数据 - 即复制到 go 时它与 c# 中使用的不同


解决方案


您发布的代码存在一些问题。

  1. 不要将密钥存储在字节数组中,因为这意味着您正在对其进行硬编码。相反,生成一个随机 256 位密钥,将其编码为十六进制字符串,然后将其存储在程序外部,并使用 viper 等配置库读取它。
  2. 不要对 iv 进行硬编码。您应该为每条消息生成一个新的 iv。重复使用相同的 iv 会显着削弱您的加密能力。对于您加密的每条消息,生成一个随机 iv 并将其添加到消息前面。当您尝试解密时,请读取前 n 个字节的 iv,然后解密。
  3. 您应该使用经过身份验证的加密作为针对选定密文攻击的防护措施。 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删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>