public static byte[] EncryptRSA(string publicKeyAsPem, string payload, string passphrase = null) { var encoder = new UTF8Encoding(); byte[] byte_payload = encoder.GetBytes(payload); CryptoKey d = CryptoKey.FromPublicKey(publicKeyAsPem, passphrase); OpenSSL.Crypto.RSA rsa = d.GetRSA(); byte[] result = rsa.PublicEncrypt(byte_payload, OpenSSL.Crypto.RSA.Padding.PKCS1); rsa.Dispose(); return(result); }
/// <summary> /// 公钥加密 /// </summary> public static string PublicEncrypt(string publicKey, string text, Encoding encoding, int padding) { byte[] textBytes = encoding.GetBytes(text); using (BIO bio = new BIO(publicKey)) { using (OpenSSL.Crypto.RSA rsa = OpenSSL.Crypto.RSA.FromPublicKey(bio)) { textBytes = rsa.PublicEncrypt(textBytes, (OpenSSL.Crypto.RSA.Padding)padding); rsa.Dispose(); } bio.Dispose(); } return(Convert.ToBase64String(textBytes)); }
private void TestKey(int v, RSA key) { byte[] ctext_ex = null; switch (v % 3) { case 0: ctext_ex = Key1(key); break; case 1: ctext_ex = Key2(key); break; case 2: ctext_ex = Key3(key); break; } if (v / 3 >= 1) key.ConstantTime = false; byte[] ctext = key.PublicEncrypt(ptext_ex, RSA.Padding.PKCS1); Assert.AreEqual(ctext_ex.Length, ctext.Length); byte[] ptext = key.PrivateDecrypt(ctext, RSA.Padding.PKCS1); string str1 = BitConverter.ToString(ptext); string str2 = BitConverter.ToString(ptext_ex); Assert.AreEqual(str2, str1); Console.WriteLine("PKCS #1 v1.5 encryption/decryption ok"); ctext = key.PublicEncrypt(ptext_ex, RSA.Padding.OAEP); Assert.AreEqual(ctext_ex.Length, ctext.Length); ptext = key.PrivateDecrypt(ctext, RSA.Padding.OAEP); str1 = BitConverter.ToString(ptext); str2 = BitConverter.ToString(ptext_ex); Assert.AreEqual(str2, str1); Console.WriteLine("OAEP test vector {0} passed!", v); // Different ciphertexts (rsa_oaep.c without -DPKCS_TESTVECT). // Try decrypting ctext_ex ptext = key.PrivateDecrypt(ctext_ex, RSA.Padding.OAEP); str1 = BitConverter.ToString(ptext); str2 = BitConverter.ToString(ptext_ex); Assert.AreEqual(str2, str1); Console.WriteLine("OAEP encryption/decryption ok!", v); for (int n = 0; n < ctext.Length; ++n) { byte saved = ctext[n]; for (byte b = 0; b < byte.MaxValue; ++b) { if (b == saved) continue; ctext[n] = b; bool error = false; try { ptext = key.PrivateDecrypt(ctext, RSA.Padding.OAEP); } catch (Exception) { error = true; } Assert.IsTrue(error, "Corrupt data decrypted!"); } } }