如何将 Python RSA 加密代码转换为 C# 代码?
本文旨在提供一段 python rsa 加密代码到 c# 的转换示例。
python 代码如下:
from rsa import key, common, transform, core, pkcs1 def get_rsa_encrypt(rsa_key, txt): pub_key = key.publickey(int(rsa_key, 16), 65537) key_length = common.byte_size(pub_key.n) padded = pkcs1._pad_for_encryption(txt, key_length) payload = transform.bytes2int(padded) encrypted = core.encrypt_int(payload, pub_key.e, pub_key.n) encode_str = hex(encrypted)[2:-1] if len(encode_str) % 2 != 0: encode_str = '0{}'.format(encode_str) return encode_str
c# 代码转换
//公钥大素数 BigInteger biE = BigInteger.Parse(rsa_key, System.Globalization.NumberStyles.HexNumber); //大整数N BigInteger biN = BigInteger.Parse("10001", System.Globalization.NumberStyles.HexNumber); byte[] publicKeyByte2 = biE.ToByteArray(); byte[] exponentByte2 = biN.ToByteArray(); using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider()) { RSAParameters RSAKeyInfo = new RSAParameters(); UTF8Encoding ByteConverter = new UTF8Encoding(); RSAKeyInfo.Modulus = publicKeyByte2.Reverse().ToArray(); RSAKeyInfo.Exponent = exponentByte2.Reverse().ToArray(); RSA.ImportParameters(RSAKeyInfo); byte[] passwordByte = ByteConverter.GetBytes(txt); var encryptReuslt = RSA.Encrypt(passwordByte, RSAEncryptionPadding.Pkcs1); //var Ciphertext = Convert.ToBase64String(encryptReuslt); encrypted = BitConverter.ToString(encryptReuslt).Replace("-", ""); //encrypted = GetHexFromChs(Ciphertext); }