走AES加密CBC

go AES encryption CBC

问题

我必须将函数从 C# 移植到 GO,它使用 AES 加密。 显然,我必须使用 GO 获得与使用 C#

相同的结果

C#

代码fiddle

我准备了一个小fiddleC#

using System;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

public class Program
{
    public static void Main()
    {
        var query = "csharp -> golang";
        var key = Encoding.UTF8.GetBytes("12345678901234567890123456789012");
        var iv = Encoding.UTF8.GetBytes("1234567890123456");
        using (var aes = (RijndaelManaged)RijndaelManaged.Create())
        {
            aes.KeySize = 256;
            aes.Mode = CipherMode.CBC;
            aes.Key = key;
            aes.IV = iv;
            using (var transform = aes.CreateEncryptor())
            {
                Console.WriteLine("query => " + query);
                var toEncodeByte = Encoding.UTF8.GetBytes(query);
                Console.WriteLine("toEncodeByte = " + ToString(toEncodeByte));
                var encrypted = transform.TransformFinalBlock(toEncodeByte, 0, toEncodeByte.Length);
                Console.WriteLine("encrypted = " + ToString(encrypted));
            }
        }
    }

    public static string ToString(byte[] b)
    {
        return "[" + String.Join(" ", b.Select(h => h.ToString())) + "]";
    }
}

控制台输出

query => csharp -> golang
toEncodeByte = [99 115 104 97 114 112 32 45 62 32 103 111 108 97 110 103]
encrypted = [110 150 8 224 44 118 15 182 248 172 105 14 61 212 219 205 216 31 76 112 179 76 214 154 227 112 159 176 24 61 108 100]

开始

代码fiddle

我准备了一个小fiddle机智GO

package main

import (
    "bytes"
    "crypto/aes"
    "crypto/cipher"
    "encoding/hex"
    "fmt"
)

func main() {
    query := "csharp -> golang"
    key := []byte("12345678901234567890123456789012")
    iv := []byte("1234567890123456")

    if len(key) != 32 {
        fmt.Printf("key len must be 16. its: %v\n", len(key))
    }
    if len(iv) != 16 {
        fmt.Printf("IV len must be 16. its: %v\n", len(iv))
    }
    var encrypted string
    toEncodeByte := []byte(query)
    fmt.Println("query =>", query)
    fmt.Println("toEncodeByte = ", toEncodeByte)
    toEncodeBytePadded := PKCS5Padding(toEncodeByte, len(key))

    // aes
    block, err := aes.NewCipher(key)
    if err != nil {
        fmt.Println("CBC Enctryping failed.")
    }
    ciphertext := make([]byte, len(toEncodeBytePadded))
    mode := cipher.NewCBCEncrypter(block, iv)
    mode.CryptBlocks(ciphertext, toEncodeBytePadded)
    encrypted = hex.EncodeToString(ciphertext)
    // end of aes
    fmt.Println("encrypted", []byte(encrypted))
}

func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
    padding := (blockSize - len(ciphertext)%blockSize)
    padtext := bytes.Repeat([]byte{byte(padding)}, padding)
    return append(ciphertext, padtext...)
}

控制台输出

query => csharp -> golang
toEncodeByte =  [99 115 104 97 114 112 32 45 62 32 103 111 108 97 110 103]
encrypted [54 101 57 54 48 56 101 48 50 99 55 54 48 102 98 54 102 56 97 99 54 57 48 101 51 100 100 52 100 98 99 100 100 56 49 102 52 99 55 48 98 51 52 99 100 54 57 97 101 51 55 48 57 102 98 48 49 56 51 100 54 99 54 52]

总结

我注意到在 C# 中输入的大小不必与 block 相同。
GO 中,如果没有填充,这似乎不起作用(因此我在 GO 代码中添加了填充)但结果不同。
获得 equal 结果的解决方案会很棒

首先,两个密码的密文是一样的。但是Golang代码中的密文转换错误

在 C# 代码中,byte[] 的内容以十进制格式打印。要在 Golang 代码中获得等效的输出,[]byte 的内容也必须以十进制格式打印,这很容易实现:

fmt.Println("ciphertext ", ciphertext)

并产生以下输出:

ciphertext  [110 150 8 224 44 118 15 182 248 172 105 14 61 212 219 205 216 31 76 112 179 76 214 154 227 112 159 176 24 61 108 100]

并且与 C# 代码的输出相同。


在当前代码中,密文首先编码为:

encrypted = hex.EncodeToString(ciphertext)

转换为十六进制字符串,可以通过以下方式轻松验证:

fmt.Println("encrypted (hex)", encrypted)

生成以下输出:

encrypted (hex) 6e9608e02c760fb6f8ac690e3dd4dbcdd81f4c70b34cd69ae3709fb0183d6c64

当使用 []byte(encrypted) 将十六进制字符串转换为 []byte 时,会发生 Utf8 编码,使数据大小加倍,作为输出:

fmt.Println("encrypted", []byte(encrypted))

在当前代码中显示:

encrypted [54 101 57 54 48 56 101 48 50 99 55 54 48 102 98 54 102 56 97 99 54 57 48 101 51 100 100 52 100 98 99 100 100 56 49 102 52 99 55 48 98 51 52 99 100 54 57 97 101 51 55 48 57 102 98 48 49 56 51 100 54 99 54 52]

CBC是块密码模式,即明文长度必须是块大小的整数倍(AES为16字节)。如果不是这种情况,则必须应用填充。 C# 代码隐式 使用 PKCS7 填充。这就是不满足长度条件的明文也被处理的原因。

相比之下,在 Golang 代码中填充必须 显式完成 ,这是通过实现 PKCS7 填充的 PKCS5Padding() 方法完成的。 PKCS5Padding() 方法的第二个参数是块大小,对于 AES 是 16 个字节。对于这个参数实际上应该传递 aes.BlockSize 。当前,len(key) 在这里传递,对于 AES-256,它的大小为 32 字节。虽然这与 current 明文长度的 C# 代码兼容,但它不兼容 arbitrary 明文长度(例如 32 字节)。


以下代码包含上述更改和输出:

package main

import (
    "bytes"
    "crypto/aes"
    "crypto/cipher"
    "encoding/hex"
    "fmt"
)

func main() {
    query := "csharp -> golang"
    key := []byte("12345678901234567890123456789012")
    iv := []byte("1234567890123456")

    if len(key) != 32 {
        fmt.Printf("key len must be 16. its: %v\n", len(key))
    }
    if len(iv) != 16 {
        fmt.Printf("IV len must be 16. its: %v\n", len(iv))
    }
    var encrypted string
    toEncodeByte := []byte(query)
    fmt.Println("query =>", query)
    fmt.Println("toEncodeByte = ", toEncodeByte)
    toEncodeBytePadded := PKCS5Padding(toEncodeByte, aes.BlockSize)

    // aes
    block, err := aes.NewCipher(key)
    if err != nil {
        fmt.Println("CBC Enctryping failed.")
    }
    ciphertext := make([]byte, len(toEncodeBytePadded))
    mode := cipher.NewCBCEncrypter(block, iv)
    mode.CryptBlocks(ciphertext, toEncodeBytePadded)
    encrypted = hex.EncodeToString(ciphertext)
    // end of aes
    fmt.Println("encrypted", []byte(encrypted))
    fmt.Println("encrypted (hex)", encrypted)
    fmt.Println("ciphertext", ciphertext)
    fmt.Println("aes.BlockSize", aes.BlockSize)
}

func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
    padding := (blockSize - len(ciphertext)%blockSize)
    padtext := bytes.Repeat([]byte{byte(padding)}, padding)
    return append(ciphertext, padtext...)
}