/** * 私钥解密,需注意的是这里的PEM 私钥文件是PKCS1格式,而Java中的是PKCS8格式 */ public static string DecryptWithPrivate(string base64Input, string privateKey) { string priXml = RsaKeyConvert.PrivateKeyPkcs1ToXml(privateKey); RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); byte[] cipherbytes; rsa.FromXmlString(priXml); cipherbytes = rsa.Decrypt(Convert.FromBase64String(base64Input), false); return(Encoding.UTF8.GetString(cipherbytes)); }
/// <summary> /// 用私钥给数据进行RSA加密 /// </summary> /// <param name="xmlPrivateKey"> 私钥(XML格式字符串)</param> /// <param name="strEncryptString"> 要加密的数据 </param> /// <returns> 加密后的数据 </returns> public static string EncryptWithPrivate(string strEncryptString, string privateKey) { string priXml = RsaKeyConvert.PrivateKeyPkcs1ToXml(privateKey); //加载私钥 RSACryptoServiceProvider privateRsa = new RSACryptoServiceProvider(); privateRsa.FromXmlString(priXml); //转换密钥 AsymmetricCipherKeyPair keyPair = DotNetUtilities.GetKeyPair(privateRsa); IBufferedCipher c = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding"); //使用RSA/ECB/PKCS1Padding格式 //第一个参数为true表示加密,为false表示解密;第二个参数表示密钥 c.Init(true, keyPair.Private); byte[] DataToEncrypt = Encoding.UTF8.GetBytes(strEncryptString); byte[] outBytes = c.DoFinal(DataToEncrypt);//加密 string strBase64 = Convert.ToBase64String(outBytes); return(strBase64); }