.net core中使用openssl的公開金鑰私密金鑰進行加解密

來源:互聯網
上載者:User

標籤:string   ++   project   copy   build   ati   com   wap   key   

這篇博文分享的是 C#中使用OpenSSL的公開金鑰加密/私密金鑰解密 一文中的解決方案在 .net core 中的改進。之前的博文針對的是 .NET Framework ,加解密用的是 RSACryptoServiceProvider 。雖然在 corefx(.NET Core Framework) 中也有 RSACryptoServiceProvider ,但它目前只支援 Windows ,不能跨平台。

之前的 new RSACryptoServiceProvider(); 代碼在 mac 上運行,會報下面的錯誤:

System.PlatformNotSupportedException: Operation is not supported on this platform.at System.Security.Cryptography.RSACryptoServiceProvider..ctor()

要解決這個問題,需要改用  System.Security.Cryptography.RSA.Create() Factory 方法,使用它之後,在 Windows 上建立的是 System.Security.Cryptography.RSACng 的執行個體,在 Mac 與 Linux 上建立的是 System.Security.Cryptography.RSAOpenSsl 的執行個體,它們都繼承自 System.Security.Cryptography.RSA 抽象類別。

使用了 RSA.Create() 之後,帶來了一個問題,RSA 中沒有 RSACryptoServiceProvider 中的以下2個簽名的加解密方法。

public byte[] Encrypt(byte[] rgb, bool fOAEP);public byte[] Decrypt(byte[] rgb, bool fOAEP);

只有

public abstract byte[] Encrypt(byte[] data, RSAEncryptionPadding padding);public abstract byte[] Decrypt(byte[] data, RSAEncryptionPadding padding);

調用時它們時需要傳遞 RSAEncryptionPadding 類型的參數值:

但對於 openssl 產生的公開金鑰私密金鑰不知道選擇哪種 RSAEncryptionPadding ,只能採取笨方法 —— 一個一個試試,試出來的結果是 RSAEncryptionPadding.Pkcs1 

 

openssl 的公開金鑰與私密金鑰是在 Mac 上通過下面的2個命令產生的:

openssl genrsa -out rsa_1024_priv.pem 102openssl rsa -pubout -in rsa_1024_priv.pem -out rsa_1024_pub.peml

(註:一定要用 openssl 命令,用 ssh-keygen -t rsa 命令產生的公開金鑰私密金鑰是不行的)

修改這兩個地方(RSA.Create 與 RSAEncryptionPadding.Pkcs1)之後,就可以在 .net core 上使用 openssl 的公開金鑰私密金鑰進行加解密了,以下是測試時所用的完整代碼(.net core控制台程式)。經測試,在 Windows,macOS,Linux Ubuntu 上都能成功進行加解密。

Program.cs

using System;using System.IO;using System.Security.Cryptography;using System.Text;namespace TryRsa{    public class Program    {        //openssl genrsa -out rsa_1024_priv.pem 1024        private static readonly string _privateKey = @"MIICXgIBAAKBgQC0xP5HcfThSQr43bAMoopbzcCyZWE0xfUeTA4Nx4PrXEfDvybJEIjbU/rgANAty1yp7g20J7+wVMPCusxftl/d0rPQiCLjeZ3HtlRKld+9htAZtHFZosV29h/hNE9JkxzGXstaSeXIUIWquMZQ8XyscIHhqoOmjXaCv58CSRAlAQIDAQABAoGBAJtDgCwZYv2FYVk0ABw6F6CWbuZLUVykks69AG0xasti7Xjh3AximUnZLefsiuJqg2KpRzfv1CM+Cw5cp2GmIVvRqq0GlRZGxJ38AqH9oyUa2m3TojxWapY47zyePYEjWwRTGlxUBkdujdcYj6/dojNkm4azsDXl9W5YaXiPfbgJAkEA4rlhSPXlohDkFoyfX0v2OIdaTOcVpinv1jjbSzZ8KZACggjiNUVrSFV3Y4oWom93K5JLXf2mV0Sy80mPR5jOdwJBAMwciAk8xyQKpMUGNhFX2jKboAYY1SJCfuUnyXHAPWeHp5xCL2UHtjryJp/Vx8TgsFTGyWSyIE9R8hSup+32rkcCQBe+EAkC7yQ0np4Z5cql+sfarMMm4+Z9t8b4N0a+EuyLTyfs5Dtt5JkzkggTeuFRyOoALPJP0K6M3CyMBHwb7WsCQQCiTM2fCsUO06fRQu8bO1A1janhLz3K0DU24jw8RzCMckHE7pvhKhCtLn+n+MWwtzl/L9JUT4+BgxeLepXtkolhAkEA2V7er7fnEuL0+kKIjmOm5F3kvMIDh9YC1JwLGSvu1fnzxK34QwSdxgQRF1dfIKJw73lClQpHZfQxL/2XRG8IoA==".Replace("\n", "");        //openssl rsa -pubout -in rsa_1024_priv.pem -out rsa_1024_pub.pem        private static readonly string _publicKey = @"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC0xP5HcfThSQr43bAMoopbzcCyZWE0xfUeTA4Nx4PrXEfDvybJEIjbU/rgANAty1yp7g20J7+wVMPCusxftl/d0rPQiCLjeZ3HtlRKld+9htAZtHFZosV29h/hNE9JkxzGXstaSeXIUIWquMZQ8XyscIHhqoOmjXaCv58CSRAlAQIDAQAB".Replace("\n", "");        public static void Main(string[] args)        {            var plainText = "cnblogs.com";            //Encrypt            RSA rsa = CreateRsaFromPublicKey(_publicKey);                                   var plainTextBytes = Encoding.UTF8.GetBytes(plainText);            var cipherBytes = rsa.Encrypt(plainTextBytes, RSAEncryptionPadding.Pkcs1);            var cipher = Convert.ToBase64String(cipherBytes);            Console.WriteLine($"{nameof(cipher)}:{cipher}");            //Decrypt            rsa = CreateRsaFromPrivateKey(_privateKey);                        cipherBytes = System.Convert.FromBase64String(cipher);            plainTextBytes = rsa.Decrypt(cipherBytes, RSAEncryptionPadding.Pkcs1);            plainText = Encoding.UTF8.GetString(plainTextBytes);            Console.WriteLine($"{nameof(plainText)}:{plainText}");        }        private static RSA CreateRsaFromPrivateKey(string privateKey)        {            var privateKeyBits = System.Convert.FromBase64String(privateKey);            var rsa = RSA.Create();            var RSAparams = new RSAParameters();            using (var binr = new BinaryReader(new MemoryStream(privateKeyBits)))            {                byte bt = 0;                ushort twobytes = 0;                twobytes = binr.ReadUInt16();                if (twobytes == 0x8130)                    binr.ReadByte();                else if (twobytes == 0x8230)                    binr.ReadInt16();                else                    throw new Exception("Unexpected value read binr.ReadUInt16()");                twobytes = binr.ReadUInt16();                if (twobytes != 0x0102)                    throw new Exception("Unexpected version");                bt = binr.ReadByte();                if (bt != 0x00)                    throw new Exception("Unexpected value read binr.ReadByte()");                RSAparams.Modulus = binr.ReadBytes(GetIntegerSize(binr));                RSAparams.Exponent = binr.ReadBytes(GetIntegerSize(binr));                RSAparams.D = binr.ReadBytes(GetIntegerSize(binr));                RSAparams.P = binr.ReadBytes(GetIntegerSize(binr));                RSAparams.Q = binr.ReadBytes(GetIntegerSize(binr));                RSAparams.DP = binr.ReadBytes(GetIntegerSize(binr));                RSAparams.DQ = binr.ReadBytes(GetIntegerSize(binr));                RSAparams.InverseQ = binr.ReadBytes(GetIntegerSize(binr));            }            rsa.ImportParameters(RSAparams);            return rsa;        }        private static int GetIntegerSize(BinaryReader binr)        {            byte bt = 0;            byte lowbyte = 0x00;            byte highbyte = 0x00;            int count = 0;            bt = binr.ReadByte();            if (bt != 0x02)                return 0;            bt = binr.ReadByte();            if (bt == 0x81)                count = binr.ReadByte();            else                if (bt == 0x82)            {                highbyte = binr.ReadByte();                lowbyte = binr.ReadByte();                byte[] modint = { lowbyte, highbyte, 0x00, 0x00 };                count = BitConverter.ToInt32(modint, 0);            }            else            {                count = bt;            }            while (binr.ReadByte() == 0x00)            {                count -= 1;            }            binr.BaseStream.Seek(-1, SeekOrigin.Current);            return count;        }        private static RSA CreateRsaFromPublicKey(string publicKeyString)        {            byte[] SeqOID = { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 };            byte[] x509key;            byte[] seq = new byte[15];            int x509size;            x509key = Convert.FromBase64String(publicKeyString);            x509size = x509key.Length;            using (var mem = new MemoryStream(x509key))            {                using (var binr = new BinaryReader(mem))                {                    byte bt = 0;                    ushort twobytes = 0;                    twobytes = binr.ReadUInt16();                    if (twobytes == 0x8130)                        binr.ReadByte();                    else if (twobytes == 0x8230)                        binr.ReadInt16();                    else                        return null;                    seq = binr.ReadBytes(15);                    if (!CompareBytearrays(seq, SeqOID))                        return null;                    twobytes = binr.ReadUInt16();                    if (twobytes == 0x8103)                        binr.ReadByte();                    else if (twobytes == 0x8203)                        binr.ReadInt16();                    else                        return null;                    bt = binr.ReadByte();                    if (bt != 0x00)                        return null;                    twobytes = binr.ReadUInt16();                    if (twobytes == 0x8130)                        binr.ReadByte();                    else if (twobytes == 0x8230)                        binr.ReadInt16();                    else                        return null;                    twobytes = binr.ReadUInt16();                    byte lowbyte = 0x00;                    byte highbyte = 0x00;                    if (twobytes == 0x8102)                        lowbyte = binr.ReadByte();                    else if (twobytes == 0x8202)                    {                        highbyte = binr.ReadByte();                        lowbyte = binr.ReadByte();                    }                    else                        return null;                    byte[] modint = { lowbyte, highbyte, 0x00, 0x00 };                    int modsize = BitConverter.ToInt32(modint, 0);                    int firstbyte = binr.PeekChar();                    if (firstbyte == 0x00)                    {                        binr.ReadByte();                        modsize -= 1;                    }                    byte[] modulus = binr.ReadBytes(modsize);                    if (binr.ReadByte() != 0x02)                        return null;                    int expbytes = (int)binr.ReadByte();                    byte[] exponent = binr.ReadBytes(expbytes);                    var rsa = RSA.Create();                    var rsaKeyInfo = new RSAParameters                    {                        Modulus = modulus,                        Exponent = exponent                    };                    rsa.ImportParameters(rsaKeyInfo);                    return rsa;                }            }        }        private static bool CompareBytearrays(byte[] a, byte[] b)        {            if (a.Length != b.Length)                return false;            int i = 0;            foreach (byte c in a)            {                if (c != b[i])                    return false;                i++;            }            return true;        }    }}

project.json

{  "version": "1.0.0-*",  "buildOptions": {    "emitEntryPoint": true  },  "dependencies": {    "Microsoft.NETCore.App": {        "type": "platform",        "version": "1.1.0-preview1-001100-00"    },    "System.Security.Cryptography.Algorithms": "4.3.0-preview1-24530-04"  },  "frameworks": {    "netcoreapp1.1": {      "imports": "dnxcore50"    }  }}

.net core中使用openssl的公開金鑰私密金鑰進行加解密

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.