CSharp和Golang之间的AES-CFB实现不一致

时间:2018-10-13 10:32:20

标签: c# go cryptography aes

我无法使用Golang解密使用CSharp加密的字符串,因为我认为CSharp使用CFB8和Golang CFB128(反馈大小)。 但是,如果我将CSharp与FeedbackSize = 128一起使用,那么我需要使用Padding,结果我也将在加密的文本中使用它(Golang没有),反之亦然,我无法在Golang中使用FeedbackSize = 8,因为未实现。

有什么主意吗?

CSharp代码:

static void Main(string[] args)
    {
        byte[] msg = Encoding.UTF8.GetBytes("Message to encrypt");
        byte[] k = Encoding.UTF8.GetBytes("0123456789abcdef");
        byte[] iv = Encoding.UTF8.GetBytes("0123456789abcdef");
        using (RijndaelManaged Aes128 = new RijndaelManaged())
        {
            Aes128.BlockSize = 128;
            Aes128.KeySize = 128;
            Aes128.Mode = CipherMode.CFB;
            Aes128.FeedbackSize = 8;
            Aes128.Padding = PaddingMode.Zeros;
            Aes128.Key = k;
            Aes128.IV = iv;

            using (var encryptor = Aes128.CreateEncryptor())
            using (var msEncrypt = new MemoryStream())
            using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))

            using (var bw = new BinaryWriter(csEncrypt, Encoding.UTF8))
            {
                bw.Write(msg);
                bw.Close();
                msg = msEncrypt.ToArray();
                Console.WriteLine("Encrypted " + BitConverter.ToString(msg));
            }
        }
    }

结果:

Encrypted 3F-D6-AD-8E-D5-34-E6-2D-38-7B-38-4E-DE-72-E8-B1-42-1C

Golang代码:

    package main
import (
    "crypto/aes"
    "crypto/cipher"
    "fmt"
)
func main() {
    msg := []byte("Message to encrypt")
    k := []byte("0123456789abcdef")
    iv := []byte("0123456789abcdef")
    {
        block, _ := aes.NewCipher(k)
        stream := cipher.NewCFBEncrypter(block, iv)
        stream.XORKeyStream(msg, msg)
        fmt.Printf("Encrypted %x\n", msg)
    }
}

结果:

Encrypted 3f170dfb7fbb982174c8380d176ac71c89ac

注意:如果我更改为Aes128.FeedbackSize = 128,则会收到错误消息,因为我不使用填充,如果使用填充,则会得到以下结果:

Encrypted 3F-17-0D-FB-7F-BB-98-21-74-C8-38-0D-17-6A-C7-1C-89-AC-F2-4F-9A-1D-E8-0B-D4-40-21-60-AF-48-36-5F

非常感谢。

1 个答案:

答案 0 :(得分:1)

CFB不需要填充,但是您始终可以在GoLang中实现填充,从而避免RijndaelManaged实现的愚蠢性。只需在加密前应用填充,在解密后应用填充。 .NET库默认使用PKCS#7填充。