c# - 进行 AES 加密 CBC

标签 c# go encryption aes cbc-mode

问题

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

相同的结果

C#

代码 fiddle

我用C#准备了一个小的fiddle

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 代码中添加了填充),但结果不同。
获得相同结果的解决方案会很棒

最佳答案

首先,两个代码的密文是相同的。但是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(加密) 将十六进制字符串转换为 []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() 方法的第二个参数是 block 大小,对于 AES 为 16 字节。对于这个参数,实际上应该传递aes.BlockSize。目前,此处传递len(key),对于 AES-256,其大小为 32 字节。虽然这与当前明文长度的 C# 代码兼容,但它与任意明文长度(例如 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...)
}

关于c# - 进行 AES 加密 CBC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66583084/

相关文章:

java - AES-256 可以在 API 级别 26+ 的 Android 设备上工作吗?

c# - WCF 抛出异常

c - BPF 尾调用未调用

Java rsa解密模式行为

索引中结构的 Golang 模板属性

go - 未实现的 desc = 未知服务 protos.ChaincodeSupport

android - Android API 24 及更低版本上的 PBKDF2WithHmacSHA256

c# - 在 C# 中解压 4gb 文件

c# - 我怎样才能知道 .NET 线程占用的资源?

c# - 使商业软件更难破解应遵循的惯例?