Golang 使用 AES 加密数据

Kan*_*naj 0 c# aes rijndael go

我不确定这是问这个问题的合适地方。但我没有 C# 经验,我的任务是将一段安全代码转换为 Golang

我想知道我是否在这里错过了一些东西。

C# 代码使用Rijndael类来加密一位数据。valuekeyivvalue是这样用字节码写出来的

   public static byte[] Key = new byte[]{0xx, 0xx, 0xx, 0xx, 0xx,
                    0xx4, 0xxx, 0xxx, 0xxx, 0xxx, xxx, 0xxx,
                    0xxx, 0xxx, 0xxx, 0xxx};
Run Code Online (Sandbox Code Playgroud)

public static byte[] IV = new byte[] // save structure as above with 16 in length

然后有一些代码可以做到这一点

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();
Run Code Online (Sandbox Code Playgroud)

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
}
Run Code Online (Sandbox Code Playgroud)

加密功能

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
}
Run Code Online (Sandbox Code Playgroud)

其输出通过 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
}
Run Code Online (Sandbox Code Playgroud)

解密器给我乱码——我是不是哪里出错了?

我的问题归结为两个问题

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

  2. 字节数组是否是存储密钥的正确数据,IV in - 也就是说,当复制到 GO 时,它与 C# 中使用的不同

Bri*_*ams 5

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

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

这是一个例子。游乐场链接

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))
}
Run Code Online (Sandbox Code Playgroud)