Python AES 加密提供与原始 C# 代码不同的结果

如何解决Python AES 加密提供与原始 C# 代码不同的结果

C# 代码使用 AES 来加密字节数组。

我已经使用 PyCryptodome 编写了一个 Python 程序来做同样的事情,但是当我使用 C# 代码时,加密的字节总是与结果不同,我确保:

  • 在两者中将 IV 设置为相同的值(仅用于测试目的)
  • 确保两者的密钥相同
  • 确保原始数据相同

我正在加密的内容:一个字节数组。字节主要代表 TLD 格式的数据。

Python 程序将成为一个实用程序的一部分,该实用程序将动态生成流,这些流将由用 C# 编写的 Web 应用程序处理。

使用 http://aes.online-domain-tools.com,我实际上可以解密 C# 代码生成的字节并验证它是否使用 AES,以及原始数据是否正确。

问题是:还有什么可能是判别因素?

Python 片段:

      from Crypto.Cipher import AES
      from Crypto import Random
      from Crypto.Util.Padding import pad

**** Correction ***
        aes_cipher = AES.new(bytes(key,'UTF-8'),AES.MODE_CBC)
#
# Correct,the above call would use a random IV value.
# For debugging & learning purpose,I halted this in the 
# debugger and manually set 
# aes_cipher.IV = <a given value>
# and used the same IV in the C# code to try and keep all known inputs identical.
# 
        aes_cipher.block_size = 128
        aes_cipher.key_size = 128   # bits
        encrypted_pack = aes_cipher.encrypt(pad(pack,16))

        # Tack on to the beginning the 16 bytes of the "IV"

        # FYI - the C# decryption function strips off the first 16 IV bytes
        encrypted_pack = aes_cipher.IV + encrypted_pack

        return encrypted_pack

C# 片段

            AesCipher = new RijndaelManaged();
            AesCipher.KeySize = 128;  // 192,256

            // BlockSize: 128-bit == 16 bytes. 
            // 128-bit is the default for RijndaelManaged
            AesCipher.BlockSize = 128;

            AesCipher.Mode = CipherMode.CBC;
            AesCipher.Padding = PaddingMode.Zeros;

...
...

# 
# Yes,GenerateIV() generates a random IV.
# As mentioned above,I overrode this by setting 
# AesCipher.IV = <the same value as above>
# 

                AesCipher.GenerateIV();                
                setKey(key);   // converts a string of decimal digits to string of hex digits  

                ICryptoTransform transform = AesCipher.CreateEncryptor();
                byte[] encrypted = transform.TransformFinalBlock(buf,buf.Length);
                byte[] result = new byte[encrypted.Length + 16];

                Buffer.BlockCopy(AesCipher.IV,result,16);
                Buffer.BlockCopy(encrypted,16,encrypted.Length);

                return result;


***
Update
***
There was another problem that I just discovered and fixed.
The key was being saved as a 32-byte rather than 16-byte bytearray,which would explain the gigantic discrepancy from online tool results.

Solved easiy with 
```byte_key = binascii.unhexlify(key)
Once I did that,the returned by both pieces of code matched,and they matched what was in the online tool,too.
Sneaky because in the debugger,it's easy to miss because the values look the same.

解决方法

AesCipher.GenerateIV() 正在生成一个随机 IV,如果我没记错的话。这与

不同

在两者中将 IV 设置为相同的值(仅用于测试目的)

Crypto.Util.Padding.pad 的默认填充是

style (string) – 填充算法。它可以是‘pkcs7’(默认)、‘iso7816’或‘x923’。

不同于:

AesCipher.Padding = PaddingMode.Zeros;

完整的 C# 和 Python 示例:

public static byte[] SimpleEncryptAesVariableLengthCbcZeros(string key,byte[] iv,byte[] plain)
{
    byte[] key2 = Encoding.UTF8.GetBytes(key);

    if (key.Length == 0 || key.Length > 32)
    {
        throw new ApplicationException("Illegal length for key");
    }

    int keySize = key2.Length <= 16 ? 128 : key2.Length <= 24 ? 192 : 256;

    using (var aesCipher = new RijndaelManaged())
    {
        aesCipher.KeySize = keySize;

        // BlockSize: 128-bit == 16 bytes. 
        // 128-bit is the default for RijndaelManaged
        aesCipher.BlockSize = 128;

        aesCipher.Mode = CipherMode.CBC;
        aesCipher.Padding = PaddingMode.Zeros;

        if (iv == null)
        {
            // IV as calculated by http://aes.online-domain-tools.com/
            // SHA1(key) truncated to 16 bytes
            iv = SHA1.HashData(key2);
            Array.Resize(ref iv,aesCipher.BlockSize / 8);
        }
        else if (iv.Length != aesCipher.BlockSize / 8)
        {
            throw new ApplicationException("Illegal length for IV");
        }

        aesCipher.IV = iv;

        // Key is padded with bytes set to 0
        Array.Resize(ref key2,aesCipher.KeySize / 8);
        aesCipher.Key = key2;

        using (var encryptor = aesCipher.CreateEncryptor())
        {
            var encrypted = encryptor.TransformFinalBlock(plain,plain.Length);

            var iv_encrypted = new byte[iv.Length + encrypted.Length];
            Array.Copy(iv,iv_encrypted,iv.Length);
            Array.Copy(encrypted,iv.Length,encrypted.Length);
            return iv_encrypted;
        }
    }
}

// https://stackoverflow.com/a/311179/613130
public static byte[] StringToByteArray(string hex)
{
    hex = hex.Replace(" ",string.Empty);

    byte[] bytes = new byte[hex.Length / 2];

    for (int i = 0; i < hex.Length; i += 2)
    {
        bytes[i / 2] = Convert.ToByte(hex.Substring(i,2),16);
    }

    return bytes;
}

public static string ByteArrayToString(byte[] bytes,string join)
{
    string res = string.Join(join,Array.ConvertAll(bytes,x => x.ToString("x2")));
    return res;
}


static void Main(string[] args)
{
    string key = "abcdefghabcdefghabcdefghabcdefgh";
    byte[] plain = StringToByteArray("0000000000000000000000000000000001");
    var res = SimpleEncryptAesVariableLengthCbcZeros(key,null,plain);
    var res2 = ByteArrayToString(res," ");
    Console.WriteLine(res2);
}

和(请注意,这可能是我一生中第二次或第三次编写 Python,所以我不太确定它的质量,而且它肯定没有优化):

from Crypto.Cipher import AES
from Crypto import Random
import hashlib 
#from Crypto.Util.Padding import pad

#key must be string
#iv must be bytes or None
#plain must be bytes
def SimpleEncryptAesVariableLengthCbcZeros(key,iv,plain):
    key2 = bytes(key,'UTF-8')
    
    if len(key2) == 0 or len(key2) > 32:
        raise Exception('Illegal length for key')

    keySize = 128 if len(key2) <= 16 else 192 if len(key2) <= 24 else 256

    if iv == None:
        #IV as calculated by http://aes.online-domain-tools.com/
        #SHA1(key) truncated to 16 bytes
        h = hashlib.sha1()
        h.update(key2)

        iv = h.digest()
        iv = iv[0:16]
    elif len(iv) != 128 // 8:
        raise Exception('Illegal length for iv')

    #Key is padded with bytes set to 0
    key2 = key2 + b'\0' * (keySize // 8 - len(key2))

    aes_cipher = AES.new(key2,AES.MODE_CBC,iv)

    aes_cipher.key_size = keySize
    aes_cipher.block_size = 128

    padded = plain
    
    #zero padding
    if len(padded) % 16 != 0:
        padded = padded + b'\0' * (16 - len(padded) % 16)

    encrypted = aes_cipher.encrypt(bytes(padded))

    iv_encrypted = iv + encrypted

    return iv_encrypted

key = 'abcdefghabcdefghabcdefghabcdefgh'
plain = bytearray.fromhex('0000000000000000000000000000000001')
iv_encrypted = SimpleEncryptAesVariableLengthCbcZeros(key,None,plain)
print(' '.join(["{:02x}".format(x) for x in iv_encrypted]))

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

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-