在C#中進行RSA解密,需要用RSACryptoServiceProvider,但是不支持OpenSSL格式的公鑰或者私鑰。 X509 公鑰 非加密 PKCS#8 私鑰 PKCS#1 私鑰 引用以下 Nuget 包 https://www.nuget.org/packages/System.Exte ...
在C#中進行RSA解密,需要用RSACryptoServiceProvider,但是不支持OpenSSL格式的公鑰或者私鑰。
X509 公鑰
-----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCRh7vKq7r6EhSg9y6iD38Vy08z umEJXhNTIGe8vRjdpE118Nu1cPRZ0AU9FbMIx8cnQtgCqGgW3DPDLj4VmlmdnJ8P cFHBBWgh85P1hicv8BQ0nLLjqezaBcS9EmO1C7zhdONVrvMFyHc1j76e+Fv+XfC6 CRvwKfqX+j5OMmWtowIDAQAB -----END PUBLIC KEY-----
非加密 PKCS#8 私鑰
-----BEGIN 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 J9VZA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aTiDBoPpJ8N805XEhd0Kq+ghzSThxL3 fVtKUQLiCh7Yd8oMd/G5S3xWJHUXSioATT8uPRH2bOb/ -----END RSA PRIVATE 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格式