public static void testRsaKeyConvert() { string publicKeySC8 = @"-----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC1f0xSc8UyzldsIA2v9OHNfKGw tRzt7oOfMyXplPqQQopcq92YVEoSs0FXhlRDMDpPgc603TDmg2h7OId3VrNu98S + TDdX0fl57EamcmSlxX5yNvqq + KKhCg7 / I9Wj0DaGRi3lHS2W2s7r9d / k3eeB7hej sZ9s1YoGEp5iRLfoRwIDAQAB ---- - END PUBLIC KEY-----"; string privateKeySC8 = @"-----BEGIN PRIVATE KEY----- MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALV/TFJzxTLOV2wg Da/04c18obC1HO3ug58zJemU+pBCilyr3ZhUShKzQVeGVEMwOk+BzrTdMOaDaHs4 h3dWs273xL5MN1fR+XnsRqZyZKXFfnI2+qr4oqEKDv8j1aPQNoZGLeUdLZbazuv1 3+Td54HuF6Oxn2zVigYSnmJEt+hHAgMBAAECgYAoWkwyzNCcUio3vQyuAWku0bX1 Xt82u2ACRlH4lAn9hv3SStfy5VKuw7IUbqZPZeqhAMBfkAouRis1skTUMK+l7Pvl 2sb57lZPyNQb9wZF022zmDQZO+I924GFmPWOfs8UyLMRfO7/azi4WaPBIQDyTN/t aKgX+LP3VxRweeouOQJBAPCleP4YTE+hlaKn8cMbT1DNU9NuxHTAcOQ0/Oioiu/V T8mRtDhuyt4w9s7qwSWfkyn6qUyUlAzszIDLhweNxDsCQQDBE7sKrSG6hnKl3B0U BhXt+t+iL5WgjEwNVgKJ+Jezo3kl37S2/JlQQuL/Nt6o6BrwIzFOOpI2Q6gYpzRy 5adlAkEAjPQviY3L7Py1e/+pIWH2tFqAViDUW5p4xYKv/Mr0DoTAZk285S0oELtX ZV2l4pa0iWs0DRIeIe/13R7ZqbgFDwJAaE5NdLYVi5wIodvpBaFIBZnLaOYGEobY qze1BW58HfsJftF84oJSHQ8VbMTqwxspOmP4xgdUZ+ZjEHZ8GjpBFQJAMKpS5dM6 jvXytT1IsQLIb4s5WVArgcaV548ZzUrdfSbN42L8EcYsTAgNjQYFu8gWs7OVLKK/ kSYyqc/4m8/fFA== -----END PRIVATE KEY-----"; string privateKeySC1 = RsaKeyConvert.PrivateKeyPkcs8ToPkcs1(privateKeySC8); Console.WriteLine(privateKeySC1); }
/** * 私钥解密,需注意的是这里的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); }