public PemObject Generate() { if (algorithm == null) { PrivateKeyInfo pki = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privKey); return(new PemObject("PRIVATE KEY", pki.GetEncoded())); } // TODO Theoretically, the amount of salt needed depends on the algorithm byte[] salt = new byte[20]; if (random == null) { random = new SecureRandom(); } random.NextBytes(salt); try { EncryptedPrivateKeyInfo epki = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo( algorithm, password, salt, iterationCount, privKey); return(new PemObject("ENCRYPTED PRIVATE KEY", epki.GetEncoded())); } catch (Exception e) { throw new PemGenerationException("Couldn't encrypt private key", e); } }
/// <summary> /// Returns the specified XML RSA key <c>string</c> converted to the PEM format. /// </summary> /// <param name="xml">The XML <c>string</c> containing the RSA key.</param> /// <returns>System.String.</returns> /// <exception cref="InvalidKeyException">Invalid XML RSA Key</exception> public static string XmlToPem(this string xml) { using (var rsa = RSA.Create()) { rsa.FromXmlStringNetCore(xml); // Try to get the private and public key pair first. AsymmetricCipherKeyPair keyPair = DotNetUtilities.GetRsaKeyPair(rsa); if (keyPair != null) { PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyPair.Private); return(FormatPem(Convert.ToBase64String(privateKeyInfo.GetEncoded()), "RSA PRIVATE KEY")); } // At this point, the XML RSA key contains only the public key. RsaKeyParameters publicKey = DotNetUtilities.GetRsaPublicKey(rsa); if (publicKey != null) { SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey); return(FormatPem(Convert.ToBase64String(publicKeyInfo.GetEncoded()), "PUBLIC KEY")); } } throw new InvalidKeyException("Invalid XML RSA Key"); }
public static string XmlStringToPem(this string xml) { try { using (RSA rsa = RSA.Create()) { rsa.FromXmlString(xml); var keyPair = DotNetUtilities.GetRsaKeyPair(rsa); if (keyPair != null) { PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyPair.Private); return(FormatPem(Convert.ToBase64String(privateKeyInfo.GetEncoded()), "RSA PRIVATE KEY")); } var publicKey = DotNetUtilities.GetRsaPublicKey(rsa); if (publicKey != null) { SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey); return(FormatPem(Convert.ToBase64String(publicKeyInfo.GetEncoded()), "PUBLIC KEY")); } } } catch (Exception e) { throw new InvalidKeyException("Invalid RSA Xml Key", e); } throw new InvalidKeyException("Keys were not found"); }
public static EncryptedPrivateKeyInfo CreateEncryptedPrivateKeyInfo( string algorithm, char[] passPhrase, byte[] salt, int iterationCount, PrivateKeyInfo keyInfo) { IBufferedCipher cipher = PbeUtilities.CreateEngine(algorithm) as IBufferedCipher; if (cipher == null) { throw new Exception("Unknown encryption algorithm: " + algorithm); } Asn1Encodable pbeParameters = PbeUtilities.GenerateAlgorithmParameters( algorithm, salt, iterationCount); ICipherParameters cipherParameters = PbeUtilities.GenerateCipherParameters( algorithm, passPhrase, pbeParameters); cipher.Init(true, cipherParameters); byte[] encoding = cipher.DoFinal(keyInfo.GetEncoded()); DerObjectIdentifier oid = PbeUtilities.GetObjectIdentifier(algorithm); AlgorithmIdentifier algID = new AlgorithmIdentifier(oid, pbeParameters); return(new EncryptedPrivateKeyInfo(algID, encoding)); }
public static EncryptedPrivateKeyInfo CreateEncryptedPrivateKeyInfo( DerObjectIdentifier cipherAlgorithm, DerObjectIdentifier prfAlgorithm, char[] passPhrase, byte[] salt, int iterationCount, SecureRandom random, PrivateKeyInfo keyInfo) { IBufferedCipher cipher = CipherUtilities.GetCipher(cipherAlgorithm) as IBufferedCipher; if (cipher == null) { throw new Exception("Unknown encryption algorithm: " + cipherAlgorithm); } Asn1Encodable pbeParameters = PbeUtilities.GenerateAlgorithmParameters( cipherAlgorithm, prfAlgorithm, salt, iterationCount, random); ICipherParameters cipherParameters = PbeUtilities.GenerateCipherParameters( PkcsObjectIdentifiers.IdPbeS2, passPhrase, pbeParameters); cipher.Init(true, cipherParameters); byte[] encoding = cipher.DoFinal(keyInfo.GetEncoded()); AlgorithmIdentifier algID = new AlgorithmIdentifier(PkcsObjectIdentifiers.IdPbeS2, pbeParameters); return(new EncryptedPrivateKeyInfo(algID, encoding)); }
public string Encode(bool Private, bool Public) { string derPublicKey; string derPrivateKey; string retval; derPrivateKey = ""; derPublicKey = ""; switch (this.Type) { case "RSA": if (this._containsprivatekey == true && Private == true) { PrivateKeyInfo infoPrivate = PrivateKeyInfoFactory.CreatePrivateKeyInfo(this.PrivateKey); derPrivateKey = Convert.ToBase64String(infoPrivate.GetEncoded()); } if (this._containspublickey = true && Public == true) { SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(this.PublicKey); derPublicKey = Convert.ToBase64String(publicKeyInfo.GetEncoded()); } retval = this.UUID.ToString() + "!RSA!" + this.Length.ToString() + "!" + derPublicKey + "!" + derPrivateKey; break; default: retval = this.UUID.ToString() + "!NONE!!!"; break; } return(retval); }
public PemObject Generate() { if (this.algorithm == null) { PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(this.privKey); return(new PemObject("PRIVATE KEY", privateKeyInfo.GetEncoded())); } byte[] array = new byte[20]; if (this.random == null) { this.random = new SecureRandom(); } this.random.NextBytes(array); PemObject result; try { EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo(this.algorithm, this.password, array, this.iterationCount, this.privKey); result = new PemObject("ENCRYPTED PRIVATE KEY", encryptedPrivateKeyInfo.GetEncoded()); } catch (Exception exception) { throw new PemGenerationException("Couldn't encrypt private key", exception); } return(result); }
private void checkCertReqMsgWithArchiveControl(AsymmetricCipherKeyPair kp, CertificateRequestMessage certReqMessage) { var archiveControl = (PkiArchiveControl)certReqMessage.GetControl(CrmfObjectIdentifiers.id_regCtrl_pkiArchiveOptions); IsEquals("Archive type", PkiArchiveControl.encryptedPrivKey, archiveControl.ArchiveType); IsTrue(archiveControl.EnvelopedData); RecipientInformationStore recips = archiveControl.GetEnvelopedData().GetRecipientInfos(); ArrayList collection = (ArrayList)recips.GetRecipients(); IsTrue(collection.Count == 1); KeyTransRecipientInformation info = (KeyTransRecipientInformation)collection[0]; EncKeyWithID encKeyWithId = EncKeyWithID.GetInstance(info.GetContent(kp.Private)); IsTrue(encKeyWithId.HasIdentifier); IsTrue(!encKeyWithId.IsIdentifierUtf8String); // GeneralName at this point. IsTrue("Name", X509Name.GetInstance(GeneralName.GetInstance(encKeyWithId.Identifier).Name).Equivalent(new X509Name("CN=Test"))); PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(kp.Private); IsTrue("Private Key", Arrays.AreEqual(privateKeyInfo.GetEncoded(), encKeyWithId.PrivateKey.GetEncoded())); }
public static EncryptedPrivateKeyInfo CreateEncryptedPrivateKeyInfo( string algorithm, char[] passPhrase, byte[] salt, int iterationCount, PrivateKeyInfo keyInfo) { if (!PbeUtilities.IsPbeAlgorithm(algorithm)) { throw new ArgumentException("attempt to use non-PBE algorithm with PBE EncryptedPrivateKeyInfo generation"); } IBufferedCipher cipher = PbeUtilities.CreateEngine(algorithm) as IBufferedCipher; if (cipher == null) { // TODO Throw exception? } Asn1Encodable parameters = PbeUtilities.GenerateAlgorithmParameters( algorithm, salt, iterationCount); ICipherParameters keyParameters = PbeUtilities.GenerateCipherParameters( algorithm, passPhrase, parameters); cipher.Init(true, keyParameters); byte[] keyBytes = keyInfo.GetEncoded(); byte[] encoding = cipher.DoFinal(keyBytes); DerObjectIdentifier oid = PbeUtilities.GetObjectIdentifier(algorithm); AlgorithmIdentifier algID = new AlgorithmIdentifier(oid, parameters); return(new EncryptedPrivateKeyInfo(algID, encoding)); }
private void EncodePrivateKey() { X9ECParameters ecP = X962NamedCurves.GetByOid(X9ObjectIdentifiers.Prime239v3); // // named curve // X962Parameters _params = new X962Parameters(X9ObjectIdentifiers.Prime192v1); X9ECPoint pPoint = new X9ECPoint( new FPPoint(ecP.Curve, new FPFieldElement(BigInteger.Two, BigInteger.One), new FPFieldElement(BigInteger.ValueOf(4), BigInteger.ValueOf(3)), true)); Asn1OctetString p = (Asn1OctetString)pPoint.ToAsn1Object(); if (p == null) { Fail("failed to convert to ASN.1"); } PrivateKeyInfo info = new PrivateKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.IdECPublicKey, _params), new ECPrivateKeyStructure(BigInteger.Ten).ToAsn1Object()); if (!Arrays.AreEqual(info.GetEncoded(), namedPriv)) { Fail("failed private named generation"); } Asn1Object o = Asn1Object.FromByteArray(namedPriv); if (!info.Equals(o)) { Fail("failed private named equality"); } // // explicit curve parameters // _params = new X962Parameters(ecP); info = new PrivateKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.IdECPublicKey, _params), new ECPrivateKeyStructure(BigInteger.ValueOf(20)).ToAsn1Object()); if (!Arrays.AreEqual(info.GetEncoded(), expPriv)) { Fail("failed private explicit generation"); } o = Asn1Object.FromByteArray(expPriv); if (!info.Equals(o)) { Fail("failed private explicit equality"); } }
/// <summary> /// /// </summary> /// <param name="forPubKey"></param> /// <param name="forPrivKey"></param> /// <param name="keyStrength">1024, 2048,4096</param> /// <param name="exponent">Typically a fermat number 3, 5, 17, 257, 65537, 4294967297, 18446744073709551617,</param> /// <param name="certaninty">Should be 80 or higher depending on Key strength number (exponent)</param> public static void GenerateKeys(out string forPubKey, out string forPrivKey, int keyStrength, int exponent, int certaninty) { // Create key RsaKeyPairGenerator generator = new RsaKeyPairGenerator(); /* * This value should be a Fermat number. 0x10001 (F4) is current recommended value. 3 (F1) is known to be safe also. * 3, 5, 17, 257, 65537, 4294967297, 18446744073709551617, * * Practically speaking, Windows does not tolerate public exponents which do not fit in a 32-bit unsigned integer. Using e=3 or e=65537 works "everywhere". */ BigInteger exponentBigInt = new BigInteger(exponent.ToString()); var param = new RsaKeyGenerationParameters( exponentBigInt, // new BigInteger("10001", 16) publicExponent new SecureRandom(), // SecureRandom.getInstance("SHA1PRNG"),//prng keyStrength, //strength certaninty); //certainty generator.Init(param); AsymmetricCipherKeyPair keyPair = generator.GenerateKeyPair(); // Save to export format SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public); byte[] ret = info.GetEncoded(); forPubKey = Convert.ToBase64String(ret); // EncryptedPrivateKeyInfo asdf = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo( // DerObjectIdentifier.Ber,,,keyPair.Private); //TextWriter textWriter = new StringWriter(); //PemWriter pemWriter = new PemWriter(textWriter); //pemWriter.WriteObject(keyPair); //pemWriter.Writer.Flush(); //string ret2 = textWriter.ToString(); //// demonstration: how to serialise option 1 //TextReader tr = new StringReader(ret2); //PemReader read = new PemReader(tr); //AsymmetricCipherKeyPair something = (AsymmetricCipherKeyPair)read.ReadObject(); //// demonstration: how to serialise option 2 (don't know how to deserailize) //PrivateKeyInfo pKinfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyPair.Private); //byte[] privRet = pKinfo.GetEncoded(); //string forPrivKey2Test = Convert.ToBase64String(privRet); PrivateKeyInfo pKinfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyPair.Private); byte[] privRet = pKinfo.GetEncoded(); string forPrivKey2Test = Convert.ToBase64String(privRet); forPrivKey = forPrivKey2Test; }
private static byte[] EncodePrivateKey( AsymmetricKeyParameter akp, out string keyType) { PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(akp); AlgorithmIdentifier algID = info.PrivateKeyAlgorithm; DerObjectIdentifier oid = algID.Algorithm; if (oid.Equals(X9ObjectIdentifiers.IdDsa)) { keyType = "DSA PRIVATE KEY"; DsaParameter p = DsaParameter.GetInstance(algID.Parameters); BigInteger x = ((DsaPrivateKeyParameters)akp).X; BigInteger y = p.G.ModPow(x, p.P); // TODO Create an ASN1 object somewhere for this? return(new DerSequence( new DerInteger(0), new DerInteger(p.P), new DerInteger(p.Q), new DerInteger(p.G), new DerInteger(y), new DerInteger(x)).GetEncoded()); } if (oid.Equals(PkcsObjectIdentifiers.RsaEncryption)) { keyType = "RSA PRIVATE KEY"; return(info.ParsePrivateKey().GetEncoded()); } else if (oid.Equals(CryptoProObjectIdentifiers.GostR3410x2001) || oid.Equals(X9ObjectIdentifiers.IdECPublicKey)) { keyType = "EC PRIVATE KEY"; return(info.ParsePrivateKey().GetEncoded()); } else { keyType = "PRIVATE KEY"; return(info.GetEncoded()); } }
private void EncodePrivateKey() { X9ECParameters ecP = X962NamedCurves.GetByOid(X9ObjectIdentifiers.Prime192v1); // // named curve // X962Parameters _params = new X962Parameters(X9ObjectIdentifiers.Prime192v1); PrivateKeyInfo info = new PrivateKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.IdECPublicKey, _params), new ECPrivateKeyStructure(ecP.N.BitLength, BigInteger.Ten).ToAsn1Object()); if (!Arrays.AreEqual(info.GetEncoded(), namedPriv)) { Fail("failed private named generation"); } Asn1Object o = Asn1Object.FromByteArray(namedPriv); if (!info.Equals(o)) { Fail("failed private named equality"); } // // explicit curve parameters // ecP = X962NamedCurves.GetByOid(X9ObjectIdentifiers.Prime239v3); _params = new X962Parameters(ecP); info = new PrivateKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.IdECPublicKey, _params), new ECPrivateKeyStructure(ecP.N.BitLength, BigInteger.ValueOf(20)).ToAsn1Object()); if (!Arrays.AreEqual(info.GetEncoded(), expPriv)) { Fail("failed private explicit generation"); } o = Asn1Object.FromByteArray(expPriv); if (!info.Equals(o)) { Fail("failed private explicit equality"); } }
/// <summary> /// onvert RSA xml private key to pem private xml /// </summary> /// <param name="privatePem"></param> /// <returns></returns> public static string PrivateXmlToPem(string privateXml) { using (RSA rsa = RSA.Create()) { rsa.FromXmlString(privateXml); var keyPair = DotNetUtilities.GetRsaKeyPair(rsa); PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyPair.Private); var base64 = Convert.ToBase64String(privateKeyInfo.GetEncoded()); StringBuilder b = new StringBuilder(); b.Append("-----BEGIN PRIVATE KEY-----\n"); for (int i = 0; i < base64.Length; i += 64) { b.Append($"{ base64.Substring(i, Math.Min(64, base64.Length - i)) }\n"); } b.Append("-----END PRIVATE KEY-----\n"); return(b.ToString()); } }
public static EncryptedPrivateKeyInfo CreateEncryptedPrivateKeyInfo(string algorithm, char[] passPhrase, byte[] salt, int iterationCount, PrivateKeyInfo keyInfo) { IBufferedCipher bufferedCipher = PbeUtilities.CreateEngine(algorithm) as IBufferedCipher; if (bufferedCipher == null) { throw new global::System.Exception("Unknown encryption algorithm: " + algorithm); } Asn1Encodable asn1Encodable = PbeUtilities.GenerateAlgorithmParameters(algorithm, salt, iterationCount); ICipherParameters parameters = PbeUtilities.GenerateCipherParameters(algorithm, passPhrase, asn1Encodable); bufferedCipher.Init(forEncryption: true, parameters); byte[] encoding = bufferedCipher.DoFinal(keyInfo.GetEncoded()); DerObjectIdentifier objectIdentifier = PbeUtilities.GetObjectIdentifier(algorithm); AlgorithmIdentifier algId = new AlgorithmIdentifier(objectIdentifier, asn1Encodable); return(new EncryptedPrivateKeyInfo(algId, encoding)); }
public override void PerformTest() { PrivateKeyInfo privInfo1 = PrivateKeyInfo.GetInstance(priv); IsTrue(!privInfo1.HasPublicKey); PrivateKeyInfo privInfo2 = new PrivateKeyInfo(privInfo1.PrivateKeyAlgorithm, privInfo1.ParsePrivateKey()); IsTrue("enc 1 failed", AreEqual(priv, privInfo2.GetEncoded())); privInfo1 = PrivateKeyInfo.GetInstance(privWithPub); IsTrue(privInfo1.HasPublicKey); privInfo2 = new PrivateKeyInfo(privInfo1.PrivateKeyAlgorithm, privInfo1.ParsePrivateKey(), privInfo1.Attributes, privInfo1.PublicKeyData.GetOctets()); IsTrue("enc 2 failed", AreEqual(privWithPub, privInfo2.GetEncoded())); }
/// <summary> /// Create the encrypted private key info using the passed in encryptor. /// </summary> /// <param name="encryptor">The encryptor to use.</param> /// <returns>An encrypted private key info containing the original private key info.</returns> public Pkcs8EncryptedPrivateKeyInfo Build( ICipherBuilder encryptor) { try { MemoryStream bOut = new MemoryOutputStream(); ICipher cOut = encryptor.BuildCipher(bOut); byte[] keyData = privateKeyInfo.GetEncoded(); Stream str = cOut.Stream; str.Write(keyData, 0, keyData.Length); BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(str); return(new Pkcs8EncryptedPrivateKeyInfo(new EncryptedPrivateKeyInfo((AlgorithmIdentifier)encryptor.AlgorithmDetails, bOut.ToArray()))); } catch (IOException) { throw new InvalidOperationException("cannot encode privateKeyInfo"); } }
/// <summary> /// Create the encrypted private key info using the passed in encryptor. /// </summary> /// <param name="encryptor">The encryptor to use.</param> /// <returns>An encrypted private key info containing the original private key info.</returns> public Pkcs8EncryptedPrivateKeyInfo Build( ICipherBuilder encryptor) { try { MemoryStream bOut = new MemoryOutputStream(); ICipher cOut = encryptor.BuildCipher(bOut); byte[] keyData = privateKeyInfo.GetEncoded(); using (var str = cOut.Stream) { str.Write(keyData, 0, keyData.Length); } return(new Pkcs8EncryptedPrivateKeyInfo(new EncryptedPrivateKeyInfo((AlgorithmIdentifier)encryptor.AlgorithmDetails, bOut.ToArray()))); } catch (IOException) { throw new InvalidOperationException("cannot encode privateKeyInfo"); } }
public PemObject Generate() { if (algorithm == null) { PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privKey); return(new PemObject("PRIVATE KEY", privateKeyInfo.GetEncoded())); } byte[] array = new byte[20]; if (random == null) { random = new SecureRandom(); } ((Random)random).NextBytes(array); try { EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo(algorithm, password, array, iterationCount, privKey); return(new PemObject("ENCRYPTED PRIVATE KEY", encryptedPrivateKeyInfo.GetEncoded())); } catch (global::System.Exception exception) { throw new PemGenerationException("Couldn't encrypt private key", exception); } }
public static string XmlToPem(string xml) { using (RSA rsa = RSA.Create()) { rsa.FromXmlString(xml); AsymmetricCipherKeyPair keyPair = Org.BouncyCastle.Security.DotNetUtilities.GetRsaKeyPair(rsa); // try get private and public key pair if (keyPair != null) // if XML RSA key contains private key { PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyPair.Private); return(FormatPem(Convert.ToBase64String(privateKeyInfo.GetEncoded()), "PRIVATE KEY")); } RsaKeyParameters publicKey = Org.BouncyCastle.Security.DotNetUtilities.GetRsaPublicKey(rsa); // try get public key if (publicKey != null) // if XML RSA key contains public key { SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey); return(FormatPem(Convert.ToBase64String(publicKeyInfo.GetEncoded()), "PUBLIC KEY")); } } throw new InvalidKeyException("Invalid RSA Xml Key"); }
public static string XmlToPem(string xml) { using (RSA rsa = RSA.Create()) { rsa.FromXmlString(xml); AsymmetricCipherKeyPair keyPair = rsa.GetKeyPair(); // try get private and public key pair if (keyPair != null) // if XML RSA key contains private key { PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyPair.Private); return(FormatPem(privateKeyInfo.GetEncoded().ToBase64(), "RSA PRIVATE KEY")); } RsaKeyParameters publicKey = rsa.GetPublicKey(); // try get public key if (publicKey != null) // if XML RSA key contains public key { SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey); return(FormatPem(publicKeyInfo.GetEncoded().ToBase64(), "PUBLIC KEY")); } } throw new InvalidKeyException("Invalid RSA Xml Key"); }
private PemObject createPemObject(Object o) { String type; byte[] encoding; if (o is PemObject) { return((PemObject)o); } if (o is PemObjectGenerator) { return(((PemObjectGenerator)o).Generate()); } if (o is X509Certificate) { type = "CERTIFICATE"; encoding = ((X509Certificate)o).GetEncoded(); } else if (o is X509Crl) { type = "X509 CRL"; encoding = ((X509Crl)o).GetEncoded(); } else if (o is X509TrustedCertificateBlock) { type = "TRUSTED CERTIFICATE"; encoding = ((X509TrustedCertificateBlock)o).GetEncoded(); } else if (o is PrivateKeyInfo) { PrivateKeyInfo info = (PrivateKeyInfo)o; DerObjectIdentifier algOID = info.PrivateKeyAlgorithm.Algorithm; if (algOID.Equals(PkcsObjectIdentifiers.RsaEncryption)) { type = "RSA PRIVATE KEY"; encoding = info.ParsePrivateKey().ToAsn1Object().GetEncoded(); } else if (algOID.Equals(dsaOids[0]) || algOID.Equals(dsaOids[1])) { type = "DSA PRIVATE KEY"; DsaParameter p = DsaParameter.GetInstance(info.PrivateKeyAlgorithm.Parameters); Asn1EncodableVector v = new Asn1EncodableVector(); v.Add(new DerInteger(0)); v.Add(new DerInteger(p.P)); v.Add(new DerInteger(p.Q)); v.Add(new DerInteger(p.G)); BigInteger x = DerInteger.GetInstance(info.ParsePrivateKey()).Value; BigInteger y = p.G.ModPow(x, p.P); v.Add(new DerInteger(y)); v.Add(new DerInteger(x)); encoding = new DerSequence(v).GetEncoded(); } else if (algOID.Equals(X9ObjectIdentifiers.IdECPublicKey)) { type = "EC PRIVATE KEY"; encoding = info.ParsePrivateKey().ToAsn1Object().GetEncoded(); } else { type = "PRIVATE KEY"; encoding = info.GetEncoded(); } } else if (o is SubjectPublicKeyInfo) { type = "PUBLIC KEY"; encoding = ((SubjectPublicKeyInfo)o).GetEncoded(); } /* * else if (o is X509AttributeCertificateHolder) * { * type = "ATTRIBUTE CERTIFICATE"; * encoding = ((X509AttributeCertificateHolder)o).getEncoded(); * } */ else if (o is Pkcs8EncryptedPrivateKeyInfo) { type = "ENCRYPTED PRIVATE KEY"; encoding = ((Pkcs8EncryptedPrivateKeyInfo)o).GetEncoded(); } else if (o is Pkcs10CertificationRequest) { type = "CERTIFICATE REQUEST"; encoding = ((Pkcs10CertificationRequest)o).GetEncoded(); } else if (o is ContentInfo) { type = "PKCS7"; encoding = ((ContentInfo)o).GetEncoded(); } else { throw new PemGenerationException("unknown object passed - can't encode."); } if (encryptorBuilder != null) { String dekAlgName = Platform.ToUpperInvariant(encryptorBuilder.AlgorithmDetails.Info); // Note: For backward compatibility if (dekAlgName.StartsWith("DESEDE")) { dekAlgName = "DES-EDE3-CBC"; } MemoryOutputStream bOut = new MemoryOutputStream(); ICipher encryptor = encryptorBuilder.BuildCipher(bOut); using (var stream = encryptor.Stream) { stream.Write(encoding, 0, encoding.Length); } byte[] encData = bOut.ToArray(); IList headers = Platform.CreateArrayList(); headers.Add(new PemHeader("Proc-Type", "4,ENCRYPTED")); headers.Add(new PemHeader("DEK-Info", encryptorBuilder.AlgorithmDetails.Info)); return(new PemObject(type, headers, encData)); } return(new PemObject(type, encoding)); }
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); } }
/// <summary> /// Generates a ca certificate /// </summary> /// <param name="privateKey">The CA private key used to sign certificates</param> /// <param name="base64EncodedCer">The cer file used to configure the browser</param> /// <returns></returns> public static void GenerateCACert(out string privateKey, out string base64EncodedCer) { string subjectName = CA_NAME; int keyStrength = 1024; // Generating Random Numbers var randomGenerator = new CryptoApiRandomGenerator(); var random = new SecureRandom(randomGenerator); // The Certificate Generator var certificateGenerator = new X509V3CertificateGenerator(); // Serial Number var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random); certificateGenerator.SetSerialNumber(serialNumber); // Issuer and Subject Name var subjectDN = new X509Name(subjectName); var issuerDN = subjectDN; certificateGenerator.SetIssuerDN(issuerDN); certificateGenerator.SetSubjectDN(subjectDN); // Valid For var notBefore = DateTime.UtcNow.Date; var notAfter = notBefore.AddYears(2); certificateGenerator.SetNotBefore(notBefore); certificateGenerator.SetNotAfter(notAfter); certificateGenerator.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(0)); // Subject Public Key AsymmetricCipherKeyPair subjectKeyPair; var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength); var keyPairGenerator = new RsaKeyPairGenerator(); keyPairGenerator.Init(keyGenerationParameters); subjectKeyPair = keyPairGenerator.GenerateKeyPair(); certificateGenerator.SetPublicKey(subjectKeyPair.Public); // Generating the Certificate var issuerKeyPair = subjectKeyPair; ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA256WithRSA", issuerKeyPair.Private, random); var certificate = certificateGenerator.Generate(signatureFactory); base64EncodedCer = String.Format("-----BEGIN CERTIFICATE-----\r\n{0}\r\n-----END CERTIFICATE-----", Convert.ToBase64String(certificate.GetEncoded())); //var x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded()); //System.Security.Cryptography.X509Certificates.X509Certificate dotNetCert = DotNetUtilities.ToX509Certificate(certificate); //X509Certificate2 dotNetCert2 = new X509Certificate2(dotNetCert); // Add CA certificate to Root store //AddCertToStore(dotNetCert2, StoreName.Root, StoreLocation.LocalMachine); PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(issuerKeyPair.Private); privateKey = Convert.ToBase64String(info.GetEncoded()); }