微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

去AES加密CBC

如何解决去AES加密CBC

问题

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

相同的结果

C#

代码小提琴

我用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,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机智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 代码添加了 Padding),但结果不同。
获得 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 将十六进制字符串转换为 []byte(encrypted) 时,会进行 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 字节。尽管这与当前明文长度的 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...)
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。