public override PrivateKey ImportPrivateKey <PK>(EncodingFormat fmt, Stream source) { if (typeof(PK) == typeof(RsaPrivateKey)) { using (BIO keyBio = BIO.MemoryBuffer()) { using (var ms = new MemoryStream()) { source.CopyTo(ms); keyBio.Write(ms.ToArray()); } using (var key = CryptoKey.FromPrivateKey(keyBio, null)) { var rsa = key.GetRSA(); return(new RsaPrivateKey(rsa.Size, rsa.PrivateExponent.ToHexString(), rsa.PrivateKeyAsPEM)); } } } else { throw new NotSupportedException("unsupported private key type"); } }
// Protected non-polymorphic methods // Public non-polymorphic methods static public CryptoKey AsymmetricKeyToOpenSslFormat(RSACryptoServiceProvider rsa) { // PEM, since OpenSSL doesn't easily allow unpassworded DER, for whatever reason string pkcs = RSAPrivateKeyToDER.RSAKeyToPEM(rsa.ExportParameters(true)); CryptoKey key = CryptoKey.FromPrivateKey(pkcs, null); return(key); }
public static byte[] AsymmetricDecrypt(string privateKeyAsPem, byte[] payload) { //CryptoKey d = CryptoKey.FromPrivateKey(privateKeyAsPem, null); CryptoKey d = CryptoKey.FromPrivateKey(privateKeyAsPem, "pass"); RSA rsa = d.GetRSA(); byte[] result = rsa.PrivateDecrypt(payload, RSA.Padding.PKCS1); rsa.Dispose(); return(result); }
static void WriteDll(string dllpath, string pempath) { //Load public key StreamReader sr = new StreamReader(pempath); string keyaspem = sr.ReadToEnd(); sr.Close(); CryptoKey d; //Is private key if (keyaspem.IndexOf("-----BEGIN RSA PRIVATE KEY-----") == 0) { d = CryptoKey.FromPrivateKey(keyaspem, null); } //Is public key else if (keyaspem.IndexOf("-----BEGIN PUBLIC KEY-----") == 0) { d = CryptoKey.FromPublicKey(keyaspem, null); } else { Console.WriteLine("Key is not vaild."); return; } //Init openssl rsa component. RSA r = d.GetRSA(); Console.WriteLine("Key File:"); Console.WriteLine(pempath); Console.WriteLine(); Console.WriteLine("Public Moludus: (reversed)"); byte[] moludus = new byte[256]; r.PublicModulus.ToBytes(moludus); Array.Reverse(moludus); Console.WriteLine(BitConverter.ToString(moludus)); Console.WriteLine(); Console.Write("Begin writing \""); Console.Write(dllpath); Console.Write("\" at "); Console.WriteLine("{0:x8}", SIGNATURE_OFFEST); //hex output Console.WriteLine(); //write game.dll FileStream fs = new FileStream(dllpath, FileMode.Open, FileAccess.ReadWrite); fs.Seek(SIGNATURE_OFFEST, SeekOrigin.Begin); fs.Write(moludus, 0, moludus.Length); fs.Close(); Console.WriteLine("Writing successful"); Console.WriteLine(); Console.WriteLine("======================"); }
public static string DecryptRSA(string privateKeyAsPem, byte[] payload, string passphrase = null) { var encoder = new UTF8Encoding(); byte[] byte_payload = payload; CryptoKey d = CryptoKey.FromPrivateKey(privateKeyAsPem, passphrase); OpenSSL.Crypto.RSA rsa = d.GetRSA(); byte[] result = rsa.PrivateDecrypt(byte_payload, OpenSSL.Crypto.RSA.Padding.PKCS1); rsa.Dispose(); return(encoder.GetString(result)); }
public override void ExportArchive(PrivateKey pk, IEnumerable <Crt> certs, ArchiveFormat fmt, Stream target, string password = "") { var rsaPk = pk as RsaPrivateKey; if (rsaPk == null) { throw new NotSupportedException("unsupported private key type"); } if (fmt == ArchiveFormat.PKCS12) { var x509Arr = certs.Select(x => { using (var bio = BIO.MemoryBuffer()) { bio.Write(x.Pem); return(new X509Certificate(bio)); } }).ToArray(); using (var key = CryptoKey.FromPrivateKey(rsaPk.Pem, null)) { var caStack = new OpenSSL.Core.Stack <X509Certificate>(); for (int i = 1; i < x509Arr.Length; ++i) { caStack.Add(x509Arr[i]); } using (var pfx = new PKCS12(password == string.Empty ? null : password, key, x509Arr[0], caStack)) { using (var bio = BIO.MemoryBuffer()) { pfx.Write(bio); var count = (int)bio.BytesPending; var array = bio.ReadBytes(count); target.Write(array.Array, 0, count); } } } foreach (var x in x509Arr) { x.Dispose(); } } else { throw new NotSupportedException("unsupported archive format"); } }
/// <summary> /// 私钥签名 /// </summary> public static string Sign(string privateKey, string text, Encoding encoding) { using (BIO bio = new BIO(privateKey)) { using (CryptoKey cryptoKey = CryptoKey.FromPrivateKey(bio, null)) { using (MessageDigestContext sha256 = new MessageDigestContext(MessageDigest.SHA256)) { byte[] msgByte = encoding.GetBytes(text); byte[] signByte = sha256.Sign(msgByte, cryptoKey); return(Convert.ToBase64String(signByte)); } } } }
//===================================================== // Sign map signature data(map hash) with private key // - output in reversed order //===================================================== public static byte[] SignData(byte[] BytesToSign, string keypath) { //Load private key StreamReader sr = new StreamReader(keypath); string pvtkeyaspem = sr.ReadToEnd(); sr.Close(); //Init openssl rsa component. CryptoKey d = CryptoKey.FromPrivateKey(pvtkeyaspem, null); RSA r = d.GetRSA(); byte[] result = r.PrivateEncrypt(BytesToSign, OpenSSL.Crypto.RSA.Padding.None); r.Dispose(); Array.Reverse(result); return(result); }
/// <summary> /// Converts a certificate and private key to a PKCS#12 (.PFX) file. /// </summary> public static void ConvertToPfx(Stream keyPemSource, Stream crtPemSource, Stream isrPemSource, Stream pfxTarget) { using (BIO keyBio = BIO.MemoryBuffer(), crtBio = BIO.MemoryBuffer(), isrBio = BIO.MemoryBuffer()) { using (var ms = new MemoryStream()) { keyPemSource.CopyTo(ms); keyBio.Write(ms.ToArray()); } using (var ms = new MemoryStream()) { crtPemSource.CopyTo(ms); crtBio.Write(ms.ToArray()); } using (var ms = new MemoryStream()) { isrPemSource.CopyTo(ms); isrBio.Write(ms.ToArray()); } using (var key = CryptoKey.FromPrivateKey(keyBio, null)) { using (var crt = new X509Certificate(crtBio)) { using (var isr = new X509Certificate(isrBio)) { var isrStack = new OpenSSL.Core.Stack <X509Certificate>(); isrStack.Add(isr); using (var pfx = new PKCS12(null, key, crt, isrStack)) { using (var pfxBio = BIO.MemoryBuffer()) { pfx.Write(pfxBio); var arr = pfxBio.ReadBytes((int)pfxBio.BytesPending); pfxTarget.Write(arr.Array, arr.Offset, arr.Count); } } } } } } }
public void TestGenCSR() { var pem = File.ReadAllText("openssl-rsagen-privatekey.txt"); var rsa = CryptoKey.FromPrivateKey(pem, null); //pem = File.ReadAllText("openssl-rsagen-publickey.txt"); //rsa = CryptoKey.FromPublicKey(pem, null); var nam = new X509Name(); nam.Common = "FOOBAR"; nam.Country = "US"; var csr = new X509Request(); csr.PublicKey = rsa; csr.Subject = nam; csr.Sign(rsa, MessageDigest.SHA256); File.WriteAllText("openssl-requ-csr.txt", csr.PEM); using (var bioOut = BIO.MemoryBuffer()) { csr.Write_DER(bioOut); var arr = bioOut.ReadBytes((int)bioOut.BytesPending); File.WriteAllBytes("openssl-requ-csr.der", arr.Array); } //using (var bioIn = BIO.MemoryBuffer()) //{ // var pem2 = File.ReadAllText("openssl-requ-csr.txt"); // bioIn.Write(pem2); // var csr = new X509Request() // var x509 = new X509Certificate(bioIn); //} }
private Csr GenerateCsr(CsrDetails csrDetails, RsaPrivateKey rsaKeyPair, string messageDigest = "SHA256") { var rsaKeys = CryptoKey.FromPrivateKey(rsaKeyPair.Pem, null); // Translate from our external form to our OpenSSL internal form // Ref: https://www.openssl.org/docs/manmaster/crypto/X509_NAME_new.html var xn = new X509Name(); if (!string.IsNullOrEmpty(csrDetails.CommonName /**/)) { xn.Common = csrDetails.CommonName; // CN; } if (!string.IsNullOrEmpty(csrDetails.Country /**/)) { xn.Country = csrDetails.Country; // C; } if (!string.IsNullOrEmpty(csrDetails.StateOrProvince /**/)) { xn.StateOrProvince = csrDetails.StateOrProvince; // ST; } if (!string.IsNullOrEmpty(csrDetails.Locality /**/)) { xn.Locality = csrDetails.Locality; // L; } if (!string.IsNullOrEmpty(csrDetails.Organization /**/)) { xn.Organization = csrDetails.Organization; // O; } if (!string.IsNullOrEmpty(csrDetails.OrganizationUnit /**/)) { xn.OrganizationUnit = csrDetails.OrganizationUnit; // OU; } if (!string.IsNullOrEmpty(csrDetails.Description /**/)) { xn.Description = csrDetails.Description; // D; } if (!string.IsNullOrEmpty(csrDetails.Surname /**/)) { xn.Surname = csrDetails.Surname; // S; } if (!string.IsNullOrEmpty(csrDetails.GivenName /**/)) { xn.Given = csrDetails.GivenName; // G; } if (!string.IsNullOrEmpty(csrDetails.Initials /**/)) { xn.Initials = csrDetails.Initials; // I; } if (!string.IsNullOrEmpty(csrDetails.Title /**/)) { xn.Title = csrDetails.Title; // T; } if (!string.IsNullOrEmpty(csrDetails.SerialNumber /**/)) { xn.SerialNumber = csrDetails.SerialNumber; // SN; } if (!string.IsNullOrEmpty(csrDetails.UniqueIdentifier /**/)) { xn.UniqueIdentifier = csrDetails.UniqueIdentifier; // UID; } var xr = new X509Request(0, xn, rsaKeys); var md = MessageDigest.CreateByName(messageDigest); xr.Sign(rsaKeys, md); using (var bio = BIO.MemoryBuffer()) { xr.Write(bio); return(new Csr(bio.ReadString())); } }
protected Csr GenerateCsr(CsrDetails csrDetails, RsaPrivateKey rsaKeyPair, string messageDigest = "SHA256") { var rsaKeys = CryptoKey.FromPrivateKey(rsaKeyPair.Pem, null); // Translate from our external form to our OpenSSL internal form // Ref: https://www.openssl.org/docs/manmaster/crypto/X509_NAME_new.html var xn = new X509Name(); if (!string.IsNullOrEmpty(csrDetails.CommonName /**/)) { xn.Common = csrDetails.CommonName; // CN; } if (!string.IsNullOrEmpty(csrDetails.Country /**/)) { xn.Country = csrDetails.Country; // C; } if (!string.IsNullOrEmpty(csrDetails.StateOrProvince /**/)) { xn.StateOrProvince = csrDetails.StateOrProvince; // ST; } if (!string.IsNullOrEmpty(csrDetails.Locality /**/)) { xn.Locality = csrDetails.Locality; // L; } if (!string.IsNullOrEmpty(csrDetails.Organization /**/)) { xn.Organization = csrDetails.Organization; // O; } if (!string.IsNullOrEmpty(csrDetails.OrganizationUnit /**/)) { xn.OrganizationUnit = csrDetails.OrganizationUnit; // OU; } if (!string.IsNullOrEmpty(csrDetails.Description /**/)) { xn.Description = csrDetails.Description; // D; } if (!string.IsNullOrEmpty(csrDetails.Surname /**/)) { xn.Surname = csrDetails.Surname; // S; } if (!string.IsNullOrEmpty(csrDetails.GivenName /**/)) { xn.Given = csrDetails.GivenName; // G; } if (!string.IsNullOrEmpty(csrDetails.Initials /**/)) { xn.Initials = csrDetails.Initials; // I; } if (!string.IsNullOrEmpty(csrDetails.Title /**/)) { xn.Title = csrDetails.Title; // T; } if (!string.IsNullOrEmpty(csrDetails.SerialNumber /**/)) { xn.SerialNumber = csrDetails.SerialNumber; // SN; } if (!string.IsNullOrEmpty(csrDetails.UniqueIdentifier /**/)) { xn.UniqueIdentifier = csrDetails.UniqueIdentifier; // UID; } var xr = new X509Request(0, xn, rsaKeys); if (csrDetails.AlternativeNames != null) { // Format the common name as the first alternative name var commonName = $"{EXT_SAN_PREFIX_DNS}:{xn.Common}"; // Concat with all subsequent alternative names var altNames = commonName + string.Join("", csrDetails.AlternativeNames.Select( x => $",{EXT_SAN_PREFIX_DNS}:{x}")); // Assemble and add the SAN extension value var extensions = new OpenSSL.Core.Stack <X509Extension>(); extensions.Add(new X509Extension(xr, EXT_NAME_SAN, false, altNames)); xr.AddExtensions(extensions); } var md = MessageDigest.CreateByName(messageDigest); xr.Sign(rsaKeys, md); using (var bio = BIO.MemoryBuffer()) { xr.Write(bio); return(new Csr(bio.ReadString())); } }