简体   繁体   English

Golang使用AES加密数据

[英]Golang encrypting data using AES

I'm not sure if this is the right place to ask this. 我不确定这是否是问这个问题的正确地方。 But I have no experience with C# and have been tasked to convert a security piece of code to Golang 但是我没有使用C#的经验,并且受过将安全代码转换为Golang的任务

I was wondering if i'm missing out on something here. 我想知道我是否错过了这里的东西。

The C# code uses a Rijndael class to encrypt a bit of data. C#代码使用Rijndael类来加密一些数据。 The key value and iv value is written out in the byte code like this 这样, 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[] // save structure as above with 16 in length

then theres a bit of code which does this 然后有一些代码可以做到这一点

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();

the function sends out byte[] data as output 该函数发送byte[] data作为输出

I'm trying to mimic this is golang like this 我试图模仿这是像这样的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
}

The Encryption function 加密功能

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
}

The output of this is sent over an API whose output needs to be decrypted. 此输出通过需要对其输出进行解密的API发送。 I'm using this below 我在下面使用

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
}

The decryptor gives me gibberish - Am i going wrong somewhere? 解密器给我带来乱码-我在哪里出错了?

My question boils down to 2 questions 我的问题归结为2个问题

  1. Would the C# function using the rijndael class and the golang functiony yield the same output or should i be doing something more/less 使用rijndael类和golang函数的C#函数会产生相同的输出还是我应该做更多/更少的事情

  2. Is the byte array the right data to store the key, IV in - ie its not the same used in C# when copied to GO 字节数组是存储密钥IV的正确数据吗-即复制到GO时在C#中使用的密钥与它不同

There's a few problems with the code you posted. 您发布的代码存在一些问题。

  1. Don't store the key in a byte array, because that means that you are hard-coding it. 不要将密钥存储在字节数组中,因为这意味着您正在对其进行硬编码。 Instead generate a random 256-bit key, encode it to a hex string, then store that outside of your program and read it in using a config library like viper . 而是生成一个随机的256位密钥,将其编码为十六进制字符串,然后将其存储程序之外 ,并使用viper之类的配置库将其读取。
  2. Don't hard-code the IV. 不要对IV进行硬编码。 You should be generating a new IV for every single message. 您应该为每条消息生成一个新的IV。 Reusing the same IV weakens your encryption significantly. 重复使用相同的IV将大大削弱您的加密。 For every message that you encrypt, generate a random IV and prepend it to the message. 对于您加密的每条消息,都会生成一个随机IV并将其添加到消息之前。 When you attempt to decrypt it, read the IV off of the first n bytes and then decrypt. 尝试解密时,请从前n个字节中读取IV,然后解密。
  3. You should use authenticated encryption as a measure of protection against chosen ciphertext attacks. 您应该使用经过身份验证的加密来防止所选密文攻击。 GCM mode provides authentication for you. GCM模式为您提供身份验证。

Here is an example. 这是一个例子。 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))
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM