登录
首页 >  Golang >  Go问答

使用AES算法进行CBC模式加密

来源:stackoverflow

时间:2024-02-24 20:48:26 124浏览 收藏

本篇文章给大家分享《使用AES算法进行CBC模式加密》,覆盖了Golang的常见基础知识,其实一个语言的全部知识点一篇文章是不可能说完的,但希望通过这些问题,让读者对自己的掌握程度有一定的认识(B 数),从而弥补自己的不足,更好的掌握它。

问题内容

问题

我必须将函数从 c# 移植到 go,该函数使用 aes 加密。 显然我必须使用 go 得到与 c# 得到的相同结果

c#

代码小提琴

我用 c# 准备了一个小小提琴

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]

开始

代码小提琴

我准备了一个小小提琴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(加密) 将十六进制字符串转换为 []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 代码中,填充必须显式完成,这是通过 pkcs5padding() 方法完成的,该方法实现了 pkcs7 填充。 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...)
}

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>