C#RijndaelManaged vs Python加密密码AES+CBC

2024-05-29 04:54:30 发布

您现在位置:Python中文网/ 问答频道 /正文

几天来,我一直把头撞在墙上,希望有人能指出显而易见的问题。我正在尝试使用Crypto.Cipher将C#的RijndaelManaged加密与Python的加密进行匹配

问题: 尽管一切都是平等的,但我收到了两种不同的加密输出。

以下是传递的值:

  • 加密密钥为字符串(32个字符)
  • 要加密的值已填充为字符串(在本例中为32个字符)

Python 3:

import os
import base64
from Crypto.Cipher import AES

iv = 'wdp0hP2WRKWsuP8B'

def fix_binary_data_length(binary_value):
  block_length = 16
  binary_value_length = len(binary_value)
  length_with_padding = (
    binary_value_length + (block_length - binary_value_length) % block_length
  )
  return binary_value.ljust(length_with_padding, b'=')

def encrypt(value: str, key: str):
  binary_iv = iv.encode('UTF-8')
  binary_value = value.encode('UTF-8')
  binary_value = fix_binary_data_length(binary_value)
  binary_key = key.encode('UTF-8')
  cipher = AES.new(binary_key, AES.MODE_CBC, binary_iv)
  encrypted_value = cipher.encrypt(binary_value)
  return encrypted_value

#

using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

public class Crypt {

  public static string encrypt(string _sValue, string _sKey){
    string _sIv = "wdp0hP2WRKWsuP8B";
    if (_sKey.Length != 32) { return string.Empty; }
    using (RijndaelManaged _Rijndael = new RijndaelManaged(){
      Mode = CipherMode.CBC,
      KeySize = 256,
      BlockSize = 128
    }){
      byte[] _chEncrypt = Encoding.UTF8.GetBytes(_sValue);
      using (ICryptoTransform _Encryptor = _Rijndael.CreateEncryptor(Encoding.UTF8.GetBytes(_sKey), Encoding.UTF8.GetBytes(_sIv)))
      using (MemoryStream _Stream = new MemoryStream())
      using (CryptoStream _CryptoStream = new CryptoStream(_Stream, _Encryptor, CryptoStreamMode.Write)){
        _CryptoStream.Write(_chEncrypt, 0, _chEncrypt.Length);
        _CryptoStream.FlushFinalBlock();
        return Convert.ToBase64String(_Stream.ToArray());
      }
    }
    return string.Empty;
  }
}

Tags: keyimportnewstringreturnvalueblocksystem
1条回答
网友
1楼 · 发布于 2024-05-29 04:54:30

感谢@Topaco指出了显而易见的问题;)

似乎我没有完全掌握填充的概念。我就是这样让它工作的:

import os
import base64
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad

iv = 'wdp0hP2WRKWsuP8B'

def encrypt(value: str, key: str):
  binary_iv = iv.encode('UTF-8')
  binary_value = value.encode('UTF-8')
  binary_key = key.encode('UTF-8')
  cipher = AES.new(binary_key, AES.MODE_CBC, binary_iv)
  encrypted_value = cipher.encrypt(pad(binary_value, AES.block_size))
  encrypted_value = base64.b64encode(encrypted_value)
  return encrypted_value

相关问题 更多 >

    热门问题