C#实现RSA加密和解密详解

 

项目要求,生成一个private key 和 public key ,用 Public Key 加密,用Private key 解密,我是这样实现的,

 

希望对有这方面需求朋友的一个帮助.

 

  

 

  源代码如下:

 

1.生成一对keys:

 

          /// <summary>
        /// generate private key and public key arr[0] for private key arr[1] for public key
        /// </summary>
        /// <returns></returns>
        public static string[] GenerateKeys()
        {
            string[] sKeys = new String[2];
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            sKeys[0] = rsa.ToXmlString(true);
            sKeys[1] = rsa.ToXmlString(false);
            return sKeys;
        } 

 

2.加密:

 

      /// <summary>
        /// RSA Encrypt
        /// </summary>
       /// <param name="sSource" >Source string</param>
        /// <param name="sPublicKey" >public key</param>
        /// <returns></returns>
        public static  string EncryptString(string sSource,string sPublicKey)
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            string plaintext = sSource;
            rsa.FromXmlString(sPublicKey);
            byte[] cipherbytes;
            byte[] byteEn = rsa.Encrypt(Encoding.UTF8.GetBytes("a"), false);
            cipherbytes = rsa.Encrypt(Encoding.UTF8.GetBytes(plaintext), false);

 

            StringBuilder sbString = new StringBuilder();
            for (int i = 0; i < cipherbytes.Length; i++)
            {
                sbString.Append(cipherbytes[i] + ",");
            }

 

3. 解密:

 

     /// <summary>
        /// RSA Decrypt
        /// </summary>
        /// <param name="sSource">Source string</param>
        /// <param name="sPrivateKey">Private Key</param>
        /// <returns></returns>
        public static string DecryptString(String sSource, string sPrivateKey)
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            rsa.FromXmlString(sPrivateKey);
            byte[] byteEn = rsa.Encrypt(Encoding.UTF8.GetBytes("a"), false);
            string[] sBytes = sSource.Split(',');

 

            for (int j = 0; j < sBytes.Length; j++)
            {
                if (sBytes[j] != "")
                {
                    byteEn[j] = Byte.Parse(sBytes[j]);
                }
            }
            byte[] plaintbytes = rsa.Decrypt(byteEn, false);
            return  Encoding.UTF8.GetString(plaintbytes);
        }
            return  sbString.ToString();
        }

 

 

--------------------------------------------------------------------

RSA加密解密源码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

namespace MyRSA
{
publicclass MyRSA
...{

privatestaticstring publicKey =
"<RSAKeyValue><Modulus>6CdsXgYOyya/yQH"+
"TO96dB3gEurM2UQDDVGrZoe6RcAVTxAqDDf5L"+
"wPycZwtNOx3Cfy44/D5Mj86koPew5soFIz9sx"+
"PAHRF5hcqJoG+q+UfUYTHYCsMH2cnqGVtnQiE"+
"/PMRMmY0RwEfMIo+TDpq3QyO03MaEsDGf13sP"+
"w9YRXiac=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
privatestaticstring privateKey =
"<RSAKeyValue><Modulus>6CdsXgYOyya/yQH"+
"TO96dB3gEurM2UQDDVGrZoe6RcAVTxAqDDf5L"+
"wPycZwtNOx3Cfy44/D5Mj86koPew5soFIz9sx"+
"PAHRF5hcqJoG+q+UfUYTHYCsMH2cnqGVtnQiE"+
"/PMRMmY0RwEfMIo+TDpq3QyO03MaEsDGf13sP"+
"w9YRXiac=</Modulus><Exponent>AQAB</Exponent>"+
"<P>/aoce2r6tonjzt1IQI6FM4ysR40j/gKvt4d"+
"L411pUop1Zg61KvCm990M4uN6K8R/DUvAQdrRd"+
"VgzvvAxXD7ESw==</P><Q>6kqclrEunX/fmOle"+
"VTxG4oEpXY4IJumXkLpylNR3vhlXf6ZF9obEpG"+
"lq0N7sX2HBxa7T2a0WznOAb0si8FuelQ==</Q>"+
"<DP>3XEvxB40GD5v/Rr4BENmzQW1MBFqpki6FU"+
"GrYiUd2My+iAW26nGDkUYMBdYHxUWYlIbYo6Te"+
"zc3d/oW40YqJ2Q==</DP><DQ>LK0XmQCmY/ArY"+
"gw2Kci5t51rluRrl4f5l+aFzO2K+9v3PGcndjA"+
"StUtIzBWGO1X3zktdKGgCLlIGDrLkMbM21Q==</DQ><InverseQ>"+
"GqC4Wwsk2fdvJ9dmgYlej8mTDBWg0Wm6aqb5kjn"+
"cWK6WUa6CfD+XxfewIIq26+4Etm2A8IAtRdwPl4"+
"aPjSfWdA==</InverseQ><D>a1qfsDMY8DSxB2D"+
"Cr7LX5rZHaZaqDXdO3GC01z8dHjI4dDVwOS5ZFZ"+
"s7MCN3yViPsoRLccnVWcLzOkSQF4lgKfTq3IH40"+
"H5N4gg41as9GbD0g9FC3n5IT4VlVxn9ZdW+WQry"+
"oHdbiIAiNpFKxL/DIEERur4sE1Jt9VdZsH24CJE=</D></RSAKeyValue>";

staticpublicstring Decrypt(string base64code)
...{
try
...{

//Create a UnicodeEncoder to convert between byte array and string.
UnicodeEncoding ByteConverter =new UnicodeEncoding();

//Create a new instance of RSACryptoServiceProvider to generate
//public and private key data.
RSACryptoServiceProvider RSA =new RSACryptoServiceProvider();
RSA.FromXmlString(privateKey);

byte[] encryptedData;
byte[] decryptedData;
encryptedData
= Convert.FromBase64String(base64code);

//Pass the data to DECRYPT, the private key information
//(using RSACryptoServiceProvider.ExportParameters(true),
//and a boolean flag specifying no OAEP padding.
decryptedData = RSADecrypt(
encryptedData, RSA.ExportParameters(
true), false);

//Display the decrypted plaintext to the console.
return ByteConverter.GetString(decryptedData);
}

catch (Exception exc)
...{
//Exceptions.LogException(exc);
Console.WriteLine(exc.Message);
return"";
}

}


staticpublicstring Encrypt(string toEncryptString)
...{
try
...{
//Create a UnicodeEncoder to convert between byte array and string.
UnicodeEncoding ByteConverter =new UnicodeEncoding();

//Create byte arrays to hold original, encrypted, and decrypted data.
byte[] dataToEncrypt =
ByteConverter.GetBytes(toEncryptString);
byte[] encryptedData;
byte[] decryptedData;

//Create a new instance of RSACryptoServiceProvider to generate
//public and private key data.
RSACryptoServiceProvider RSA =new RSACryptoServiceProvider();

RSA.FromXmlString(privateKey);

//Pass the data to ENCRYPT, the public key information
//(using RSACryptoServiceProvider.ExportParameters(false),
//and a boolean flag specifying no OAEP padding.
encryptedData = RSAEncrypt(
dataToEncrypt, RSA.ExportParameters(
false), false);

string base64code = Convert.ToBase64String(encryptedData);
return base64code;
}

catch (Exception exc)
...{
//Catch this exception in case the encryption did
//not succeed.
//Exceptions.LogException(exc);
Console.WriteLine(exc.Message);
return"";
}




}


staticprivatebyte[] RSAEncrypt(
byte[] DataToEncrypt,
RSAParameters RSAKeyInfo,
bool DoOAEPPadding)
...{
try
...{
//Create a new instance of RSACryptoServiceProvider.
RSACryptoServiceProvider RSA =new RSACryptoServiceProvider();

//Import the RSA Key information. This only needs
//toinclude the public key information.
RSA.ImportParameters(RSAKeyInfo);

//Encrypt the passed byte array and specify OAEP padding.
//OAEP padding is only available on Microsoft Windows XP or
//later.
return RSA.Encrypt(DataToEncrypt, DoOAEPPadding);
}

//Catch and display a CryptographicException
//to the console.
catch (CryptographicException e)
...{
//Exceptions.LogException(e);
Console.WriteLine(e.Message);

returnnull;
}


}


staticprivatebyte[] RSADecrypt(
byte[] DataToDecrypt,
RSAParameters RSAKeyInfo,
bool DoOAEPPadding)
...{
try
...{
//Create a new instance of RSACryptoServiceProvider.
RSACryptoServiceProvider RSA =new RSACryptoServiceProvider();

//Import the RSA Key information. This needs
//to include the private key information.
RSA.ImportParameters(RSAKeyInfo);

//Decrypt the passed byte array and specify OAEP padding.
//OAEP padding is only available on Microsoft Windows XP or
//later.
return RSA.Decrypt(DataToDecrypt, DoOAEPPadding);
}

//Catch and display a CryptographicException
//to the console.
catch (CryptographicException e)
...{
//Exceptions.LogException(e);
Console.WriteLine(e.Message);

returnnull;
}

}

}

}

namespace MyRSA

...{

publicclass MyRSA

...{



privatestaticstring publicKey =

   
"<RSAKeyValue><Modulus>6CdsXgYOyya/yQH"+

   
"TO96dB3gEurM2UQDDVGrZoe6RcAVTxAqDDf5L"+

   
"wPycZwtNOx3Cfy44/D5Mj86koPew5soFIz9sx"+

   
"PAHRF5hcqJoG+q+UfUYTHYCsMH2cnqGVtnQiE"+

   
"/PMRMmY0RwEfMIo+TDpq3QyO03MaEsDGf13sP"+

   
"w9YRXiac=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";

privatestaticstring privateKey =

   
"<RSAKeyValue><Modulus>6CdsXgYOyya/yQH"+

   
"TO96dB3gEurM2UQDDVGrZoe6RcAVTxAqDDf5L"+

   
"wPycZwtNOx3Cfy44/D5Mj86koPew5soFIz9sx"+

   
"PAHRF5hcqJoG+q+UfUYTHYCsMH2cnqGVtnQiE"+

   
"/PMRMmY0RwEfMIo+TDpq3QyO03MaEsDGf13sP"+

   
"w9YRXiac=</Modulus><Exponent>AQAB</Exponent>"+

   
"<P>/aoce2r6tonjzt1IQI6FM4ysR40j/gKvt4d"+

   
"L411pUop1Zg61KvCm990M4uN6K8R/DUvAQdrRd"+

   
"VgzvvAxXD7ESw==</P><Q>6kqclrEunX/fmOle"+

   
"VTxG4oEpXY4IJumXkLpylNR3vhlXf6ZF9obEpG"+

   
"lq0N7sX2HBxa7T2a0WznOAb0si8FuelQ==</Q>"+

   
"<DP>3XEvxB40GD5v/Rr4BENmzQW1MBFqpki6FU"+

   
"GrYiUd2My+iAW26nGDkUYMBdYHxUWYlIbYo6Te"+

   
"zc3d/oW40YqJ2Q==</DP><DQ>LK0XmQCmY/ArY"+

   
"gw2Kci5t51rluRrl4f5l+aFzO2K+9v3PGcndjA"+

   
"StUtIzBWGO1X3zktdKGgCLlIGDrLkMbM21Q==</DQ><InverseQ>"+

   
"GqC4Wwsk2fdvJ9dmgYlej8mTDBWg0Wm6aqb5kjn"+

   
"cWK6WUa6CfD+XxfewIIq26+4Etm2A8IAtRdwPl4"+

   
"aPjSfWdA==</InverseQ><D>a1qfsDMY8DSxB2D"+

   
"Cr7LX5rZHaZaqDXdO3GC01z8dHjI4dDVwOS5ZFZ"+

   
"s7MCN3yViPsoRLccnVWcLzOkSQF4lgKfTq3IH40"+

   
"H5N4gg41as9GbD0g9FC3n5IT4VlVxn9ZdW+WQry"+

   
"oHdbiIAiNpFKxL/DIEERur4sE1Jt9VdZsH24CJE=</D></RSAKeyValue>";



staticpublicstring Decrypt(string base64code)

...{

   
try

   
...{



       
//Create a UnicodeEncoder to convert between byte array and string.

        UnicodeEncoding ByteConverter =new UnicodeEncoding();



       
//Create a new instance of RSACryptoServiceProvider to generate

       
//public and private key data.

        RSACryptoServiceProvider RSA =new RSACryptoServiceProvider();

        RSA.FromXmlString(privateKey);



       
byte[] encryptedData;

       
byte[] decryptedData;

        encryptedData
= Convert.FromBase64String(base64code);



       
//Pass the data to DECRYPT, the private key information

       
//(using RSACryptoServiceProvider.ExportParameters(true),

       
//and a boolean flag specifying no OAEP padding.

        decryptedData = RSADecrypt(

            encryptedData, RSA.ExportParameters(
true), false);



       
//Display the decrypted plaintext to the console.

        return ByteConverter.GetString(decryptedData);

    }


   
catch (Exception exc)

   
...{

       
//Exceptions.LogException(exc);

        Console.WriteLine(exc.Message);

       
return"";

    }


}




staticpublicstring Encrypt(string toEncryptString)

...{

   
try

   
...{

       
//Create a UnicodeEncoder to convert between byte array and string.

        UnicodeEncoding ByteConverter =new UnicodeEncoding();



       
//Create byte arrays to hold original, encrypted, and decrypted data.

        byte[] dataToEncrypt =

            ByteConverter.GetBytes(toEncryptString);

       
byte[] encryptedData;

       
byte[] decryptedData;



       
//Create a new instance of RSACryptoServiceProvider to generate

       
//public and private key data.

        RSACryptoServiceProvider RSA =new RSACryptoServiceProvider();



        RSA.FromXmlString(privateKey);



       
//Pass the data to ENCRYPT, the public key information

       
//(using RSACryptoServiceProvider.ExportParameters(false),

       
//and a boolean flag specifying no OAEP padding.

        encryptedData = RSAEncrypt(

            dataToEncrypt, RSA.ExportParameters(
false), false);



       
string base64code = Convert.ToBase64String(encryptedData);

       
return base64code;

    }


   
catch (Exception exc)

   
...{

       
//Catch this exception in case the encryption did

       
//not succeed.

       
//Exceptions.LogException(exc);

        Console.WriteLine(exc.Message);

       
return"";

    }








}




staticprivatebyte[] RSAEncrypt(

   
byte[] DataToEncrypt,

    RSAParameters RSAKeyInfo,

   
bool DoOAEPPadding)

...{

   
try

   
...{

       
//Create a new instance of RSACryptoServiceProvider.

        RSACryptoServiceProvider RSA =new RSACryptoServiceProvider();



       
//Import the RSA Key information. This only needs

       
//toinclude the public key information.

        RSA.ImportParameters(RSAKeyInfo);



       
//Encrypt the passed byte array and specify OAEP padding. 

       
//OAEP padding is only available on Microsoft Windows XP or

       
//later. 

        return RSA.Encrypt(DataToEncrypt, DoOAEPPadding);

    }


   
//Catch and display a CryptographicException 

   
//to the console.

    catch (CryptographicException e)

   
...{

       
//Exceptions.LogException(e);

        Console.WriteLine(e.Message);



       
returnnull;

    }




}




staticprivatebyte[] RSADecrypt(

   
byte[] DataToDecrypt,

    RSAParameters RSAKeyInfo,

   
bool DoOAEPPadding)

...{

   
try

   
...{

       
//Create a new instance of RSACryptoServiceProvider.

        RSACryptoServiceProvider RSA =new RSACryptoServiceProvider();



       
//Import the RSA Key information. This needs

       
//to include the private key information.

        RSA.ImportParameters(RSAKeyInfo);



       
//Decrypt the passed byte array and specify OAEP padding. 

       
//OAEP padding is only available on Microsoft Windows XP or

       
//later. 

        return RSA.Decrypt(DataToDecrypt, DoOAEPPadding);

    }


   
//Catch and display a CryptographicException 

   
//to the console.

    catch (CryptographicException e)

   
...{

       
//Exceptions.LogException(e);

        Console.WriteLine(e.Message);



       
returnnull;

    }


}


}


}

 测试代码:

         static   void  Main( string [] args)
        {
            
string  encodeString  =  MyRSA.Encrypt( " 1234567 " );
            Console.WriteLine(encodeString);


            
string  decode  =  MyRSA.Decrypt(encodeString);
            Console.WriteLine(decode);

            Console.ReadLine();
        }

转载于:https://www.cnblogs.com/amylis_chen/p/3641638.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现RSA加密解密算法的C语言代码,你需要以下几个步骤: 1. 生成RSA密钥对: - 随机选择两个大素数 p 和 q。 - 计算 n = p * q。 - 计算 φ(n) = (p-1) * (q-1),其中 φ(n) 表示欧拉函数。 - 选择一个整数 e,满足 1 < e < φ(n),且 e 和 φ(n) 互质。 - 计算 d,使得 (d * e) ≡ 1 (mod φ(n)),即 d * e 除以 φ(n) 的余数为 1。 - 公钥为 (e, n),私钥为 (d, n)。 2. 加密: - 将明文转换为整数 M。 - 使用公钥 (e, n) 进行加密,计算密文 C = M^e % n。 3. 解密: - 使用私钥 (d, n) 进行解密,计算明文 M = C^d % n。 下面是一个简单的示例代码: ```c #include <stdio.h> // 求最大公约数 int gcd(int a, int b) { if (b == 0) return a; else return gcd(b, a % b); } // 求模逆元 int mod_inverse(int a, int m) { int m0 = m, t, q; int x0 = 0, x1 = 1; if (m == 1) return 0; while (a > 1) { q = a / m; t = m; m = a % m; a = t; t = x0; x0 = x1 - q * x0; x1 = t; } if (x1 < 0) x1 += m0; return x1; } // 加密 int encrypt(int message, int e, int n) { int ciphertext = 1; for (int i = 0; i < e; i++) { ciphertext = (ciphertext * message) % n; } return ciphertext; } // 解密 int decrypt(int ciphertext, int d, int n) { int message = 1; for (int i = 0; i < d; i++) { message = (message * ciphertext) % n; } return message; } int main() { int p = 61; // 第一个大素数 int q = 53; // 第二个大素数 int n = p * q; int phi_n = (p - 1) * (q - 1); int e = 17; // 选择一个与 phi(n) 互质的数,常用公钥指数 int d = mod_inverse(e, phi_n); // 计算私钥指数 // 明文和密文 int message = 123; int ciphertext = encrypt(message, e, n); int decrypted_message = decrypt(ciphertext, d, n); printf("明文: %d\n", message); printf("密文: %d\n", ciphertext); printf("解密后的明文: %d\n", decrypted_message); return 0; } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值