Python模数公钥加密转C#

文章介绍了如何在Python中使用Crypto库进行RSA加密,特别是使用公钥模数对内容加密的函数`encrypt_with_modulus`。同时,展示了C#端如何使用RSACryptoServiceProvider进行相同的RSA加密操作,涉及大整数解析和加密过程。
摘要由CSDN通过智能技术生成
因为需要对接API,有部分是Python写的,查了资料看到人家遇到了相同的问题,做一下笔记记录一下。
Python部分:
#!-*- coding:utf8 -*-
from binascii import a2b_hex , b2a_hex
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
from Crypto.Util.number import bytes_to_long
def encrypt_with_modulus ( content , modulus = None ):
u""" 使用模数对文本进行加密
:param content: 待加密内容,例如密码
:param modulus: 公钥模数,需要调用 get-public—key 接口获取
:return: 加密后的 content
"""
content = content . encode ( 'utf-8' )
e = int ( 0x10001 )
n = bytes_to_long ( a2b_hex ( modulus ))
rsa_key = RSA . construct (( n , e ))
# generate/export public key
public_key = rsa_key . publickey ()
cipher = PKCS1_v1_5 . new ( public_key )
content = cipher . encrypt ( content )
content = b2a_hex ( content )
return str ( content . decode ( 'utf-8' ))

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(content);
                var encryptReuslt = RSA.Encrypt(passwordByte, RSAEncryptionPadding.Pkcs1);
                //var Ciphertext = Convert.ToBase64String(encryptReuslt);
                var encrypted = BitConverter.ToString(encryptReuslt).Replace("-", "");
                //encrypted = GetHexFromChs(Ciphertext);
            }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值