private X509CertificateCollection GetCertificate() { X509CertificateCollection outCertificate = new X509CertificateCollection(); X509Certificate2 x509 = null; AsymmetricCipherKeyPair privateKey = null; x509 = new X509Certificate2(Encoding.ASCII.GetBytes(MobileStaticVariables.ConectSettings.Certificates[0].Certificate)); var stringReader = new StringReader(MobileStaticVariables.ConectSettings.Certificates[0].PrivateKey); var key = new PemReader(stringReader).ReadObject(); //as AsymmetricCipherKeyPair; if (key != null) { privateKey = (AsymmetricCipherKeyPair)key; } if (privateKey != null) { PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey.Private); var seq = (Asn1Sequence)Asn1Object.FromByteArray(info.ParsePrivateKey().GetDerEncoded()); if (seq.Count != 9) { throw new PemException("malformed sequence in RSA private key"); } var rsa = RsaPrivateKeyStructure.GetInstance(seq); RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters( rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient); x509.PrivateKey = DotNetUtilities.ToRSA(rsaparams); //Logger.WriteLine("Certificates : " + x509.GetCertHashString() + " hash class : " + this.GetHashCode()); outCertificate.Add(x509); } return(outCertificate); }
/** * 获取der编码格式中的纯私钥数据 */ public static byte[] GetPrivateKeyFormDER(byte[] derData) { PrivateKeyInfo pinfo = PrivateKeyInfo.GetInstance(derData); ECPrivateKeyStructure cpk = ECPrivateKeyStructure.GetInstance(pinfo.ParsePrivateKey()); int length = 32; byte[] bytes = cpk.GetKey().ToByteArray(); if (bytes.Length == length) { return(bytes); } int start = bytes[0] == 0 ? 1 : 0; int count = bytes.Length - start; if (count > length) { throw new ArgumentException("privateKey data is error"); } byte[] tmp = new byte[length]; Buffer.BlockCopy(bytes, start, tmp, tmp.Length - count, count); return(tmp); }
ToDotNetCert(CertPrivateKey key, BcCertificate certificate) { // merge into X509Certificate2 // correcponding private key PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(key.KeyPair.Private); var x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2( certificate.GetEncoded()); #pragma warning disable CS0618 // Type or member is obsolete var seq = (Asn1Sequence)Asn1Object.FromByteArray(info.ParsePrivateKey().GetDerEncoded()); #pragma warning restore CS0618 // Type or member is obsolete if (seq.Count != 9) { throw new PemException("malformed sequence in RSA private key"); } #pragma warning disable CS0618 // Type or member is obsolete var rsa = new RsaPrivateKeyStructure(seq); #pragma warning restore CS0618 // Type or member is obsolete RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters( rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient); x509.PrivateKey = DotNetUtilities.ToRSA(rsaparams); return(x509); }
private static byte[] EncodePrivateKey(AsymmetricKeyParameter akp, out string keyType) { PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(akp); AlgorithmIdentifier privateKeyAlgorithm = privateKeyInfo.PrivateKeyAlgorithm; DerObjectIdentifier derObjectIdentifier = privateKeyAlgorithm.Algorithm; if (derObjectIdentifier.Equals(X9ObjectIdentifiers.IdDsa)) { keyType = "DSA"; DsaParameter instance = DsaParameter.GetInstance(privateKeyAlgorithm.Parameters); BigInteger x = ((DsaPrivateKeyParameters)akp).X; BigInteger value = instance.G.ModPow(x, instance.P); return(new DerSequence(new DerInteger(0), new DerInteger(instance.P), new DerInteger(instance.Q), new DerInteger(instance.G), new DerInteger(value), new DerInteger(x)).GetEncoded()); } if (derObjectIdentifier.Equals(PkcsObjectIdentifiers.RsaEncryption)) { keyType = "RSA"; } else { if (!derObjectIdentifier.Equals(CryptoProObjectIdentifiers.GostR3410x2001) && !derObjectIdentifier.Equals(X9ObjectIdentifiers.IdECPublicKey)) { throw new ArgumentException("Cannot handle private key of type: " + Platform.GetTypeName(akp), "akp"); } keyType = "EC"; } return(privateKeyInfo.ParsePrivateKey().GetEncoded()); }
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 static byte[] GetRawKey(PrivateKeyInfo keyInfo, int expectedSize) { byte[] result = Asn1OctetString.GetInstance(keyInfo.ParsePrivateKey()).GetOctets(); if (expectedSize != result.Length) throw new SecurityUtilityException("private key encoding has incorrect length"); return result; }
private static RsaPrivateKeyStructure ParsePrivateKey(PrivateKeyInfo privateKeyInfo) { try { return(RsaPrivateKeyStructure.GetInstance(privateKeyInfo.ParsePrivateKey())); } catch (Exception e) { throw new ArgumentException("Unable to parse private key: " + e.Message, e); } }
/// <summary> /// Converts the 32 byte private key to a 25 word mnemonic, including a checksum. /// Refer to the mnemonic package for additional documentation. /// </summary> /// <returns>return string a 25 word mnemonic</returns> public string ToMnemonic() { PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(this.privateKeyPair.Private); byte[] X509enc = privateKeyInfo.ToAsn1Object().GetEncoded(); PrivateKeyInfo pkinfo = PrivateKeyInfo.GetInstance(X509enc); var keyOcts = pkinfo.ParsePrivateKey(); byte[] res = Asn1OctetString.GetInstance(keyOcts).GetOctets(); return(Mnemonic.FromKey(res)); }
private static BigInteger ParsePrivateKey(PrivateKeyInfo info) { try { return(DerInteger.GetInstance(info.ParsePrivateKey()).Value); } catch (Exception e) { throw new ArgumentException("Unable to parse DSA private key: " + e.Message, e); } }
public static void ExportPrivateKey(AsymmetricKeyParameter privKey, TextWriter outputStream) { PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privKey); var seq = (Asn1Sequence)Asn1Object.FromByteArray(info.ParsePrivateKey().GetDerEncoded()); if (seq.Count != 9) { throw new PemException("Malformed sequence in RSA private key"); } var rsa = RsaPrivateKeyStructure.GetInstance(seq); var parameters = new RsaPrivateCrtKeyParameters(rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient); using (var stream = new MemoryStream()) { var writer = new BinaryWriter(stream); writer.Write((byte)0x30); // SEQUENCE using (var innerStream = new MemoryStream()) { var innerWriter = new BinaryWriter(innerStream); EncodeIntegerBigEndian(innerWriter, new byte[] { 0x00 }); // Version EncodeIntegerBigEndian(innerWriter, parameters.Modulus.ToByteArray()); EncodeIntegerBigEndian(innerWriter, parameters.PublicExponent.ToByteArray()); EncodeIntegerBigEndian(innerWriter, parameters.Exponent.ToByteArray()); EncodeIntegerBigEndian(innerWriter, parameters.P.ToByteArray()); EncodeIntegerBigEndian(innerWriter, parameters.Q.ToByteArray()); EncodeIntegerBigEndian(innerWriter, parameters.DP.ToByteArray()); EncodeIntegerBigEndian(innerWriter, parameters.DQ.ToByteArray()); EncodeIntegerBigEndian(innerWriter, parameters.QInv.ToByteArray()); var length = (int)innerStream.Length; EncodeLength(writer, length); writer.Write(innerStream.GetBuffer(), 0, length); } var base64 = Convert.ToBase64String(stream.GetBuffer(), 0, (int)stream.Length).ToCharArray(); outputStream.WriteLine("-----BEGIN RSA PRIVATE KEY-----"); // Output as Base64 with lines chopped at 64 characters for (var i = 0; i < base64.Length; i += 64) { outputStream.WriteLine(base64, i, Math.Min(64, base64.Length - i)); } outputStream.WriteLine("-----END RSA PRIVATE KEY-----"); } }
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())); }
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"; 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"; } else if (oid.Equals(CryptoProObjectIdentifiers.GostR3410x2001) || oid.Equals(X9ObjectIdentifiers.IdECPublicKey)) { keyType = "EC"; } else { throw new ArgumentException("Cannot handle private key of type: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(akp), "akp"); } return(info.ParsePrivateKey().GetEncoded()); }
protected static X509Certificate2 GenerateCertificate( string subjectName = "CN=localhost", string issuerName = "CN=Local AjaxLife CA", int strength = 2048, string hashAlgo = "SHA256WithRSA", double age = 86400 ) { AsymmetricKeyParameter issuerPrivateKey = GenerateCA(issuerName, strength, hashAlgo, age); CryptoApiRandomGenerator genRandom = new CryptoApiRandomGenerator(); SecureRandom random = new SecureRandom(genRandom); X509V3CertificateGenerator genCert = new X509V3CertificateGenerator(); genCert.SetSerialNumber( BigIntegers.CreateRandomInRange( BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random ) ); genCert.SetSignatureAlgorithm(hashAlgo); genCert.SetIssuerDN(new X509Name(issuerName)); genCert.SetSubjectDN(new X509Name(subjectName)); genCert.SetNotBefore(DateTime.Now.AddSeconds(-86400)); genCert.SetNotAfter(DateTime.Now.AddSeconds(age)); RsaKeyPairGenerator genKeypair = new RsaKeyPairGenerator(); genKeypair.Init( new KeyGenerationParameters(random, strength) ); AsymmetricCipherKeyPair keypair = genKeypair.GenerateKeyPair(); genCert.SetPublicKey(keypair.Public); PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keypair.Private); X509Certificate2 x509 = new X509Certificate2(genCert.Generate(issuerPrivateKey, random).GetEncoded()); Asn1Sequence seq = (Asn1Sequence)Asn1Object.FromByteArray(info.ParsePrivateKey().GetDerEncoded()); if (seq.Count != 9) { throw new PemException("Malformed sequence in RSA private key"); } RsaPrivateKeyStructure rsa = new RsaPrivateKeyStructure(seq); RsaPrivateCrtKeyParameters rsaParams = new RsaPrivateCrtKeyParameters( rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient ); x509.PrivateKey = DotNetUtilities.ToRSA(rsaParams); AddCertToStore(x509, StoreName.My, StoreLocation.CurrentUser); return(x509); }
public static string PrintPrivateKey(AsymmetricCipherKeyPair keys) { StringBuilder sb = new StringBuilder(); PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keys.Private); RsaPrivateKeyStructure rsa = RsaPrivateKeyStructure.GetInstance(privateKeyInfo.ParsePrivateKey()); byte[] serializedBytes = privateKeyInfo.ToAsn1Object().GetDerEncoded(); string serialized = Convert.ToBase64String(serializedBytes); sb.AppendLine("Key==>" + serialized); sb.AppendLine("Prime 1 ==>" + rsa.Prime1.ToString()); sb.AppendLine("Prime 2 ==>" + rsa.Prime2.ToString()); sb.AppendLine("Modulus ==>" + rsa.Modulus.ToString()); sb.AppendLine("Coefficient ==>" + rsa.Coefficient.ToString()); sb.AppendLine("Exponent1 ==>" + rsa.Exponent1.ToString()); sb.AppendLine("Exponent2 ==>" + rsa.Exponent2.ToString()); sb.AppendLine("PrivateExponent ==>" + rsa.PrivateExponent.ToString()); sb.AppendLine("PublicExponent ==>" + rsa.PublicExponent.ToString()); return(sb.ToString()); }
/// <summary> /// Generate, install and export to file system new certificate /// </summary> /// <param name="subjectName">Subject name for new certificate</param> /// <param name="issuerName">CA(Certificate authority) name</param> /// <param name="issuerPrivKey">Issuer private key</param> /// <returns></returns> public static X509Certificate2 GenerateAuthorizeSignedCertificate(string subjectName, string issuerName, AsymmetricKeyParameter issuerPrivKey) { const int keyStrength = 2048; // Generating random numbers CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator(); SecureRandom random = new SecureRandom(randomGenerator); // The Certificate Generator X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator(); // Serial Number BigInteger serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random); certificateGenerator.SetSerialNumber(serialNumber); // Signature Algorithm const string signatureAlgorithm = "SHA256WithRSA"; certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm); // Issuer and Subject Name X509Name subjectDN = new X509Name("CN=" + subjectName); X509Name issuerDN = new X509Name(issuerName); certificateGenerator.SetIssuerDN(issuerDN); certificateGenerator.SetSubjectDN(subjectDN); // Valid For DateTime notBefore = DateTime.UtcNow.Date; DateTime notAfter = notBefore.AddYears(2); certificateGenerator.SetNotBefore(notBefore); certificateGenerator.SetNotAfter(notAfter); // 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); // selfsign certificate Org.BouncyCastle.X509.X509Certificate certificate = certificateGenerator.Generate(issuerPrivKey, random); // correcponding private key PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private); // merge into X509Certificate2 X509Certificate2 x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded()); Asn1Sequence seq = (Asn1Sequence)Asn1Object.FromByteArray(info.ParsePrivateKey().GetDerEncoded()); RsaPrivateKeyStructure rsa = RsaPrivateKeyStructure.GetInstance(seq); RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters( rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient); // Set Private Key x509.PrivateKey = DotNetUtilities.ToRSA(rsaparams); // Install certificate AddCertificateToStore(x509, StoreName.TrustedPeople, StoreLocation.LocalMachine); //Export ExportToFileSystem(X509ContentType.Pfx, x509, subjectName); return(x509); }
public static AsymmetricKeyParameter CreateKey( PrivateKeyInfo keyInfo) { AlgorithmIdentifier algID = keyInfo.PrivateKeyAlgorithm; DerObjectIdentifier algOid = algID.Algorithm; // TODO See RSAUtil.isRsaOid in Java build if (algOid.Equals(PkcsObjectIdentifiers.RsaEncryption) || algOid.Equals(X509ObjectIdentifiers.IdEARsa) || algOid.Equals(PkcsObjectIdentifiers.IdRsassaPss) || algOid.Equals(PkcsObjectIdentifiers.IdRsaesOaep)) { RsaPrivateKeyStructure keyStructure = RsaPrivateKeyStructure.GetInstance(keyInfo.ParsePrivateKey()); return(new RsaPrivateCrtKeyParameters( keyStructure.Modulus, keyStructure.PublicExponent, keyStructure.PrivateExponent, keyStructure.Prime1, keyStructure.Prime2, keyStructure.Exponent1, keyStructure.Exponent2, keyStructure.Coefficient)); } // TODO? // else if (algOid.Equals(X9ObjectIdentifiers.DHPublicNumber)) else if (algOid.Equals(PkcsObjectIdentifiers.DhKeyAgreement)) { DHParameter para = new DHParameter( Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object())); DerInteger derX = (DerInteger)keyInfo.ParsePrivateKey(); BigInteger lVal = para.L; int l = lVal == null ? 0 : lVal.IntValue; DHParameters dhParams = new DHParameters(para.P, para.G, null, l); return(new DHPrivateKeyParameters(derX.Value, dhParams, algOid)); } else if (algOid.Equals(OiwObjectIdentifiers.ElGamalAlgorithm)) { ElGamalParameter para = new ElGamalParameter( Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object())); DerInteger derX = (DerInteger)keyInfo.ParsePrivateKey(); return(new ElGamalPrivateKeyParameters( derX.Value, new ElGamalParameters(para.P, para.G))); } else if (algOid.Equals(X9ObjectIdentifiers.IdDsa)) { DerInteger derX = (DerInteger)keyInfo.ParsePrivateKey(); Asn1Encodable ae = algID.Parameters; DsaParameters parameters = null; if (ae != null) { DsaParameter para = DsaParameter.GetInstance(ae.ToAsn1Object()); parameters = new DsaParameters(para.P, para.Q, para.G); } return(new DsaPrivateKeyParameters(derX.Value, parameters)); } else if (algOid.Equals(X9ObjectIdentifiers.IdECPublicKey)) { X962Parameters para = X962Parameters.GetInstance(algID.Parameters.ToAsn1Object()); X9ECParameters x9; if (para.IsNamedCurve) { x9 = ECKeyPairGenerator.FindECCurveByOid((DerObjectIdentifier)para.Parameters); } else { x9 = new X9ECParameters((Asn1Sequence)para.Parameters); } ECPrivateKeyStructure ec = ECPrivateKeyStructure.GetInstance(keyInfo.ParsePrivateKey()); BigInteger d = ec.GetKey(); if (para.IsNamedCurve) { return(new ECPrivateKeyParameters("EC", d, (DerObjectIdentifier)para.Parameters)); } ECDomainParameters dParams = new ECDomainParameters(x9.Curve, x9.G, x9.N, x9.H, x9.GetSeed()); return(new ECPrivateKeyParameters(d, dParams)); } else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x2001)) { Gost3410PublicKeyAlgParameters gostParams = Gost3410PublicKeyAlgParameters.GetInstance( algID.Parameters.ToAsn1Object()); ECDomainParameters ecP = ECGost3410NamedCurves.GetByOid(gostParams.PublicKeyParamSet); if (ecP == null) { throw new ArgumentException("Unrecognized curve OID for GostR3410x2001 private key"); } Asn1Object privKey = keyInfo.ParsePrivateKey(); ECPrivateKeyStructure ec; if (privKey is DerInteger) { ec = new ECPrivateKeyStructure(ecP.N.BitLength, ((DerInteger)privKey).PositiveValue); } else { ec = ECPrivateKeyStructure.GetInstance(privKey); } return(new ECPrivateKeyParameters("ECGOST3410", ec.GetKey(), gostParams.PublicKeyParamSet)); } else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x94)) { Gost3410PublicKeyAlgParameters gostParams = Gost3410PublicKeyAlgParameters.GetInstance(algID.Parameters); Asn1Object privKey = keyInfo.ParsePrivateKey(); BigInteger x; if (privKey is DerInteger) { x = DerInteger.GetInstance(privKey).PositiveValue; } else { x = new BigInteger(1, Arrays.Reverse(Asn1OctetString.GetInstance(privKey).GetOctets())); } return(new Gost3410PrivateKeyParameters(x, gostParams.PublicKeyParamSet)); } else if (algOid.Equals(EdECObjectIdentifiers.id_X25519)) { return(new X25519PrivateKeyParameters(GetRawKey(keyInfo, X25519PrivateKeyParameters.KeySize), 0)); } else if (algOid.Equals(EdECObjectIdentifiers.id_X448)) { return(new X448PrivateKeyParameters(GetRawKey(keyInfo, X448PrivateKeyParameters.KeySize), 0)); } else if (algOid.Equals(EdECObjectIdentifiers.id_Ed25519)) { return(new Ed25519PrivateKeyParameters(GetRawKey(keyInfo, Ed25519PrivateKeyParameters.KeySize), 0)); } else if (algOid.Equals(EdECObjectIdentifiers.id_Ed448)) { return(new Ed448PrivateKeyParameters(GetRawKey(keyInfo, Ed448PrivateKeyParameters.KeySize), 0)); } else if (algOid.Equals(RosstandartObjectIdentifiers.id_tc26_gost_3410_12_512) || algOid.Equals(RosstandartObjectIdentifiers.id_tc26_gost_3410_12_256)) { Gost3410PublicKeyAlgParameters gostParams = Gost3410PublicKeyAlgParameters.GetInstance(keyInfo.PrivateKeyAlgorithm.Parameters); ECGost3410Parameters ecSpec = null; BigInteger d = null; Asn1Object p = keyInfo.PrivateKeyAlgorithm.Parameters.ToAsn1Object(); if (p is Asn1Sequence && (Asn1Sequence.GetInstance(p).Count == 2 || Asn1Sequence.GetInstance(p).Count == 3)) { ECDomainParameters ecP = ECGost3410NamedCurves.GetByOid(gostParams.PublicKeyParamSet); ecSpec = new ECGost3410Parameters( new ECNamedDomainParameters( gostParams.PublicKeyParamSet, ecP), gostParams.PublicKeyParamSet, gostParams.DigestParamSet, gostParams.EncryptionParamSet); Asn1OctetString privEnc = keyInfo.PrivateKeyData; if (privEnc.GetOctets().Length == 32 || privEnc.GetOctets().Length == 64) { byte[] dVal = Arrays.Reverse(privEnc.GetOctets()); d = new BigInteger(1, dVal); } else { Asn1Encodable privKey = keyInfo.ParsePrivateKey(); if (privKey is DerInteger) { d = DerInteger.GetInstance(privKey).PositiveValue; } else { byte[] dVal = Arrays.Reverse(Asn1OctetString.GetInstance(privKey).GetOctets()); d = new BigInteger(1, dVal); } } } else { X962Parameters parameters = X962Parameters.GetInstance(keyInfo.PrivateKeyAlgorithm.Parameters); if (parameters.IsNamedCurve) { DerObjectIdentifier oid = DerObjectIdentifier.GetInstance(parameters.Parameters); X9ECParameters ecP = ECNamedCurveTable.GetByOid(oid); if (ecP == null) { ECDomainParameters gParam = ECGost3410NamedCurves.GetByOid(oid); ecSpec = new ECGost3410Parameters(new ECNamedDomainParameters( oid, gParam.Curve, gParam.G, gParam.N, gParam.H, gParam.GetSeed()), gostParams.PublicKeyParamSet, gostParams.DigestParamSet, gostParams.EncryptionParamSet); } else { ecSpec = new ECGost3410Parameters(new ECNamedDomainParameters( oid, ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed()), gostParams.PublicKeyParamSet, gostParams.DigestParamSet, gostParams.EncryptionParamSet); } } else if (parameters.IsImplicitlyCA) { ecSpec = null; } else { X9ECParameters ecP = X9ECParameters.GetInstance(parameters.Parameters); ecSpec = new ECGost3410Parameters(new ECNamedDomainParameters( algOid, ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed()), gostParams.PublicKeyParamSet, gostParams.DigestParamSet, gostParams.EncryptionParamSet); } Asn1Encodable privKey = keyInfo.ParsePrivateKey(); if (privKey is DerInteger) { DerInteger derD = DerInteger.GetInstance(privKey); d = derD.Value; } else { ECPrivateKeyStructure ec = ECPrivateKeyStructure.GetInstance(privKey); d = ec.GetKey(); } } return(new ECPrivateKeyParameters( d, new ECGost3410Parameters( ecSpec, gostParams.PublicKeyParamSet, gostParams.DigestParamSet, gostParams.EncryptionParamSet))); } else { throw new SecurityUtilityException("algorithm identifier in private key not recognised"); } }
/// <summary> /// gen cert /// </summary> /// <param name="subjectName"></param> /// <param name="issuerName"></param> /// <param name="issuerPrivKey"></param> /// <param name="keyStrength"></param> /// <returns>.net framewory style cert</returns> /// <remarks> /// Many thanks to this stackoverflow post: /// https://stackoverflow.com/a/22237794 /// </remarks> private X509Certificate2 GenerateSelfSignedCertificate(string subjectName, string issuerName, AsymmetricKeyParameter issuerPrivKey, int keyStrength, TimeSpan lifespan) { // Generating Random Numbers var random = new SecureRandom(); // The Certificate Generator var certificateGenerator = new X509V3CertificateGenerator(); // Serial Number certificateGenerator.SetSerialNumber(GenerateSerial()); // Issuer and Subject Name var subjectDN = new X509Name(subjectName); var issuerDN = new X509Name(issuerName); certificateGenerator.SetIssuerDN(issuerDN); certificateGenerator.SetSubjectDN(subjectDN); //set validity AssignLife(certificateGenerator, lifespan); // 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; // selfsign certificate var signatureFactory = new Asn1SignatureFactory(CertificateAuthority.SignatureAlg, issuerPrivKey, random); var certificate = certificateGenerator.Generate(signatureFactory); // correcponding private key PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private); // merge into X509Certificate2 var x509 = new X509Certificate2(certificate.GetEncoded()); var seq = (Asn1Sequence)Asn1Object.FromByteArray(info.ParsePrivateKey().GetDerEncoded()); if (seq.Count != 9) { throw new InvalidOperationException("malformed sequence in RSA private key"); } //var rsa = new RsaPrivateKeyStructure(seq); var rsa = RsaPrivateKeyStructure.GetInstance(seq); var rsaparams = new RsaPrivateCrtKeyParameters( rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient); x509.PrivateKey = DotNetUtilities.ToRSA(rsaparams); return(x509); }
/// <summary> /// Constructor from an algorithm and a PrivateKeyInfo object containing a SPHINCS private key. /// </summary> /// <param name="algorithm">Algorithm marker to associate with the key.</param> /// <param name="privateKeyInfo">A PrivateKeyInfo object.</param> public AsymmetricSphincsPrivateKey(Algorithm algorithm, PrivateKeyInfo privateKeyInfo) : base(algorithm, privateKeyInfo.PrivateKeyAlgorithm) { this.keyData = Arrays.Clone(Asn1OctetString.GetInstance(privateKeyInfo.ParsePrivateKey()).GetOctets()); }
X509Certificate2 GenerateSelfSignedCertificate(string subjectName, string issuerName, AsymmetricKeyParameter issuerPrivKey, int keyStrength = 2048) { // 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); // Signature Algorithm const string signatureAlgorithm = "SHA256WithRSA"; // Issuer and Subject Name var subjectDN = new X509Name(subjectName); var issuerDN = new X509Name(issuerName); certificateGenerator.SetIssuerDN(issuerDN); certificateGenerator.SetSubjectDN(subjectDN); // Valid For var notBefore = DateTime.UtcNow.Date; var notAfter = notBefore.AddYears(2); certificateGenerator.SetNotBefore(notBefore); certificateGenerator.SetNotAfter(notAfter); // 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; // create key factory ISignatureFactory signatureFactory = new Asn1SignatureFactory(signatureAlgorithm, issuerPrivKey, random); // selfsign certificate var certificate = certificateGenerator.Generate(signatureFactory); // correcponding private key PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private); // merge into X509Certificate2 var x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded()); var seq = (Asn1Sequence)Asn1Object.FromByteArray(info.ParsePrivateKey().GetDerEncoded()); if (seq.Count != 9) { throw new PemException("malformed sequence in RSA private key"); } var rsa = RsaPrivateKeyStructure.GetInstance(seq); RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters( rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient); x509.PrivateKey = DotNetUtilities.ToRSA(rsaparams); return(x509); }
/// <summary> /// Generates the certificate. /// </summary> /// <param name="subjectName">Name of the subject.</param> /// <param name="issuerName">Name of the issuer.</param> /// <param name="validFrom">The valid from.</param> /// <param name="validTo">The valid to.</param> /// <param name="keyStrength">The key strength.</param> /// <param name="signatureAlgorithm">The signature algorithm.</param> /// <param name="issuerPrivateKey">The issuer private key.</param> /// <param name="hostName">The host name</param> /// <returns>X509Certificate2 instance.</returns> /// <exception cref="PemException">Malformed sequence in RSA private key</exception> private static X509Certificate2 generateCertificate(string hostName, string subjectName, string issuerName, System.DateTime validFrom, System.DateTime validTo, int keyStrength = 2048, string signatureAlgorithm = "SHA256WithRSA", AsymmetricKeyParameter issuerPrivateKey = null) { // Generating Random Numbers CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator(); SecureRandom secureRandom = new SecureRandom(randomGenerator); // The Certificate Generator X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator(); // Serial Number BigInteger serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(long.MaxValue), secureRandom); certificateGenerator.SetSerialNumber(serialNumber); // Issuer and Subject Name X509Name subjectDn = new X509Name(subjectName); X509Name issuerDn = new X509Name(issuerName); certificateGenerator.SetIssuerDN(issuerDn); certificateGenerator.SetSubjectDN(subjectDn); certificateGenerator.SetNotBefore(validFrom); certificateGenerator.SetNotAfter(validTo); if (hostName != null) { // add subject alternative names Asn1Encodable[] subjectAlternativeNames = new Asn1Encodable[] { new GeneralName(GeneralName.DnsName, hostName) }; DerSequence subjectAlternativeNamesExtension = new DerSequence(subjectAlternativeNames); certificateGenerator.AddExtension(X509Extensions.SubjectAlternativeName.Id, false, subjectAlternativeNamesExtension); } // Subject Public Key KeyGenerationParameters keyGenerationParameters = new KeyGenerationParameters(secureRandom, keyStrength); RsaKeyPairGenerator keyPairGenerator = new RsaKeyPairGenerator(); keyPairGenerator.Init(keyGenerationParameters); AsymmetricCipherKeyPair subjectKeyPair = keyPairGenerator.GenerateKeyPair(); certificateGenerator.SetPublicKey(subjectKeyPair.Public); // Set certificate intended purposes to only Server Authentication certificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage.Id, false, new ExtendedKeyUsage(KeyPurposeID.IdKPServerAuth)); if (issuerPrivateKey == null) { certificateGenerator.AddExtension(X509Extensions.BasicConstraints.Id, true, new BasicConstraints(true)); } Asn1SignatureFactory signatureFactory = new Asn1SignatureFactory(signatureAlgorithm, issuerPrivateKey ?? subjectKeyPair.Private, secureRandom); // Self-sign the certificate X509Certificate certificate = certificateGenerator.Generate(signatureFactory); // Corresponding private key PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private); Asn1Sequence seq = (Asn1Sequence)Asn1Object.FromByteArray(privateKeyInfo.ParsePrivateKey().GetDerEncoded()); if (seq.Count != 9) { throw new PemException("Malformed sequence in RSA private key"); } RsaPrivateKeyStructure rsa = RsaPrivateKeyStructure.GetInstance(seq); RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters(rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient); #if NET45 // Set private key onto certificate instance X509Certificate2 x509Certificate = new X509Certificate2(certificate.GetEncoded()); x509Certificate.PrivateKey = DotNetUtilities.ToRSA(rsaparams); #else X509Certificate2 x509Certificate = withPrivateKey(certificate, rsaparams); if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { x509Certificate.FriendlyName = subjectName; } #endif doNotSetFriendlyName = false; if (!doNotSetFriendlyName) { try { x509Certificate.FriendlyName = ProxyConstants.CNRemoverRegex.Replace(subjectName, string.Empty); } catch (System.PlatformNotSupportedException) { doNotSetFriendlyName = true; } } return(x509Certificate); }
public static AsymmetricKeyParameter CreateKey(PrivateKeyInfo keyInfo) { //IL_02a2: Unknown result type (might be due to invalid IL or missing references) AlgorithmIdentifier privateKeyAlgorithm = keyInfo.PrivateKeyAlgorithm; DerObjectIdentifier algorithm = privateKeyAlgorithm.Algorithm; if (algorithm.Equals(PkcsObjectIdentifiers.RsaEncryption) || algorithm.Equals(X509ObjectIdentifiers.IdEARsa) || algorithm.Equals(PkcsObjectIdentifiers.IdRsassaPss) || algorithm.Equals(PkcsObjectIdentifiers.IdRsaesOaep)) { RsaPrivateKeyStructure instance = RsaPrivateKeyStructure.GetInstance(keyInfo.ParsePrivateKey()); return(new RsaPrivateCrtKeyParameters(instance.Modulus, instance.PublicExponent, instance.PrivateExponent, instance.Prime1, instance.Prime2, instance.Exponent1, instance.Exponent2, instance.Coefficient)); } if (algorithm.Equals(PkcsObjectIdentifiers.DhKeyAgreement)) { DHParameter dHParameter = new DHParameter(Asn1Sequence.GetInstance(privateKeyAlgorithm.Parameters.ToAsn1Object())); DerInteger derInteger = (DerInteger)keyInfo.ParsePrivateKey(); int l = dHParameter.L?.IntValue ?? 0; DHParameters parameters = new DHParameters(dHParameter.P, dHParameter.G, null, l); return(new DHPrivateKeyParameters(derInteger.Value, parameters, algorithm)); } if (algorithm.Equals(OiwObjectIdentifiers.ElGamalAlgorithm)) { ElGamalParameter elGamalParameter = new ElGamalParameter(Asn1Sequence.GetInstance(privateKeyAlgorithm.Parameters.ToAsn1Object())); DerInteger derInteger2 = (DerInteger)keyInfo.ParsePrivateKey(); return(new ElGamalPrivateKeyParameters(derInteger2.Value, new ElGamalParameters(elGamalParameter.P, elGamalParameter.G))); } if (algorithm.Equals(X9ObjectIdentifiers.IdDsa)) { DerInteger derInteger3 = (DerInteger)keyInfo.ParsePrivateKey(); Asn1Encodable parameters2 = privateKeyAlgorithm.Parameters; DsaParameters parameters3 = null; if (parameters2 != null) { DsaParameter instance2 = DsaParameter.GetInstance(parameters2.ToAsn1Object()); parameters3 = new DsaParameters(instance2.P, instance2.Q, instance2.G); } return(new DsaPrivateKeyParameters(derInteger3.Value, parameters3)); } if (algorithm.Equals(X9ObjectIdentifiers.IdECPublicKey)) { X962Parameters x962Parameters = new X962Parameters(privateKeyAlgorithm.Parameters.ToAsn1Object()); X9ECParameters x9ECParameters = ((!x962Parameters.IsNamedCurve) ? new X9ECParameters((Asn1Sequence)x962Parameters.Parameters) : ECKeyPairGenerator.FindECCurveByOid((DerObjectIdentifier)x962Parameters.Parameters)); ECPrivateKeyStructure instance3 = ECPrivateKeyStructure.GetInstance(keyInfo.ParsePrivateKey()); BigInteger key = instance3.GetKey(); if (x962Parameters.IsNamedCurve) { return(new ECPrivateKeyParameters("EC", key, (DerObjectIdentifier)x962Parameters.Parameters)); } ECDomainParameters parameters4 = new ECDomainParameters(x9ECParameters.Curve, x9ECParameters.G, x9ECParameters.N, x9ECParameters.H, x9ECParameters.GetSeed()); return(new ECPrivateKeyParameters(key, parameters4)); } if (algorithm.Equals(CryptoProObjectIdentifiers.GostR3410x2001)) { Gost3410PublicKeyAlgParameters gost3410PublicKeyAlgParameters = new Gost3410PublicKeyAlgParameters(Asn1Sequence.GetInstance(privateKeyAlgorithm.Parameters.ToAsn1Object())); ECDomainParameters byOid = ECGost3410NamedCurves.GetByOid(gost3410PublicKeyAlgParameters.PublicKeyParamSet); if (byOid == null) { throw new ArgumentException("Unrecognized curve OID for GostR3410x2001 private key"); } Asn1Object asn1Object = keyInfo.ParsePrivateKey(); ECPrivateKeyStructure eCPrivateKeyStructure = ((!(asn1Object is DerInteger)) ? ECPrivateKeyStructure.GetInstance(asn1Object) : new ECPrivateKeyStructure(byOid.N.BitLength, ((DerInteger)asn1Object).Value)); return(new ECPrivateKeyParameters("ECGOST3410", eCPrivateKeyStructure.GetKey(), gost3410PublicKeyAlgParameters.PublicKeyParamSet)); } if (algorithm.Equals(CryptoProObjectIdentifiers.GostR3410x94)) { Gost3410PublicKeyAlgParameters gost3410PublicKeyAlgParameters2 = new Gost3410PublicKeyAlgParameters(Asn1Sequence.GetInstance(privateKeyAlgorithm.Parameters.ToAsn1Object())); DerOctetString derOctetString = (DerOctetString)keyInfo.ParsePrivateKey(); BigInteger x = new BigInteger(1, Arrays.Reverse(derOctetString.GetOctets())); return(new Gost3410PrivateKeyParameters(x, gost3410PublicKeyAlgParameters2.PublicKeyParamSet)); } throw new SecurityUtilityException("algorithm identifier in key not recognised"); }
public static X509Certificate2 GenerateSelfSignedCertificate(string subjectName, string issuerName, AsymmetricKeyParameter issuerPrivKey) { const int keyStrength = 2048; // Generating Random Numbers CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator(); SecureRandom random = new SecureRandom(randomGenerator); ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA512WITHRSA", issuerPrivKey, random); // The Certificate Generator X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator(); certificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage.Id, true, new ExtendedKeyUsage(KeyPurposeID.IdKPServerAuth)); // Serial Number BigInteger serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random); certificateGenerator.SetSerialNumber(serialNumber); // Signature Algorithm //const string signatureAlgorithm = "SHA512WITHRSA"; //certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm); // Issuer and Subject Name X509Name subjectDN = new X509Name(subjectName); X509Name issuerDN = new X509Name(issuerName); certificateGenerator.SetIssuerDN(issuerDN); certificateGenerator.SetSubjectDN(subjectDN); // Valid For DateTime notBefore = DateTime.UtcNow.Date; DateTime notAfter = notBefore.AddYears(2); certificateGenerator.SetNotBefore(notBefore); certificateGenerator.SetNotAfter(notAfter); // 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 AsymmetricCipherKeyPair issuerKeyPair = subjectKeyPair; // selfsign certificate var certificate = certificateGenerator.Generate(signatureFactory); // correcponding private key PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private); // merge into X509Certificate2 X509Certificate2 x509 = new X509Certificate2(certificate.GetEncoded()); Asn1Sequence seq = (Asn1Sequence)Asn1Object.FromByteArray(info.ParsePrivateKey().GetDerEncoded()); if (seq.Count != 9) { //throw new PemException("malformed sequence in RSA private key"); } RsaPrivateKeyStructure rsa = RsaPrivateKeyStructure.GetInstance(seq); //new RsaPrivateKeyStructure(seq); RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters( rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient); return(x509.CopyWithPrivateKey(DotNetUtilities.ToRSA(rsaparams))); }
public System.Security.Cryptography.X509Certificates.X509Certificate2 GenerateSelfSignedCertificate(string certificateName, List <string> subjectAlternateNames, string certificateFileName, string privateKeyFilePassword, string issuerName, AsymmetricKeyParameter issuerPrivKey, int keyStrength) { string subjectName = string.Format("CN={0}", certificateName); // Generating Random Numbers var randomGenerator = new CryptoApiRandomGenerator(); var random = new SecureRandom(randomGenerator); // The Certificate Generator X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator(); // Serial Number var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(long.MaxValue), random); certificateGenerator.SetSerialNumber(serialNumber); // Issuer and Subject Name var subjectDN = new X509Name(subjectName); // original code var issuerDN = issuerName; var issuerDN = new X509Name(issuerName); certificateGenerator.SetIssuerDN(issuerDN); certificateGenerator.SetSubjectDN(subjectDN); // Valid For var notBefore = DateTime.UtcNow.Date; var notAfter = notBefore.AddYears(2); certificateGenerator.SetNotBefore(notBefore); certificateGenerator.SetNotAfter(notAfter); KeyUsage keyUsage = new KeyUsage(KeyUsage.DigitalSignature | KeyUsage.KeyEncipherment); certificateGenerator.AddExtension(X509Extensions.KeyUsage, true, keyUsage); // Add the “Extended Key Usage” attribute, specifying “server authentication”. var usages = new[] { KeyPurposeID.IdKPServerAuth }; certificateGenerator.AddExtension( X509Extensions.ExtendedKeyUsage.Id, false, new ExtendedKeyUsage(usages)); /* DNS Name=*.fullyqualified.domainname.com */ if (subjectAlternateNames.Count <= 1) { /* the <=1 is for the simple reason of showing an alternate syntax .. */ foreach (string subjectAlternateName in subjectAlternateNames) { GeneralName altName = new GeneralName(GeneralName.DnsName, subjectAlternateName); GeneralNames subjectAltName = new GeneralNames(altName); certificateGenerator.AddExtension(X509Extensions.SubjectAlternativeName, false, subjectAltName); } } else { //Asn1Encodable[] ansiEncodeSubjectAlternativeNames = new Asn1Encodable[] // { // //new GeneralName(GeneralName.DnsName, “*.fullyqualified.domainname.com”), // new GeneralName(GeneralName.DnsName, “*.fullyqualified.domainname.com”) // }; List <Asn1Encodable> asn1EncodableList = new List <Asn1Encodable>(); foreach (string subjectAlternateName in subjectAlternateNames) { asn1EncodableList.Add(new GeneralName(GeneralName.DnsName, subjectAlternateName)); } DerSequence subjectAlternativeNamesExtension = new DerSequence(asn1EncodableList.ToArray()); certificateGenerator.AddExtension(X509Extensions.SubjectAlternativeName.Id, false, subjectAlternativeNamesExtension); } // 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; // selfsign certificate ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA512WITHRSA", issuerKeyPair.Private, random); Org.BouncyCastle.X509.X509Certificate certificate = certificateGenerator.Generate(signatureFactory); // correcponding private key PrivateKeyInfo pinfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private); // merge into X509Certificate2 var x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded()); var seq = (Asn1Sequence)Asn1Object.FromByteArray(pinfo.ParsePrivateKey().GetDerEncoded()); if (seq.Count != 9) { throw new PemException("malformed sequence in RSA private key"); } RsaPrivateKeyStructure rsa = RsaPrivateKeyStructure.GetInstance(seq); RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters( rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient); x509.PrivateKey = DotNetUtilities.ToRSA(rsaparams); File.WriteAllBytes(certificateFileName.Replace(".pfx", ".cer"), x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Cert)); // Export Certificate with private key File.WriteAllBytes(certificateFileName, x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pkcs12, privateKeyFilePassword)); return(x509); }
public AsymmetricKeyParameter GenerateCACertificate(string subjectName, string privateKeyFilePassword, string rootsigningCertFileName, int keyStrength = 2048) { // 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(long.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); KeyUsage keyUsage = new KeyUsage(KeyUsage.KeyCertSign | KeyUsage.CrlSign); certificateGenerator.AddExtension(X509Extensions.KeyUsage, true, keyUsage); // 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; // selfsign certificate ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA512WITHRSA", issuerKeyPair.Private, random); Org.BouncyCastle.X509.X509Certificate certificate = certificateGenerator.Generate(signatureFactory); System.Security.Cryptography.X509Certificates.X509Certificate2 x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded()); #region Private Key // correcponding private key PrivateKeyInfo pinfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private); var seq = (Asn1Sequence)Asn1Object.FromByteArray(pinfo.ParsePrivateKey().GetDerEncoded()); if (seq.Count != 9) { throw new PemException("malformed sequence in RSA private key"); } RsaPrivateKeyStructure rsa = RsaPrivateKeyStructure.GetInstance(seq); RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters( rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient); x509.PrivateKey = DotNetUtilities.ToRSA(rsaparams); #endregion // Add CA certificate to Root store AddCertToStore(x509, System.Security.Cryptography.X509Certificates.StoreName.Root, System.Security.Cryptography.X509Certificates.StoreLocation.LocalMachine); File.WriteAllBytes(rootsigningCertFileName.Replace(".pfx", ".cer"), x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Cert)); // Export Certificate with private key File.WriteAllBytes(rootsigningCertFileName, x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pkcs12, privateKeyFilePassword)); return(issuerKeyPair.Private); }
public static AsymmetricKeyParameter CreateKey( PrivateKeyInfo keyInfo) { AlgorithmIdentifier algID = keyInfo.PrivateKeyAlgorithm; DerObjectIdentifier algOid = algID.Algorithm; // TODO See RSAUtil.isRsaOid in Java build if (algOid.Equals(PkcsObjectIdentifiers.RsaEncryption) || algOid.Equals(X509ObjectIdentifiers.IdEARsa) || algOid.Equals(PkcsObjectIdentifiers.IdRsassaPss) || algOid.Equals(PkcsObjectIdentifiers.IdRsaesOaep)) { RsaPrivateKeyStructure keyStructure = RsaPrivateKeyStructure.GetInstance(keyInfo.ParsePrivateKey()); return(new RsaPrivateCrtKeyParameters( keyStructure.Modulus, keyStructure.PublicExponent, keyStructure.PrivateExponent, keyStructure.Prime1, keyStructure.Prime2, keyStructure.Exponent1, keyStructure.Exponent2, keyStructure.Coefficient)); } // TODO? // else if (algOid.Equals(X9ObjectIdentifiers.DHPublicNumber)) else if (algOid.Equals(PkcsObjectIdentifiers.DhKeyAgreement)) { DHParameter para = new DHParameter( Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object())); DerInteger derX = (DerInteger)keyInfo.ParsePrivateKey(); BigInteger lVal = para.L; int l = lVal == null ? 0 : lVal.IntValue; DHParameters dhParams = new DHParameters(para.P, para.G, null, l); return(new DHPrivateKeyParameters(derX.Value, dhParams, algOid)); } else if (algOid.Equals(OiwObjectIdentifiers.ElGamalAlgorithm)) { ElGamalParameter para = new ElGamalParameter( Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object())); DerInteger derX = (DerInteger)keyInfo.ParsePrivateKey(); return(new ElGamalPrivateKeyParameters( derX.Value, new ElGamalParameters(para.P, para.G))); } else if (algOid.Equals(X9ObjectIdentifiers.IdDsa)) { DerInteger derX = (DerInteger)keyInfo.ParsePrivateKey(); Asn1Encodable ae = algID.Parameters; DsaParameters parameters = null; if (ae != null) { DsaParameter para = DsaParameter.GetInstance(ae.ToAsn1Object()); parameters = new DsaParameters(para.P, para.Q, para.G); } return(new DsaPrivateKeyParameters(derX.Value, parameters)); } else if (algOid.Equals(X9ObjectIdentifiers.IdECPublicKey)) { X962Parameters para = new X962Parameters(algID.Parameters.ToAsn1Object()); X9ECParameters x9; if (para.IsNamedCurve) { x9 = ECKeyPairGenerator.FindECCurveByOid((DerObjectIdentifier)para.Parameters); } else { x9 = new X9ECParameters((Asn1Sequence)para.Parameters); } ECPrivateKeyStructure ec = ECPrivateKeyStructure.GetInstance(keyInfo.ParsePrivateKey()); BigInteger d = ec.GetKey(); if (para.IsNamedCurve) { return(new ECPrivateKeyParameters("EC", d, (DerObjectIdentifier)para.Parameters)); } ECDomainParameters dParams = new ECDomainParameters(x9.Curve, x9.G, x9.N, x9.H, x9.GetSeed()); return(new ECPrivateKeyParameters(d, dParams)); } else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x2001)) { Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters( Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object())); ECDomainParameters ecP = ECGost3410NamedCurves.GetByOid(gostParams.PublicKeyParamSet); if (ecP == null) { throw new ArgumentException("Unrecognized curve OID for GostR3410x2001 private key"); } Asn1Object privKey = keyInfo.ParsePrivateKey(); ECPrivateKeyStructure ec; if (privKey is DerInteger) { ec = new ECPrivateKeyStructure(ecP.N.BitLength, ((DerInteger)privKey).PositiveValue); } else { ec = ECPrivateKeyStructure.GetInstance(privKey); } return(new ECPrivateKeyParameters("ECGOST3410", ec.GetKey(), gostParams.PublicKeyParamSet)); } else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x94)) { Gost3410PublicKeyAlgParameters gostParams = Gost3410PublicKeyAlgParameters.GetInstance(algID.Parameters); Asn1Object privKey = keyInfo.ParsePrivateKey(); BigInteger x; if (privKey is DerInteger) { x = DerInteger.GetInstance(privKey).PositiveValue; } else { x = new BigInteger(1, Arrays.Reverse(Asn1OctetString.GetInstance(privKey).GetOctets())); } return(new Gost3410PrivateKeyParameters(x, gostParams.PublicKeyParamSet)); } else { throw new SecurityUtilityException("algorithm identifier in key not recognised"); } }
protected virtual X509Certificate2 CreateCertificate(string subjectName, bool isCertificateAuthority, string altName) { // Generating Random Numbers var randomGenerator = new CryptoApiRandomGenerator(); var random = new SecureRandom(randomGenerator); // The Certificate Generator var certificateGenerator = new X509V3CertificateGenerator(); if (!isCertificateAuthority) { certificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage.Id, true, new ExtendedKeyUsage(KeyPurposeID.IdKPServerAuth)); } else { certificateGenerator.AddExtension(X509Extensions.BasicConstraints.Id, true, new BasicConstraints(true)); } // Serial Number BigInteger serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random); certificateGenerator.SetSerialNumber(serialNumber); // Issuer and Subject Name var subjectDN = new X509Name(true, subjectName); certificateGenerator.SetSubjectDN(subjectDN); certificateGenerator.SetIssuerDN(isCertificateAuthority ? subjectDN : new X509Name(true, $"CN={RootCertificateName}, O={Issuer}")); if (!isCertificateAuthority) { var subjectAltName = new GeneralNames(new GeneralName(GeneralName.DnsName, altName)); certificateGenerator.AddExtension(X509Extensions.SubjectAlternativeName, false, subjectAltName); } // Valid For DateTime notBefore = DateTime.UtcNow.Date; certificateGenerator.SetNotBefore(notBefore); DateTime notAfter = notBefore.AddYears(1); certificateGenerator.SetNotAfter(notAfter); // Subject Public Key var keyGenerationParameters = new KeyGenerationParameters(random, 1024); var keyPairGenerator = new RsaKeyPairGenerator(); keyPairGenerator.Init(keyGenerationParameters); AsymmetricCipherKeyPair subjectKeyPair = keyPairGenerator.GenerateKeyPair(); certificateGenerator.SetPublicKey(subjectKeyPair.Public); AsymmetricKeyParameter issuerPrivateKey; if (isCertificateAuthority) { issuerPrivateKey = subjectKeyPair.Private; _privateKey = issuerPrivateKey; } else { if (_privateKey == null) { X509Certificate2 rootCA = InstallCertificate(RootStore, RootCertificateName); _privateKey = TransformRSAPrivateKey(rootCA.GetRSAPrivateKey().ExportParameters(true)); } issuerPrivateKey = _privateKey; } var privateKey = (RsaPrivateCrtKeyParameters)issuerPrivateKey; if (!isCertificateAuthority) { PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private); var seq = (Asn1Sequence)Asn1Object.FromByteArray(info.ParsePrivateKey().GetDerEncoded()); var rsa = RsaPrivateKeyStructure.GetInstance(seq); privateKey = new RsaPrivateCrtKeyParameters(rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient); } // Self-Sign Certificate ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA256WITHRSA", issuerPrivateKey, random); X509Certificate2 certificate = GetSignedCertificate(certificateGenerator.Generate(signatureFactory), privateKey); certificate.FriendlyName = subjectName; return(certificate); }
private static byte[] GetRawKey(PrivateKeyInfo keyInfo) { return(Asn1OctetString.GetInstance(keyInfo.ParsePrivateKey()).GetOctets()); }
/// <summary> /// Constructor from an algorithm and a PrivateKeyInfo object containing a NewHope private key. /// </summary> /// <param name="algorithm">Algorithm marker to associate with the key.</param> /// <param name="privateKeyInfo">A PrivateKeyInfo object.</param> public AsymmetricNHPrivateKey(Algorithm algorithm, PrivateKeyInfo privateKeyInfo) : base(algorithm) { this.privateKeyData = Convert(Asn1OctetString.GetInstance(privateKeyInfo.ParsePrivateKey()).GetOctets()); }
/// <summary> /// https://stackoverflow.com/questions/22230745/generate-a-self-signed-certificate-on-the-fly /// </summary> /// <param name="subjectName"></param> /// <param name="issuerName"></param> /// <param name="issuerPrivKey"></param> /// <returns></returns> public static X509Certificate2 GenerateSelfSignedCertificate( string subjectName, string issuerName, AsymmetricKeyParameter issuerPrivKey) { const int keyStrength = 2048; // Generating Random Numbers CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator(); SecureRandom random = new SecureRandom(randomGenerator); // The Certificate Generator X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator(); // Serial Number BigInteger serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(long.MaxValue), random); certificateGenerator.SetSerialNumber(serialNumber); // Signature Algorithm const string signatureAlgorithm = "SHA256WithRSA"; certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm); // Issuer and Subject Name X509Name subjectDn = new X509Name(subjectName); X509Name issuerDn = new X509Name(issuerName); certificateGenerator.SetIssuerDN(issuerDn); certificateGenerator.SetSubjectDN(subjectDn); // Valid For DateTime notBefore = DateTime.UtcNow.Date; DateTime notAfter = notBefore.AddYears(2); certificateGenerator.SetNotBefore(notBefore); certificateGenerator.SetNotAfter(notAfter); // Subject Public Key var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength); var keyPairGenerator = new RsaKeyPairGenerator(); keyPairGenerator.Init(keyGenerationParameters); var subjectKeyPair = keyPairGenerator.GenerateKeyPair(); certificateGenerator.SetPublicKey(subjectKeyPair.Public); // Selfsign certificate Org.BouncyCastle.X509.X509Certificate certificate = certificateGenerator.Generate(issuerPrivKey, random); // Corresponding private key PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private); // Merge into X509Certificate2 X509Certificate2 x509 = new X509Certificate2(certificate.GetEncoded(), string.Empty, X509KeyStorageFlags.EphemeralKeySet); Asn1Sequence seq = (Asn1Sequence)Asn1Object.FromByteArray(info.ParsePrivateKey().GetDerEncoded()); if (seq.Count != 9) { throw new PemException("malformed sequence in RSA private key"); } RsaPrivateKeyStructure rsa = new RsaPrivateKeyStructure(seq); RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters( rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient); x509.PrivateKey = ToDotNetKey(rsaparams); // x509.PrivateKey = DotNetUtilities.ToRSA(rsaparams); return(x509); }
/// <summary> /// 生成自签名证书 /// </summary> /// <param name="subjectName"></param> /// <param name="issuerName"></param> /// <param name="issuerPrivKey"></param> /// <param name="keyStrength"></param> /// <returns></returns> public static X509Certificate2 GenerateSelfSignedCertificate(string subjectName, string issuerName, AsymmetricKeyParameter issuerPrivKey, int keyStrength = 2048) { // 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 = new X509Name(issuerName); certificateGenerator.SetIssuerDN(issuerDN); certificateGenerator.SetSubjectDN(subjectDN); // Valid For var notBefore = DateTime.UtcNow.Date; var notAfter = notBefore.AddYears(2); certificateGenerator.SetNotBefore(notBefore); certificateGenerator.SetNotAfter(notAfter); // 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; // https://stackoverflow.com/questions/60547020/c-sharp-generate-intermediate-certificate-from-self-signed-root-ca ISignatureFactory signatureFactory = new Asn1SignatureFactory(PkcsObjectIdentifiers.Sha256WithRsaEncryption.ToString(), issuerPrivKey, random); // ISignatureFactory signatureFactory = new Asn1SignatureFactory(PkcsObjectIdentifiers.Sha256WithRsaEncryption.ToString(), issuerKeyPair.Private, random); // selfsign certificate var certificate = certificateGenerator.Generate(signatureFactory); // Corresponding private key PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private); // Merge into X509Certificate2 var x509 = new X509Certificate2(certificate.GetEncoded()); Asn1Sequence seq = (Asn1Sequence)Asn1Object.FromByteArray(info.ParsePrivateKey().GetDerEncoded()); if (seq.Count != 9) { throw new PemException("malformed sequence in RSA private key"); } RsaPrivateKeyStructure rsa = RsaPrivateKeyStructure.GetInstance(seq); RsaPrivateCrtKeyParameters rsaParams = new RsaPrivateCrtKeyParameters( rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient); // https://github.com/bcgit/bc-csharp/issues/160 // https://stackoverflow.com/questions/54752834/error-setting-x509certificate2-privatekey // x509.PrivateKey = DotNetUtilities.ToRSA(rsaParams); // return x509; // [DotNetUtilities class only works on Windows](https://github.com/bcgit/bc-csharp/issues/160) // if run on Linux will cause 'CspParameters' requires Windows Cryptographic API (CAPI), which is not available on this platform. // var cert = x509.CopyWithPrivateKey(DotNetUtilities.ToRSA(rsaParams)); var parms = DotNetUtilities.ToRSAParameters(rsaParams); var rsaCreate = RSA.Create(); rsaCreate.ImportParameters(parms); var cert = x509.CopyWithPrivateKey(rsaCreate); return(cert); }