private void lengthTest(string type, IList headers, byte[] data) { StringWriter sw = new StringWriter(); PemWriter pWrt = new PemWriter(sw); PemObject pemObj = new PemObject(type, headers, data); pWrt.WriteObject(pemObj); pWrt.Writer.Close(); Assert.AreEqual(sw.ToString().Length, pWrt.GetOutputSize(pemObj)); }
private void EncryptedTest(AsymmetricKeyParameter privKey, string algorithm) { StringWriter sw = new StringWriter(); PemWriter pWrt = new PemWriter(sw); Pkcs8Generator pkcs8 = new Pkcs8Generator(privKey, algorithm); pkcs8.Password = "******".ToCharArray(); pWrt.WriteObject(pkcs8); pWrt.Writer.Close(); String result = sw.ToString(); PemReader pRd = new PemReader(new StringReader(result), new Password("hello".ToCharArray())); AsymmetricKeyParameter rdKey = (AsymmetricKeyParameter)pRd.ReadObject(); pRd.Reader.Close(); Assert.AreEqual(privKey, rdKey); }
public string buildCsr() { string certparams = "CN=" + clientcode + ",E=" + email + ",C=AT,L=Vienna,ST=Austria,O=-,OU=-"; X509Name name = new X509Name(certparams); RsaKeyPairGenerator rkpg = new RsaKeyPairGenerator(); rkpg.Init(new KeyGenerationParameters(new SecureRandom(), 2048)); keyPair = rkpg.GenerateKeyPair(); Pkcs10CertificationRequest csr = new Pkcs10CertificationRequest("SHA512WITHRSA", name, keyPair.Public, null, keyPair.Private); StringBuilder stringBuilder = new StringBuilder(); PemWriter premWriter = new PemWriter(new StringWriter(stringBuilder)); premWriter.WriteObject(csr); premWriter.Writer.Flush(); string pemCertificationRequest = stringBuilder.ToString(); return(pemCertificationRequest); }
public ECKeyPair(int keylength) { ECKeyPairGenerator keyPairGenerator = new ECKeyPairGenerator(); keyPairGenerator.Init(new KeyGenerationParameters(new SecureRandom(), keylength)); AsymmetricCipherKeyPair keyPair = keyPairGenerator.GenerateKeyPair(); TextWriter writer1 = (TextWriter) new StringWriter(); PemWriter pemWriter1 = new PemWriter(writer1); pemWriter1.WriteObject((object)keyPair.Private); pemWriter1.Writer.Flush(); this.PrivateKey = writer1.ToString(); TextWriter writer2 = (TextWriter) new StringWriter(); PemWriter pemWriter2 = new PemWriter(writer2); pemWriter2.WriteObject((object)keyPair.Public); pemWriter2.Writer.Flush(); this.PublicKey = writer2.ToString(); }
/// <summary> /// 生成PEM格式的公钥和密钥 /// </summary> /// <param name="strength">长度</param> /// <returns>(PublicKey,PrivateKey)</returns> public static (string, string) GenerateKeyPair(int strength = 1024) { var r = new RsaKeyPairGenerator(); r.Init(new KeyGenerationParameters(new SecureRandom(), strength)); var keys = r.GenerateKeyPair(); TextWriter privateTextWriter = new StringWriter(); var privatePemWriter = new PemWriter(privateTextWriter); privatePemWriter.WriteObject(keys.Private); privatePemWriter.Writer.Flush(); TextWriter publicTextWriter = new StringWriter(); var publicPemWriter = new PemWriter(publicTextWriter); publicPemWriter.WriteObject(keys.Public); publicPemWriter.Writer.Flush(); return(publicTextWriter.ToString(), privateTextWriter.ToString()); }
public static void GeneratePKeys(int intSize) { //Generating p-128 keys 128 specifies strength var keyPair = GenerateKeys(intSize); TextWriter textWriter = new StringWriter(); PemWriter pemWriter = new PemWriter(textWriter); pemWriter.WriteObject(keyPair.Private); pemWriter.Writer.Flush(); string privateKey = textWriter.ToString(); pemWriter.WriteObject(keyPair.Public); pemWriter.Writer.Flush(); string publicKey = textWriter.ToString(); Console.WriteLine(privateKey); Console.WriteLine(publicKey); }
public static string GetPrivateKeyInPkcs8(this MsRSA rsa) { var privateKeyParameters = rsa.ExportParameters(true); var rsaKeyParameters = new RsaPrivateCrtKeyParameters( new BigInteger(1, privateKeyParameters.Modulus), new BigInteger(1, privateKeyParameters.Exponent), new BigInteger(1, privateKeyParameters.D), new BigInteger(1, privateKeyParameters.P), new BigInteger(1, privateKeyParameters.Q), new BigInteger(1, privateKeyParameters.DP), new BigInteger(1, privateKeyParameters.DQ), new BigInteger(1, privateKeyParameters.InverseQ)); using var writer = new StringWriter(); var pemWriter = new PemWriter(writer); var pkcs8 = new Pkcs8Generator(rsaKeyParameters); pemWriter.WriteObject(pkcs8); pemWriter.Writer.Close(); return(writer.ToString()); }
private static string ConvertCertificateToPem(X509Certificate certificate) { var generator = new MiscPemGenerator(certificate); string certificateString; using (var textWriter = new StringWriter()) { var writer = new PemWriter(textWriter); writer.WriteObject(generator); writer.Writer.Flush(); certificateString = textWriter.ToString(); } if (string.IsNullOrWhiteSpace(certificateString)) { throw new InvalidOperationException(); } return(certificateString); }
// converts bouncy castle objects of type // X509Certificate, X509Crl, AsymmetricCipherKeyPair, AsymmetricKeyParameter, // IX509AttributeCertificate, Pkcs10CertificationRequest, Asn1.Cms.ContentInfo // to PEM format string private static string ToPem(object obj) { using (var mem = new MemoryStream()) using (var writer = new StreamWriter(mem)) { var pem = new PemWriter(writer); pem.WriteObject(obj); // force the pem write to flush it's data - kind of abnoxious you have to do that pem.Writer.Flush(); // create a stream reader to read the data. using (var reader = new StreamReader(mem)) { mem.Position = 0; string pemStr = reader.ReadToEnd(); return(pemStr); } } }
private void DoWriteReadTest( AsymmetricKeyParameter akp, string algorithm) { StringWriter sw = new StringWriter(); PemWriter pw = new PemWriter(sw); pw.WriteObject(akp, algorithm, testPassword, random); pw.Writer.Close(); string data = sw.ToString(); PemReader pr = new PemReader(new StringReader(data), new Password(testPassword)); AsymmetricCipherKeyPair kp = pr.ReadObject() as AsymmetricCipherKeyPair; if (kp == null || !kp.Private.Equals(akp)) { Fail("Failed to read back test key encoded with: " + algorithm); } }
/// <summary> /// 私钥XML2PEM /// </summary> private static void XMLConvertToPEM()//XML格式密钥转PEM { var rsa2 = new RSACryptoServiceProvider(); using (var sr = new StreamReader("D:\\keys\\private.key")) { rsa2.FromXmlString(sr.ReadToEnd()); } var p = rsa2.ExportParameters(true); var key = new RsaPrivateCrtKeyParameters( new Org.BouncyCastle.Math.BigInteger(1, p.Modulus), new Org.BouncyCastle.Math.BigInteger(1, p.Exponent), new Org.BouncyCastle.Math.BigInteger(1, p.D), new Org.BouncyCastle.Math.BigInteger(1, p.P), new Org.BouncyCastle.Math.BigInteger(1, p.Q), new Org.BouncyCastle.Math.BigInteger(1, p.DP), new Org.BouncyCastle.Math.BigInteger(1, p.DQ), new Org.BouncyCastle.Math.BigInteger(1, p.InverseQ)); using (var sw = new StreamWriter("D:\\keys\\PrivateKey.pem")) { var pemWriter = new PemWriter(sw); pemWriter.WriteObject(key); } }
public static void CreateSelfSignedCertificate(Certificate certInfo, string certificateFile, string keyFile) { var rndGen = new CryptoApiRandomGenerator(); var rnd = new SecureRandom(rndGen); var keyGenParams = new KeyGenerationParameters(rnd, 2048); var keyPairGen = new RsaKeyPairGenerator(); // var keyGenParams = new ECKeyGenerationParameters(SecObjectIdentifiers.SecP256r1, rnd); // var keyPairGen = new ECKeyPairGenerator(); keyPairGen.Init(keyGenParams); var keyPair = keyPairGen.GenerateKeyPair(); var certGen = new X509V3CertificateGenerator(); var serialNo = BigIntegers.CreateRandomInRange( BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), rnd); certGen.SetSerialNumber(serialNo); certGen.SetSubjectDN(certInfo.X509Name()); certGen.SetIssuerDN(certInfo.X509Name()); var now = DateTime.UtcNow.Date; certGen.SetNotBefore(now); certGen.SetNotAfter(now.AddDays(certInfo.ValidDays)); certGen.SetPublicKey(keyPair.Public); var sigFac = new Asn1SignatureFactory("SHA256WithRSA", keyPair.Private, rnd); var cert = certGen.Generate(sigFac); using (var w = new StreamWriter(certificateFile, false, Encoding.ASCII)) { var pemWriter = new PemWriter(w); pemWriter.WriteObject(cert); } using (var w = new StreamWriter(keyFile, false, Encoding.ASCII)) { var pemWriter = new PemWriter(w); pemWriter.WriteObject(keyPair); } }
/// <summary> /// Generate Pkcs8 format RSA key. Result: Index 0 is the private key and index 1 is the public key /// </summary> /// <param name="keySize">Key Size.Unit: bits</param> /// <param name="format">Whether the format is true If it is standard pem file format</param> /// <returns></returns> public static List <string> Pkcs8Key(int keySize, bool format) { List <string> res = new List <string>(); IAsymmetricCipherKeyPairGenerator kpGen = GeneratorUtilities.GetKeyPairGenerator("RSA"); kpGen.Init(new KeyGenerationParameters(new SecureRandom(), keySize)); var keyPair = kpGen.GenerateKeyPair(); StringWriter swpri = new StringWriter(); PemWriter pWrtpri = new PemWriter(swpri); Pkcs8Generator pkcs8 = new Pkcs8Generator(keyPair.Private); pWrtpri.WriteObject(pkcs8); pWrtpri.Writer.Close(); string privateKey = swpri.ToString(); if (!format) { privateKey = privateKey.Replace("-----BEGIN PRIVATE KEY-----", "").Replace("-----END PRIVATE KEY-----", "").Replace("\r\n", ""); } res.Add(privateKey); StringWriter swpub = new StringWriter(); PemWriter pWrtpub = new PemWriter(swpub); pWrtpub.WriteObject(keyPair.Public); pWrtpub.Writer.Close(); string publicKey = swpub.ToString(); if (!format) { publicKey = publicKey.Replace("-----BEGIN PUBLIC KEY-----", "").Replace("-----END PUBLIC KEY-----", "").Replace("\r\n", ""); } res.Add(publicKey); return(res); }
private static string EncryptPrivateKey(AsymmetricKeyParameter privateKey, string password) { // Create salts byte[] aesIv = new byte[16]; byte[] keySalt = new byte[20]; SecureRandom randomGen = new SecureRandom(); randomGen.NextBytes(aesIv); randomGen.NextBytes(keySalt); try { PrivateKeyInfo decryptedPrivateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey); // Prepare encryption Pkcs5S2ParametersGenerator pkcs5S2Gen = new Pkcs5S2ParametersGenerator(); pkcs5S2Gen.Init(PKCS5PasswordToBytes(password.ToCharArray()), keySalt, hashIterationCount); ICipherParameters cipherParams = pkcs5S2Gen.GenerateDerivedParameters(NistObjectIdentifiers.IdAes256Cbc.Id, 256); IBufferedCipher cipher = CipherUtilities.GetCipher(NistObjectIdentifiers.IdAes256Cbc); cipher.Init(true, new ParametersWithIV(cipherParams, aesIv)); // Generate encrypted private key info Asn1OctetString aesIvOctetString = new DerOctetString(aesIv); KeyDerivationFunc keyFunction = new KeyDerivationFunc(PkcsObjectIdentifiers.IdPbkdf2, new Pbkdf2Params(keySalt, hashIterationCount)); EncryptionScheme encScheme = new EncryptionScheme(NistObjectIdentifiers.IdAes256Cbc, aesIvOctetString); Asn1EncodableVector encryptionInfo = new Asn1EncodableVector { keyFunction, encScheme }; AlgorithmIdentifier algIdentifier = new AlgorithmIdentifier(PkcsObjectIdentifiers.IdPbeS2, new DerSequence(encryptionInfo)); EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = new EncryptedPrivateKeyInfo(algIdentifier, cipher.DoFinal(decryptedPrivateKeyInfo.GetEncoded())); Org.BouncyCastle.Utilities.IO.Pem.PemObject pkPemObject = new Org.BouncyCastle.Utilities.IO.Pem.PemObject("ENCRYPTED PRIVATE KEY", encryptedPrivateKeyInfo.GetEncoded()); // Write the PEM object to a string StringWriter txtWriter = new StringWriter(); PemWriter pemWriter = new PemWriter(txtWriter); pemWriter.WriteObject(pkPemObject); pemWriter.Writer.Close(); return(txtWriter.ToString()); } catch (Exception e) { throw new CryptoException("Could not encrypt private key.", e); } }
public static string GenRSAKeyPair() { var generator = new RsaKeyPairGenerator(); var seed = Encoding.UTF8.GetBytes(""); var secureRandom = new SecureRandom(); secureRandom.SetSeed(seed); generator.Init(new KeyGenerationParameters(secureRandom, 4096)); var pair = generator.GenerateKeyPair(); //第一种方案 //var privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(pair.Private); //var serializedPrivateBytes = privateKeyInfo.ToAsn1Object().GetDerEncoded(); //var serializedPrivate = Convert.ToBase64String(serializedPrivateBytes); //Console.WriteLine("Private Key:" + serializedPrivate); //var publickKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pair.Public); //var serializedPublicBytes = publickKeyInfo.ToAsn1Object().GetDerEncoded(); //var serializedPublic = Convert.ToBase64String(serializedPublicBytes); //Console.WriteLine("Public Key:" + serializedPublic); //第二种方案 var twPrivate = new StringWriter(); PemWriter pwPrivate = new PemWriter(twPrivate); pwPrivate.WriteObject(pair.Private); pwPrivate.Writer.Flush(); var privateKey = twPrivate.ToString(); Console.WriteLine("Private Key:" + privateKey); var twPublic = new StringWriter(); PemWriter pwPublic = new PemWriter(twPublic); pwPublic.WriteObject(pair.Public); pwPublic.Writer.Flush(); var publicKey = twPublic.ToString(); Console.WriteLine("Public Key:" + publicKey); return(privateKey); }
public static KeyParameter Pkcs8(int keySize = 2048, bool format = false) { var keyGenerator = GeneratorUtilities.GetKeyPairGenerator("RSA"); keyGenerator.Init(new KeyGenerationParameters(new SecureRandom(), keySize)); var keyPair = keyGenerator.GenerateKeyPair(); var subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public); var privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyPair.Private); if (!format) { return(new KeyParameter { PrivateKey = Base64.ToBase64String(privateKeyInfo.GetEncoded()), PublicKey = Base64.ToBase64String(subjectPublicKeyInfo.GetEncoded()) }); } var rsaKey = new KeyParameter(); using (var sw = new StringWriter()) { var pWrt = new PemWriter(sw); var pkcs8 = new Pkcs8Generator(keyPair.Private); pWrt.WriteObject(pkcs8); pWrt.Writer.Close(); rsaKey.PrivateKey = sw.ToString(); } using (var sw = new StringWriter()) { var pWrt = new PemWriter(sw); pWrt.WriteObject(keyPair.Public); pWrt.Writer.Close(); rsaKey.PublicKey = sw.ToString(); } return(rsaKey); }
private KeyContext GenerateSshKey() { var random = new SecureRandom(new CryptoApiRandomGenerator()); var strength = 2048; var parameters = new KeyGenerationParameters(random, strength); var keyPairGenerator = new RsaKeyPairGenerator(); keyPairGenerator.Init(parameters); var keyPair = keyPairGenerator.GenerateKeyPair(); var keyContext = new KeyContext(); // var privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyPair.Private); // var privateKey = Convert.ToBase64String(privateKeyInfo.GetEncoded(Asn1Encodable.Ber)); using (var writer = new StringWriter()) { var pem = new PemWriter(writer); pem.WriteObject(keyPair.Private); keyContext.PrivateKey = writer.ToString(); } var publicKeyParameter = (RsaKeyParameters)keyPair.Public; using (var memory = new MemoryStream()) { WriteBytes(memory, Encoding.ASCII.GetBytes("ssh-rsa")); WriteBytes(memory, publicKeyParameter.Exponent.ToByteArray()); WriteBytes(memory, publicKeyParameter.Modulus.ToByteArray()); var publicKeyBase64 = Convert.ToBase64String(memory.ToArray()); keyContext.PublicKey = $"ssh-rsa {publicKeyBase64} generated-key"; } _secretTracker.AddSecret(keyContext.PrivateKey); return(keyContext); }
/// <summary> /// Generates the certificate for <see cref="ChallengeTypes.TlsAlpn01" /> validation. /// </summary> /// <param name="key">The key.</param> /// <param name="token">The <see cref="ChallengeTypes.TlsAlpn01" /> token.</param> /// <param name="subjectName">Name of the subject.</param> /// <param name="certificateKey">The certificate key pair.</param> /// <returns>The tls-alpn-01 certificate in PEM.</returns> public static string TlsAlpnCertificate(this IKey key, string token, string subjectName, IKey certificateKey) { var keyAuthz = key.KeyAuthorization(token); var hashed = DigestUtilities.CalculateDigest("SHA256", Encoding.UTF8.GetBytes(keyAuthz)); var(_, keyPair) = signatureAlgorithmProvider.GetKeyPair(certificateKey.ToDer()); var signatureFactory = new Asn1SignatureFactory(certificateKey.Algorithm.ToPkcsObjectId(), keyPair.Private, new SecureRandom()); var gen = new X509V3CertificateGenerator(); var certName = new X509Name($"CN={subjectName}"); var serialNo = BigInteger.ProbablePrime(120, new SecureRandom()); gen.SetSerialNumber(serialNo); gen.SetSubjectDN(certName); gen.SetIssuerDN(certName); gen.SetNotBefore(DateTime.UtcNow); gen.SetNotAfter(DateTime.UtcNow.AddDays(7)); gen.SetPublicKey(keyPair.Public); // SAN for validation var gns = new[] { new GeneralName(GeneralName.DnsName, subjectName) }; gen.AddExtension(X509Extensions.SubjectAlternativeName.Id, false, new GeneralNames(gns)); // ACME-TLS/1 gen.AddExtension( acmeValidationV1Id, true, hashed); var newCert = gen.Generate(signatureFactory); using (var sr = new StringWriter()) { var pemWriter = new PemWriter(sr); pemWriter.WriteObject(newCert); return(sr.ToString()); } }
/// <summary> /// Convert RSA Private Key from PKCS8 to PKCS1 format /// </summary> /// <param name="privateKey">Private Key</param> /// <returns></returns> public static string PrivateKeyPkcs8ToPkcs1(string privateKey) { privateKey = RsaPemFormatHelper.Pkcs8PrivateKeyFormat(privateKey); PemReader pr = new PemReader(new StringReader(privateKey)); RsaPrivateCrtKeyParameters kp = pr.ReadObject() as RsaPrivateCrtKeyParameters; AsymmetricKeyParameter keyParameter = PrivateKeyFactory.CreateKey(PrivateKeyInfoFactory.CreatePrivateKeyInfo(kp)); StringWriter sw = new StringWriter(); PemWriter pWrt = new PemWriter(sw); pWrt.WriteObject(keyParameter); pWrt.Writer.Close(); string result = sw.ToString(); return(result); }
private void keyPairTest( string name, AsymmetricCipherKeyPair pair) { MemoryStream bOut = new MemoryStream(); PemWriter pWrt = new PemWriter(new StreamWriter(bOut)); pWrt.WriteObject(pair.Public); pWrt.Writer.Close(); PemReader pemRd = new PemReader(new StreamReader(new MemoryStream(bOut.ToArray(), false))); AsymmetricKeyParameter pubK = (AsymmetricKeyParameter)pemRd.ReadObject(); if (!pubK.Equals(pair.Public)) { Fail("Failed public key read: " + name); } bOut = new MemoryStream(); pWrt = new PemWriter(new StreamWriter(bOut)); pWrt.WriteObject(pair.Private); pWrt.Writer.Close(); pemRd = new PemReader(new StreamReader(new MemoryStream(bOut.ToArray(), false))); AsymmetricCipherKeyPair kPair = (AsymmetricCipherKeyPair)pemRd.ReadObject(); if (!kPair.Private.Equals(pair.Private)) { Fail("Failed private key read: " + name); } if (!kPair.Public.Equals(pair.Public)) { Fail("Failed private key public read: " + name); } }
public static void ExportCertificate(BcCertificate cert, EncodingFormat fmt, Stream target) { if (fmt == EncodingFormat.PEM) { using (var tw = new StringWriter()) { var pw = new PemWriter(tw); pw.WriteObject(cert); var pemBytes = Encoding.UTF8.GetBytes(tw.GetStringBuilder().ToString()); target.Write(pemBytes, 0, pemBytes.Length); } } else if (fmt == EncodingFormat.DER) { var der = cert.GetEncoded(); target.Write(der, 0, der.Length); } else { throw new NotSupportedException("unsupported encoding format"); } }
/// <inheritdoc /> public async Task <string> ExportAsync(string name, char[] password, CancellationToken cancel = default(CancellationToken)) { string pem = ""; var key = await Store.GetAsync(name, cancel); UseEncryptedKey(key, pkey => { using (var sw = new StringWriter()) { var pkcs8 = new Pkcs8Generator(pkey, Pkcs8Generator.PbeSha1_3DES) { Password = password }; var pw = new PemWriter(sw); pw.WriteObject(pkcs8); pw.Writer.Flush(); pem = sw.ToString(); } }); return(pem); }
private static void SavePemCertificate(CertificateChainWithPrivateKey certChainWithKey, string?password, string certFilePath, bool chain) { var keyFilePath = Path.ChangeExtension(certFilePath, ".key"); Logger.TraceInformation($"saving key to {keyFilePath}"); Logger.TraceInformation($"saving cert to {certFilePath}"); if (File.Exists(certFilePath) || File.Exists(keyFilePath)) { throw new ArgumentException("Cert or key file already exists. Please remove it or switch directories."); } Debug.Assert(certChainWithKey.Certificates.Length > 0); if (chain) { using var writer = new StreamWriter(certFilePath); var pem = new PemWriter(writer); foreach (var cert in certChainWithKey.Certificates) { pem.WriteObject(cert); } } else { using var writer = new StreamWriter(certFilePath); var pem = new PemWriter(writer); pem.WriteObject(certChainWithKey.Certificates[0]); } using (var writer = new StreamWriter(keyFilePath)) { var pem = new PemWriter(writer); var pemObjGenerator = password == null ? (Org.BouncyCastle.Utilities.IO.Pem.PemObjectGenerator) new Pkcs8Generator(certChainWithKey.PrivateKey) : new MiscPemGenerator(certChainWithKey.PrivateKey, "AES-256-CBC", password.ToCharArray(), new SecureRandom()); pem.WriteObject(pemObjGenerator); } }
public static AsymmetricCipherKeyPair CreateKeyAndSave(string name) { var fileName = GetKeyPath(name); if (File.Exists(fileName)) { Debug.WriteLine($"Deleting existing key: {fileName}"); File.Delete(fileName); } var key = CreateKey(); using (var fileWriter = new StreamWriter(fileName)) { var pem = new PemWriter(fileWriter); pem.WriteObject(key.Private); pem.Writer.Flush(); fileWriter.Close(); } return(key); }
private static void PrintPrivateKey(BigInteger pkey, DerObjectIdentifier algId) { var ecpkey = new ECPrivateKeyParameters("ECGOST3410", pkey, algId); var pkeyEnc = new DerSequence( new DerInteger(0), new DerSequence( CryptoProObjectIdentifiers.GostR3410x2001, new DerSequence( ecpkey.PublicKeyParamSet, CryptoProObjectIdentifiers.GostR3411x94CryptoProParamSet ) ), new DerOctetString(new DerInteger(ecpkey.D)) ); var pemObject = new PemObject("PRIVATE KEY", pkeyEnc.GetDerEncoded()); using (var sw = new StreamWriter(Console.OpenStandardOutput())) { var writer = new PemWriter(sw); writer.WriteObject(pemObject); } }
static void CreatePem(RsaKeyParameters key) { TextWriter textWriter = new StringWriter(); PemWriter pemWriter = new PemWriter(textWriter); string printKey; string fileLocation; pemWriter.WriteObject(key); pemWriter.Writer.Flush(); printKey = textWriter.ToString(); if (key.IsPrivate) { fileLocation = privateKeyFileLocation; } else { fileLocation = publicKeyFileLocation; } File.WriteAllText(fileLocation, printKey); }
/// <summary> /// Generate RSA key in Pkcs1 format. Result: Index 0 is the private key and index 1 is the public key /// </summary> /// <param name="keySize">Key Size.Unit: bits</param> /// <param name="format">Whether the format is true If it is standard pem file format</param> /// <returns></returns> public static List <string> Pkcs1Key(int keySize, bool format = true) { var res = new List <string>(); var kpGen = GeneratorUtilities.GetKeyPairGenerator("RSA"); kpGen.Init(new KeyGenerationParameters(new SecureRandom(), keySize)); var keyPair = kpGen.GenerateKeyPair(); var sw = new StringWriter(); var pWrt = new PemWriter(sw); pWrt.WriteObject(keyPair.Private); pWrt.Writer.Flush(); var privateKey = sw.ToString(); if (!format) { privateKey = privateKey.Replace("-----BEGIN RSA PRIVATE KEY-----", "").Replace("-----END RSA PRIVATE KEY-----", "").Replace("\r\n", ""); } res.Add(privateKey); var swpub = new StringWriter(); var pWrtpub = new PemWriter(swpub); pWrtpub.WriteObject(keyPair.Public); pWrtpub.Writer.Flush(); var publicKey = swpub.ToString(); if (!format) { publicKey = publicKey.Replace("-----BEGIN PUBLIC KEY-----", "").Replace("-----END PUBLIC KEY-----", "").Replace("\r\n", ""); } res.Add(publicKey); return(res); }
public static string GenerateRSAKeyAsPEM(int keySize) { try { IAsymmetricCipherKeyPairGenerator generator = GeneratorUtilities.GetKeyPairGenerator("RSA"); RsaKeyGenerationParameters generatorParams = new RsaKeyGenerationParameters( BigInteger.ValueOf(0x10001), new SecureRandom(), keySize, 12); generator.Init(generatorParams); AsymmetricCipherKeyPair keyPair = generator.GenerateKeyPair(); using (StringWriter sw = new StringWriter()) { PemWriter pemWriter = new PemWriter(sw); pemWriter.WriteObject(keyPair); return(sw.ToString()); } } catch (Exception e) { logger.Error($"Could not generate new key pair: {e.Message}"); return(null); } }
/// <summary> /// Convert RSA Private Key from PKCS1 to PKCS8 format /// </summary> /// <param name="privateKey">Private Key</param> /// <returns></returns> public static string PrivateKeyPkcs1ToPkcs8(string privateKey) { privateKey = RsaPemFormatHelper.Pkcs1PrivateKeyFormat(privateKey); PemReader pr = new PemReader(new StringReader(privateKey)); AsymmetricCipherKeyPair kp = pr.ReadObject() as AsymmetricCipherKeyPair; StringWriter sw = new StringWriter(); PemWriter pWrt = new PemWriter(sw); Pkcs8Generator pkcs8 = new Pkcs8Generator(kp.Private); pWrt.WriteObject(pkcs8); pWrt.Writer.Close(); string result = sw.ToString(); return(result); }
/// <summary> /// Private Key Convert xml->Pkcs8 /// </summary> /// <param name="privateKey"></param> /// <returns></returns> public static string PrivateKeyXmlToPkcs8(string privateKey) { XElement root = XElement.Parse(privateKey); //Modulus var modulus = root.Element("Modulus"); //Exponent var exponent = root.Element("Exponent"); //P var p = root.Element("P"); //Q var q = root.Element("Q"); //DP var dp = root.Element("DP"); //DQ var dq = root.Element("DQ"); //InverseQ var inverseQ = root.Element("InverseQ"); //D var d = root.Element("D"); RsaPrivateCrtKeyParameters rsaPrivateCrtKeyParameters = new RsaPrivateCrtKeyParameters( new BigInteger(1, Convert.FromBase64String(modulus.Value)), new BigInteger(1, Convert.FromBase64String(exponent.Value)), new BigInteger(1, Convert.FromBase64String(d.Value)), new BigInteger(1, Convert.FromBase64String(p.Value)), new BigInteger(1, Convert.FromBase64String(q.Value)), new BigInteger(1, Convert.FromBase64String(dp.Value)), new BigInteger(1, Convert.FromBase64String(dq.Value)), new BigInteger(1, Convert.FromBase64String(inverseQ.Value))); StringWriter swpri = new StringWriter(); PemWriter pWrtpri = new PemWriter(swpri); Pkcs8Generator pkcs8 = new Pkcs8Generator(rsaPrivateCrtKeyParameters); pWrtpri.WriteObject(pkcs8); pWrtpri.Writer.Close(); return(swpri.ToString()); }
public static string PublicKeyXmlToPem(string publicKey) { var root = XElement.Parse(publicKey); //Modulus var modulus = root.Element("Modulus"); //Exponent var exponent = root.Element("Exponent"); var rsaKeyParameters = new RsaKeyParameters( false, new BigInteger(1, Convert.FromBase64String(modulus !.Value)), new BigInteger(1, Convert.FromBase64String(exponent !.Value))); using var writer = new StringWriter(); var pemWriter = new PemWriter(writer); pemWriter.WriteObject(rsaKeyParameters); pemWriter.Writer.Close(); return(writer.ToString()); }
public void TestPkcs8Plain() { IAsymmetricCipherKeyPairGenerator kpGen = GeneratorUtilities.GetKeyPairGenerator("RSA"); kpGen.Init(new KeyGenerationParameters(new SecureRandom(), 1024)); IAsymmetricKeyParameter privKey = kpGen.GenerateKeyPair().Private; StringWriter sw = new StringWriter(); PemWriter pWrt = new PemWriter(sw); Pkcs8Generator pkcs8 = new Pkcs8Generator(privKey); pWrt.WriteObject(pkcs8); pWrt.Writer.Close(); string result = sw.ToString(); PemReader pRd = new PemReader(new StringReader(result), new Password("hello".ToCharArray())); IAsymmetricKeyParameter rdKey = (AsymmetricKeyParameter)pRd.ReadObject(); pRd.Reader.Close(); Assert.AreEqual(privKey, rdKey); }
public override void PerformTest() { IPasswordFinder pGet = new Password("secret".ToCharArray()); PemReader pemRd = OpenPemResource("test.pem", pGet); IAsymmetricCipherKeyPair pair; object o; while ((o = pemRd.ReadObject()) != null) { // if (o is AsymmetricCipherKeyPair) // { // ackp = (AsymmetricCipherKeyPair)o; // // Console.WriteLine(ackp.Public); // Console.WriteLine(ackp.Private); // } // else // { // Console.WriteLine(o.ToString()); // } } // // pkcs 7 data // pemRd = OpenPemResource("pkcs7.pem", null); ContentInfo d = (ContentInfo)pemRd.ReadObject(); if (!d.ContentType.Equals(CmsObjectIdentifiers.EnvelopedData)) { Fail("failed envelopedData check"); } /* { // // ECKey // pemRd = OpenPemResource("eckey.pem", null); // TODO Resolve return type issue with EC keys and fix PemReader to return parameters // ECNamedCurveParameterSpec spec = (ECNamedCurveParameterSpec)pemRd.ReadObject(); pair = (AsymmetricCipherKeyPair)pemRd.ReadObject(); ISigner sgr = SignerUtilities.GetSigner("ECDSA"); sgr.Init(true, pair.Private); byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' }; sgr.BlockUpdate(message, 0, message.Length); byte[] sigBytes = sgr.GenerateSignature(); sgr.Init(false, pair.Public); sgr.BlockUpdate(message, 0, message.Length); if (!sgr.VerifySignature(sigBytes)) { Fail("EC verification failed"); } // TODO Resolve this issue with the algorithm name, study Java version // if (!((ECPublicKeyParameters) pair.Public).AlgorithmName.Equals("ECDSA")) // { // Fail("wrong algorithm name on public got: " + ((ECPublicKeyParameters) pair.Public).AlgorithmName); // } // // if (!((ECPrivateKeyParameters) pair.Private).AlgorithmName.Equals("ECDSA")) // { // Fail("wrong algorithm name on private got: " + ((ECPrivateKeyParameters) pair.Private).AlgorithmName); // } } */ // // writer/parser test // IAsymmetricCipherKeyPairGenerator kpGen = GeneratorUtilities.GetKeyPairGenerator("RSA"); kpGen.Init( new RsaKeyGenerationParameters( BigInteger.ValueOf(0x10001), new SecureRandom(), 768, 25)); pair = kpGen.GenerateKeyPair(); keyPairTest("RSA", pair); // kpGen = KeyPairGenerator.getInstance("DSA"); // kpGen.initialize(512, new SecureRandom()); DsaParametersGenerator pGen = new DsaParametersGenerator(); pGen.Init(512, 80, new SecureRandom()); kpGen = GeneratorUtilities.GetKeyPairGenerator("DSA"); kpGen.Init( new DsaKeyGenerationParameters( new SecureRandom(), pGen.GenerateParameters())); pair = kpGen.GenerateKeyPair(); keyPairTest("DSA", pair); // // PKCS7 // MemoryStream bOut = new MemoryStream(); PemWriter pWrt = new PemWriter(new StreamWriter(bOut)); pWrt.WriteObject(d); pWrt.Writer.Close(); pemRd = new PemReader(new StreamReader(new MemoryStream(bOut.ToArray(), false))); d = (ContentInfo)pemRd.ReadObject(); if (!d.ContentType.Equals(CmsObjectIdentifiers.EnvelopedData)) { Fail("failed envelopedData recode check"); } // OpenSSL test cases (as embedded resources) doOpenSslDsaTest("unencrypted"); doOpenSslRsaTest("unencrypted"); doOpenSslTests("aes128"); doOpenSslTests("aes192"); doOpenSslTests("aes256"); doOpenSslTests("blowfish"); doOpenSslTests("des1"); doOpenSslTests("des2"); doOpenSslTests("des3"); doOpenSslTests("rc2_128"); doOpenSslDsaTest("rc2_40_cbc"); doOpenSslRsaTest("rc2_40_cbc"); doOpenSslDsaTest("rc2_64_cbc"); doOpenSslRsaTest("rc2_64_cbc"); // TODO Figure out why exceptions differ for commented out cases doDudPasswordTest("7fd98", 0, "Corrupted stream - out of bounds length found"); doDudPasswordTest("ef677", 1, "Corrupted stream - out of bounds length found"); // doDudPasswordTest("800ce", 2, "cannot recognise object in stream"); doDudPasswordTest("b6cd8", 3, "DEF length 81 object truncated by 56"); doDudPasswordTest("28ce09", 4, "DEF length 110 object truncated by 28"); doDudPasswordTest("2ac3b9", 5, "DER length more than 4 bytes: 11"); doDudPasswordTest("2cba96", 6, "DEF length 100 object truncated by 35"); doDudPasswordTest("2e3354", 7, "DEF length 42 object truncated by 9"); doDudPasswordTest("2f4142", 8, "DER length more than 4 bytes: 14"); doDudPasswordTest("2fe9bb", 9, "DER length more than 4 bytes: 65"); doDudPasswordTest("3ee7a8", 10, "DER length more than 4 bytes: 57"); doDudPasswordTest("41af75", 11, "malformed sequence in DSA private key"); doDudPasswordTest("1704a5", 12, "corrupted stream detected"); // doDudPasswordTest("1c5822", 13, "corrupted stream detected"); // doDudPasswordTest("5a3d16", 14, "corrupted stream detected"); doDudPasswordTest("8d0c97", 15, "corrupted stream detected"); doDudPasswordTest("bc0daf", 16, "corrupted stream detected"); doDudPasswordTest("aaf9c4d",17, "Corrupted stream - out of bounds length found"); // encrypted private key test pGet = new Password("password".ToCharArray()); pemRd = OpenPemResource("enckey.pem", pGet); RsaPrivateCrtKeyParameters privKey = (RsaPrivateCrtKeyParameters)pemRd.ReadObject(); if (!privKey.PublicExponent.Equals(new BigInteger("10001", 16))) { Fail("decryption of private key data check failed"); } // general PKCS8 test pGet = new Password("password".ToCharArray()); pemRd = OpenPemResource("pkcs8test.pem", pGet); while ((privKey = (RsaPrivateCrtKeyParameters)pemRd.ReadObject()) != null) { if (!privKey.PublicExponent.Equals(new BigInteger("10001", 16))) { Fail("decryption of private key data check failed"); } } }
private void keyPairTest( string name, IAsymmetricCipherKeyPair pair) { MemoryStream bOut = new MemoryStream(); PemWriter pWrt = new PemWriter(new StreamWriter(bOut)); pWrt.WriteObject(pair.Public); pWrt.Writer.Close(); PemReader pemRd = new PemReader(new StreamReader(new MemoryStream(bOut.ToArray(), false))); IAsymmetricKeyParameter pubK = (AsymmetricKeyParameter) pemRd.ReadObject(); if (!pubK.Equals(pair.Public)) { Fail("Failed public key read: " + name); } bOut = new MemoryStream(); pWrt = new PemWriter(new StreamWriter(bOut)); pWrt.WriteObject(pair.Private); pWrt.Writer.Close(); pemRd = new PemReader(new StreamReader(new MemoryStream(bOut.ToArray(), false))); IAsymmetricCipherKeyPair kPair = (AsymmetricCipherKeyPair) pemRd.ReadObject(); if (!kPair.Private.Equals(pair.Private)) { Fail("Failed private key read: " + name); } if (!kPair.Public.Equals(pair.Public)) { Fail("Failed private key public read: " + name); } }