C#非對稱加密RSA實現(xiàn)

字號:

做一非對稱加密,看了microsoft的simple,并不能導(dǎo)出private 和 public key .當(dāng)然,這樣的例子很多,可沒找到關(guān)于如何導(dǎo)入導(dǎo)出key及byte[]與string 的相互轉(zhuǎn)化(調(diào)用了很多直接轉(zhuǎn)化的函數(shù),轉(zhuǎn)化的過程中會有亂碼,導(dǎo)致加解密失敗。
    項目要求,生成一個private key 和 public key ,用 Public Key 加密,考試大提示用Private key 解密,是這樣實現(xiàn)的。
    源代碼如下:
    1.生成一對keys:
    ///
    /// generate private key and public key arr[0] for private key arr[1] for public key
    ///

    ///
    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.加密:
    ///
    /// RSA Encrypt
    ///

    /// Source string
    /// public key
    ///
    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. 解密:
    ///
    /// RSA Decrypt
    ///

    /// Source string
    /// Private Key
    ///
    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();
    }