RsaHelper.cs for C# 非对称加密RSA 附调用方法及测试key

本文档介绍了如何使用RSAHelper类进行公钥和私钥的加密与解密操作,包括Encrypte和Decrypte方法,以及将RSA参数转换为XML字符串的实用函数。示例代码展示了如何使用默认和自定义参数进行加密和解密操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public static class RsaHelper
    {
        public static byte[] Encrypte(byte[] source, string publicKeyXml, int keyLength, bool oaep)
        {
            publicKeyXml = "your key";
            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(keyLength))
            {
                try
                {
                    rsa.InitializeFromXmlString(publicKeyXml);
                }
                catch(Exception ex)
                {
                    //ShowError("密钥格式有误", "加密失败", ex);
                }
                return Encrypte(source, rsa,oaep);
            }
        }
        
        public static byte[] Encrypte(byte[] source, RSAParameters parameters, bool oaep)
        {
            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(parameters.Modulus.Length * 8))
            {
                rsa.ImportParameters(parameters);
                return Encrypte(source, rsa, oaep);
            }

        }

        private static byte[] Encrypte(byte[] source, RSACryptoServiceProvider rsa, bool oaep)
        {
            List<byte> encrypted = new List<byte>();
            MemoryStream msInput = new MemoryStream(source);
            int bufferSize = rsa.KeySize / 8 - 11;
            byte[] buffer = new byte[bufferSize];
            int length = msInput.Read(buffer, 0, bufferSize);
            try
            {
                while (length > 0)
                {
                    if (length == bufferSize)
                    {
                        encrypted.AddRange(rsa.Encrypt(buffer, oaep));
                    }
                    else
                    {
                        byte[] current = new byte[length];
                        Array.Copy(buffer, current, length);
                        encrypted.AddRange(rsa.Encrypt(current, oaep));
                    }
          &n

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值