你的位置:首页 > ASP.net教程

[ASP.net教程]C# 中使用 OpenSSL 的公钥/私钥进行加密和解密


在C#中进行RSA解密,需要用RSACryptoServiceProvider,但是不支持OpenSSL格式的公钥或者私钥。

X509 公钥

-----BEGIN PUBLIC KEY-----MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCRh7vKq7r6EhSg9y6iD38Vy08zumEJXhNTIGe8vRjdpE118Nu1cPRZ0AU9FbMIx8cnQtgCqGgW3DPDLj4VmlmdnJ8PcFHBBWgh85P1hicv8BQ0nLLjqezaBcS9EmO1C7zhdONVrvMFyHc1j76e+Fv+XfC6CRvwKfqX+j5OMmWtowIDAQAB-----END PUBLIC KEY-----

非加密 PKCS#8 私钥

-----BEGIN PRIVATE KEY-----MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJGHu8qruvoSFKD3LqIPfxXLTzO6YQleE1MgZ7y9GN2kTXXw27Vw9FnQBT0VswjHxydC2AKoaBbcM8MuPhWaWZ2cnw9wUcEFaCHzk/WGJy/wFDScsuOp7NoFxL0SY7ULvOF041Wu8wXIdzWPvp74W/5d8LoJG/Ap+pf6Pk4yZa2jAgMBAAECgYBxgvu5M4Xd9Che/S5Efe3UZAZdBK0Xj2dnWUlQ7/XrO3Kn4bydo4MUYqsTYE+LM7hlKUAvooe9/Pfq77DBTOlETcSJfvZdL+mX5b3v8hnknWdpiyhfB2yaYbNTOUWMHboekwtqjP5C5yA5IObGcDFFPVZA/tRa50XNq3PATS1jIQJBAPi7U+zhFG/QKI4IlUYymwKlsa7ZMHJjXX8508ZxD0azYDfFsZEWquAdPPXj9lVlXD7uMBzewAx/gn2wTBLtr1sCQQCVyGRyTarXFaqdImEe+7/o6hCIdVvCBUuyIkd0WUPTkbizpUpUrzu9oy1UbvWlI2r4QqjoMh8eq05zlU+sJ9VZAkEA6mDCzZSuiEoy3NvzpYksDguKagNYpoFBahBYoUaKKYn/Ya6VCu28KKEEf4PG7GMt0FLr3Vh8yY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E KEY-----

引用以下 Nuget 包

https://www.nuget.org/packages/System.Extended/

直接使用 RSACryptoServiceProvider,会发现多出几个扩展方法

参数为密钥Base64转码的字节数组

var private_key = @"MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJGHu8qruvoSFKD3		  LqIPfxXLTzO6YQleE1MgZ7y9GN2kTXXw27Vw9FnQBT0VswjHxydC2AKoaBbcM8Mu		  PhWaWZ2cnw9wUcEFaCHzk/WGJy/wFDScsuOp7NoFxL0SY7ULvOF041Wu8wXIdzWP		  vp74W/5d8LoJG/Ap+pf6Pk4yZa2jAgMBAAECgYBxgvu5M4Xd9Che/S5Efe3UZAZd		  BK0Xj2dnWUlQ7/XrO3Kn4bydo4MUYqsTYE+LM7hlKUAvooe9/Pfq77DBTOlETcSJ		  fvZdL+mX5b3v8hnknWdpiyhfB2yaYbNTOUWMHboekwtqjP5C5yA5IObGcDFFPVZA		  /tRa50XNq3PATS1jIQJBAPi7U+zhFG/QKI4IlUYymwKlsa7ZMHJjXX8508ZxD0az		  YDfFsZEWquAdPPXj9lVlXD7uMBzewAx/gn2wTBLtr1sCQQCVyGRyTarXFaqdImEe		  +7/o6hCIdVvCBUuyIkd0WUPTkbizpUpUrzu9oy1UbvWlI2r4QqjoMh8eq05zlU+s		  J9VZAkEA6mDCzZSuiEoy3NvzpYksDguKagNYpoFBahBYoUaKKYn/Ya6VCu28KKEE		  f4PG7GMt0FLr3Vh8yYohsUQ9+xwjvwJAGDB8yFjytjmxjB75QF+35o2mjeMmJndk		  eig/EfM4mPp3scuH7ZU/OKkZsQEaesj1hZJ+ZMFzdSiFSvVaIJtuQQJAH3sXQ3DV		  EoeSW40TyYviq2K1pEpz9fGcS1TrjI+Yt1Mf0mvO6eupNZCfuhiAqJ5ZGRzTv1Pu		  G7pgz+ey5sWBcA==";var public_key = @"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCRh7vKq7r6EhSg9y6iD38Vy08z		  umEJXhNTIGe8vRjdpE118Nu1cPRZ0AU9FbMIx8cnQtgCqGgW3DPDLj4VmlmdnJ8P		  cFHBBWgh85P1hicv8BQ0nLLjqezaBcS9EmO1C7zhdONVrvMFyHc1j76e+Fv+XfC6		  CRvwKfqX+j5OMmWtowIDAQAB";var rsa = new RSACryptoServiceProvider();rsa.FromX509PublicKey(Convert.FromBase64String(public_key));var bytes = rsa.Encrypt(Encoding.UTF8.GetBytes("mangohappy"), false);rsa.FromPKCS8PrivateKey(Convert.FromBase64String(private_key));Console.WriteLine(Encoding.UTF8.GetString(rsa.Decrypt(bytes, false)));

注意:.NET的 RSACryptoServiceProvider 只支持公钥加密,私钥解密,以上还有加密的 PKCS#8 格式的私钥,我就没有处理了,PKCS#1和PKCS#8的公钥都是X509格式