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); }
protected override ECPrivateKeyParameters CreatePrivateKeyParameters() { Asn1Sequence seq = (Asn1Sequence)Asn1Object.FromByteArray(PrivateKeyBytes); ECPrivateKeyStructure pKey = ECPrivateKeyStructure.GetInstance(seq); AlgorithmIdentifier algId = new AlgorithmIdentifier(X9ObjectIdentifiers.IdECPublicKey, pKey.GetParameters()); PrivateKeyInfo privInfo = new PrivateKeyInfo(algId, pKey.ToAsn1Object()); return (ECPrivateKeyParameters)PrivateKeyFactory.CreateKey(privInfo); }
private EncKeyWithID(Asn1Sequence seq) { this.privKeyInfo = PrivateKeyInfo.GetInstance(seq[0]); if (seq.Count > 1) { if (!(seq[1] is DerUtf8String)) { this.identifier = GeneralName.GetInstance(seq[1]); } else { this.identifier = (Asn1Encodable)seq[1]; } } else { this.identifier = null; } }
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 EncKeyWithID(PrivateKeyInfo privKeyInfo) { this.privKeyInfo = privKeyInfo; this.identifier = null; }
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"); } }
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 = Org.BouncyCastle.Utilities.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 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; // selfsign certificate var certificate = certificateGenerator.Generate(issuerPrivKey, random); // correcponding private key Org.BouncyCastle.Asn1.Pkcs.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.PrivateKey.GetDerEncoded()); if (seq.Count != 9) { throw new Org.BouncyCastle.OpenSsl.PemException("malformed sequence in RSA private key"); } var 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); return(x509); }
protected virtual void LoadKeyBag(PrivateKeyInfo privKeyInfo, Asn1Set bagAttributes) { AsymmetricKeyParameter privKey = PrivateKeyFactory.CreateKey(privKeyInfo); IDictionary attributes = Platform.CreateHashtable(); AsymmetricKeyEntry keyEntry = new AsymmetricKeyEntry(privKey, attributes); string alias = null; Asn1OctetString localId = null; if (bagAttributes != null) { foreach (Asn1Sequence sq in bagAttributes) { DerObjectIdentifier aOid = DerObjectIdentifier.GetInstance(sq[0]); Asn1Set attrSet = Asn1Set.GetInstance(sq[1]); Asn1Encodable attr = null; if (attrSet.Count > 0) { // TODO We should be adding all attributes in the set attr = attrSet[0]; // TODO We might want to "merge" attribute sets with // the same OID - currently, differing values give an error if (attributes.Contains(aOid.Id)) { // OK, but the value has to be the same if (!attributes[aOid.Id].Equals(attr)) throw new IOException("attempt to add existing attribute with different value"); } else { attributes.Add(aOid.Id, attr); } if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName)) { alias = ((DerBmpString)attr).GetString(); // TODO Do these in a separate loop, just collect aliases here keys[alias] = keyEntry; } else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID)) { localId = (Asn1OctetString)attr; } } } } if (localId != null) { string name = Hex.ToHexString(localId.GetOctets()); if (alias == null) { keys[name] = keyEntry; } else { // TODO There may have been more than one alias localIds[alias] = name; } } else { unmarkedKeyEntry = keyEntry; } }
internal static AsymmetricKeyParameter GetPrivateKeyFromPEM(Org.BouncyCastle.Utilities.IO.Pem.PemObject pem) { AsymmetricKeyParameter result = null; if (pem.Type.EndsWith("EC PRIVATE KEY")) { Asn1Sequence sequence = Asn1Sequence.GetInstance(pem.Content); IEnumerator e = sequence.GetEnumerator(); e.MoveNext(); BigInteger version = ((DerInteger)e.Current).Value; PrivateKeyInfo privateKeyInfo; if (version.IntValue == 0) //V1 { privateKeyInfo = PrivateKeyInfo.GetInstance(sequence); } else { Org.BouncyCastle.Asn1.Sec.ECPrivateKeyStructure ec = Org.BouncyCastle.Asn1.Sec.ECPrivateKeyStructure.GetInstance(sequence); AlgorithmIdentifier algId = new AlgorithmIdentifier(Org.BouncyCastle.Asn1.X9.X9ObjectIdentifiers.IdECPublicKey, ec.GetParameters()); privateKeyInfo = new PrivateKeyInfo(algId, ec.ToAsn1Object()); } result = Org.BouncyCastle.Security.PrivateKeyFactory.CreateKey(privateKeyInfo); } else if (pem.Type.EndsWith("PRIVATE KEY")) { result = Org.BouncyCastle.Security.PrivateKeyFactory.CreateKey(pem.Content); } return result; }
public static AsymmetricKeyParameter CreateKey( PrivateKeyInfo keyInfo) { AlgorithmIdentifier algID = keyInfo.AlgorithmID; DerObjectIdentifier algOid = algID.ObjectID; // 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 = new RsaPrivateKeyStructure( Asn1Sequence.GetInstance(keyInfo.PrivateKey)); return new RsaPrivateCrtKeyParameters( keyStructure.Modulus, keyStructure.PublicExponent, keyStructure.PrivateExponent, keyStructure.Prime1, keyStructure.Prime2, keyStructure.Exponent1, keyStructure.Exponent2, keyStructure.Coefficient); } else if (algOid.Equals(PkcsObjectIdentifiers.DhKeyAgreement)) { DHParameter para = new DHParameter( Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object())); DerInteger derX = (DerInteger)keyInfo.PrivateKey; 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); } else if (algOid.Equals(OiwObjectIdentifiers.ElGamalAlgorithm)) { ElGamalParameter para = new ElGamalParameter( Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object())); DerInteger derX = (DerInteger)keyInfo.PrivateKey; return new ElGamalPrivateKeyParameters( derX.Value, new ElGamalParameters(para.P, para.G)); } else if (algOid.Equals(X9ObjectIdentifiers.IdDsa)) { DerInteger derX = (DerInteger) keyInfo.PrivateKey; 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 ecP; if (para.IsNamedCurve) { // TODO ECGost3410NamedCurves support (returns ECDomainParameters though) DerObjectIdentifier oid = (DerObjectIdentifier) para.Parameters; ecP = X962NamedCurves.GetByOid(oid); if (ecP == null) { ecP = SecNamedCurves.GetByOid(oid); if (ecP == null) { ecP = NistNamedCurves.GetByOid(oid); if (ecP == null) { ecP = TeleTrusTNamedCurves.GetByOid(oid); } } } } else { ecP = new X9ECParameters((Asn1Sequence) para.Parameters); } ECDomainParameters dParams = new ECDomainParameters( ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed()); ECPrivateKeyStructure ec = new ECPrivateKeyStructure( Asn1Sequence.GetInstance(keyInfo.PrivateKey)); return new ECPrivateKeyParameters(ec.GetKey(), dParams); } else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x2001)) { Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters( Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object())); ECPrivateKeyStructure ec = new ECPrivateKeyStructure( Asn1Sequence.GetInstance(keyInfo.PrivateKey)); ECDomainParameters ecP = ECGost3410NamedCurves.GetByOid(gostParams.PublicKeyParamSet); if (ecP == null) return null; return new ECPrivateKeyParameters(ec.GetKey(), gostParams.PublicKeyParamSet); } else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x94)) { Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters( Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object())); DerOctetString derX = (DerOctetString) keyInfo.PrivateKey; byte[] keyEnc = derX.GetOctets(); byte[] keyBytes = new byte[keyEnc.Length]; for (int i = 0; i != keyEnc.Length; i++) { keyBytes[i] = keyEnc[keyEnc.Length - 1 - i]; // was little endian } BigInteger x = new BigInteger(1, keyBytes); return new Gost3410PrivateKeyParameters(x, gostParams.PublicKeyParamSet); } else { throw new SecurityUtilityException("algorithm identifier in key not recognised"); } }
public static AsymmetricKeyParameter CreateKey( PrivateKeyInfo keyInfo) { AlgorithmIdentifier algID = keyInfo.PrivateKeyAlgorithm; DerObjectIdentifier algOid = algID.ObjectID; // 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 = new ECPrivateKeyStructure( Asn1Sequence.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())); Asn1Object privKey = keyInfo.ParsePrivateKey(); ECPrivateKeyStructure ec; if (privKey is DerInteger) { // TODO Do we need to pass any parameters here? ec = new ECPrivateKeyStructure(((DerInteger)privKey).Value); } else { ec = ECPrivateKeyStructure.GetInstance(privKey); } ECDomainParameters ecP = ECGost3410NamedCurves.GetByOid(gostParams.PublicKeyParamSet); if (ecP == null) throw new ArgumentException("Unrecognized curve OID for GostR3410x2001 private key"); return new ECPrivateKeyParameters("ECGOST3410", ec.GetKey(), gostParams.PublicKeyParamSet); } else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x94)) { Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters( Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object())); DerOctetString derX = (DerOctetString)keyInfo.ParsePrivateKey(); BigInteger x = new BigInteger(1, Arrays.Reverse(derX.GetOctets())); return new Gost3410PrivateKeyParameters(x, gostParams.PublicKeyParamSet); } else { throw new SecurityUtilityException("algorithm identifier in key not recognised"); } }
/** * Read a Key Pair */ private AsymmetricCipherKeyPair ReadKeyPair( string type, string endMarker) { // // extract the key // IDictionary fields = new Hashtable(); byte[] keyBytes = ReadBytesAndFields(endMarker, fields); string procType = (string) fields["Proc-Type"]; if (procType == "4,ENCRYPTED") { if (pFinder == null) throw new PasswordException("No password finder specified, but a password is required"); char[] password = pFinder.GetPassword(); if (password == null) throw new PasswordException("Password is null, but a password is required"); string dekInfo = (string) fields["DEK-Info"]; string[] tknz = dekInfo.Split(','); string dekAlgName = tknz[0].Trim(); byte[] iv = Hex.Decode(tknz[1].Trim()); keyBytes = PemUtilities.Crypt(false, keyBytes, password, dekAlgName, iv); } try { AsymmetricKeyParameter pubSpec, privSpec; Asn1Sequence seq = (Asn1Sequence) Asn1Object.FromByteArray(keyBytes); switch (type) { case "RSA": { RsaPrivateKeyStructure rsa = new RsaPrivateKeyStructure(seq); pubSpec = new RsaKeyParameters(false, rsa.Modulus, rsa.PublicExponent); privSpec = new RsaPrivateCrtKeyParameters( rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient); break; } case "DSA": { // TODO Create an ASN1 object somewhere for this? //DerInteger v = (DerInteger)seq[0]; DerInteger p = (DerInteger)seq[1]; DerInteger q = (DerInteger)seq[2]; DerInteger g = (DerInteger)seq[3]; DerInteger y = (DerInteger)seq[4]; DerInteger x = (DerInteger)seq[5]; DsaParameters parameters = new DsaParameters(p.Value, q.Value, g.Value); privSpec = new DsaPrivateKeyParameters(x.Value, parameters); pubSpec = new DsaPublicKeyParameters(y.Value, parameters); break; } case "EC": { ECPrivateKeyStructure pKey = new ECPrivateKeyStructure(seq); AlgorithmIdentifier algId = new AlgorithmIdentifier( X9ObjectIdentifiers.IdECPublicKey, pKey.GetParameters()); PrivateKeyInfo privInfo = new PrivateKeyInfo(algId, pKey.ToAsn1Object()); DerBitString pubKey = pKey.GetPublicKey(); //Console.WriteLine(pubKey == null); SubjectPublicKeyInfo pubInfo = new SubjectPublicKeyInfo(algId, pubKey.GetBytes()); // TODO Are the keys returned here ECDSA, as Java version forces? privSpec = PrivateKeyFactory.CreateKey(privInfo); pubSpec = PublicKeyFactory.CreateKey(pubInfo); break; } default: throw new ArgumentException("Unknown key type: " + type, "type"); } return new AsymmetricCipherKeyPair(pubSpec, privSpec); } catch (Exception e) { throw new PemException( "problem creating " + type + " private key: " + e.ToString()); } }
private AsymmetricCipherKeyPair ReadECPrivateKey( string endMarker) { try { byte[] bytes = ReadBytes(endMarker); ECPrivateKeyStructure pKey = new ECPrivateKeyStructure( (Asn1Sequence) Asn1Object.FromByteArray(bytes)); AlgorithmIdentifier algId = new AlgorithmIdentifier( X9ObjectIdentifiers.IdECPublicKey, pKey.GetParameters()); PrivateKeyInfo privInfo = new PrivateKeyInfo(algId, pKey.ToAsn1Object()); SubjectPublicKeyInfo pubInfo = new SubjectPublicKeyInfo(algId, pKey.GetPublicKey().GetBytes()); // TODO Are the keys returned here ECDSA, as Java version forces? return new AsymmetricCipherKeyPair( PublicKeyFactory.CreateKey(pubInfo), PrivateKeyFactory.CreateKey(privInfo)); } catch (InvalidCastException e) { throw new IOException("wrong ASN.1 object found in stream.", e); } catch (Exception e) { throw new PemException("problem parsing EC private key.", e); } }
public EncKeyWithID(PrivateKeyInfo privKeyInfo, DerUtf8String str) { this.privKeyInfo = privKeyInfo; this.identifier = str; }
public static PrivateKeyInfo CreatePrivateKeyInfo( AsymmetricKeyParameter key) { if (key == null) throw new ArgumentNullException("key"); if (!key.IsPrivate) throw new ArgumentException("Public key passed - private key expected", "key"); if (key is ElGamalPrivateKeyParameters) { ElGamalPrivateKeyParameters _key = (ElGamalPrivateKeyParameters)key; PrivateKeyInfo info = new PrivateKeyInfo( new AlgorithmIdentifier( OiwObjectIdentifiers.ElGamalAlgorithm, new ElGamalParameter( _key.Parameters.P, _key.Parameters.G).ToAsn1Object()), new DerInteger(_key.X)); return info; } if (key is DsaPrivateKeyParameters) { DsaPrivateKeyParameters _key = (DsaPrivateKeyParameters)key; PrivateKeyInfo info = new PrivateKeyInfo( new AlgorithmIdentifier( X9ObjectIdentifiers.IdDsa, new DsaParameter( _key.Parameters.P, _key.Parameters.Q, _key.Parameters.G).ToAsn1Object()), new DerInteger(_key.X)); return info; } if (key is DHPrivateKeyParameters) { /* Process DH private key. The value for L was set to zero implicitly. This is the same action as found in JCEDHPrivateKey GetEncoded method. */ DHPrivateKeyParameters _key = (DHPrivateKeyParameters)key; DHParameter withNewL = new DHParameter( _key.Parameters.P, _key.Parameters.G, 0); PrivateKeyInfo info = new PrivateKeyInfo( new AlgorithmIdentifier( PkcsObjectIdentifiers.DhKeyAgreement, withNewL.ToAsn1Object()), new DerInteger(_key.X)); return info; } if (key is RsaKeyParameters) { if (key is RsaPrivateCrtKeyParameters) { RsaPrivateCrtKeyParameters _key = (RsaPrivateCrtKeyParameters)key; PrivateKeyInfo info = new PrivateKeyInfo( new AlgorithmIdentifier( PkcsObjectIdentifiers.RsaEncryption, DerNull.Instance), new RsaPrivateKeyStructure( _key.Modulus, _key.PublicExponent, _key.Exponent, _key.P, _key.Q, _key.DP, _key.DQ, _key.QInv).ToAsn1Object()); return info; } // TODO Check that we are not supposed to be able to encode these // RsaKeyParameters rkp = (RsaKeyParameters) key; } if (key is ECPrivateKeyParameters) { ECPrivateKeyParameters _key = (ECPrivateKeyParameters)key; if (_key.AlgorithmName == "ECGOST3410") { throw new NotImplementedException(); } else { X9ECParameters ecP = new X9ECParameters( _key.Parameters.Curve, _key.Parameters.G, _key.Parameters.N, _key.Parameters.H, _key.Parameters.GetSeed()); X962Parameters x962 = new X962Parameters(ecP); PrivateKeyInfo info = new PrivateKeyInfo( new AlgorithmIdentifier(X9ObjectIdentifiers.IdECPublicKey, x962.ToAsn1Object()), new ECPrivateKeyStructure(_key.D).ToAsn1Object()); return info; } } if (key is Gost3410PrivateKeyParameters) { Gost3410PrivateKeyParameters _key = (Gost3410PrivateKeyParameters)key; if (_key.PublicKeyParamSet == null) throw new NotImplementedException("Encoding only implemented for CryptoPro parameter sets"); // TODO Once it is efficiently implemented, use ToByteArrayUnsigned byte[] keyEnc = _key.X.ToByteArray(); byte[] keyBytes; if (keyEnc[0] == 0) { keyBytes = new byte[keyEnc.Length - 1]; } else { keyBytes = new byte[keyEnc.Length]; } for (int i = 0; i != keyBytes.Length; i++) { keyBytes[i] = keyEnc[keyEnc.Length - 1 - i]; // must be little endian } Gost3410PublicKeyAlgParameters algParams = new Gost3410PublicKeyAlgParameters( _key.PublicKeyParamSet, CryptoProObjectIdentifiers.GostR3411x94CryptoProParamSet, null); AlgorithmIdentifier algID = new AlgorithmIdentifier( CryptoProObjectIdentifiers.GostR3410x94, algParams.ToAsn1Object()); return new PrivateKeyInfo(algID, new DerOctetString(keyBytes)); } throw new ArgumentException("Class provided is not convertible: " + key.GetType().FullName); }
public EncKeyWithID(PrivateKeyInfo privKeyInfo, GeneralName generalName) { this.privKeyInfo = privKeyInfo; this.identifier = generalName; }
/** * Read a Key Pair */ private object ReadPrivateKey(PemObject pemObject) { // // extract the key // Debug.Assert(pemObject.Type.EndsWith("PRIVATE KEY")); string type = pemObject.Type.Substring(0, pemObject.Type.Length - "PRIVATE KEY".Length).Trim(); byte[] keyBytes = pemObject.Content; IDictionary fields = Platform.CreateHashtable(); foreach (PemHeader header in pemObject.Headers) { fields[header.Name] = header.Value; } string procType = (string) fields["Proc-Type"]; if (procType == "4,ENCRYPTED") { if (pFinder == null) throw new PasswordException("No password finder specified, but a password is required"); char[] password = pFinder.GetPassword(); if (password == null) throw new PasswordException("Password is null, but a password is required"); string dekInfo = (string) fields["DEK-Info"]; string[] tknz = dekInfo.Split(','); string dekAlgName = tknz[0].Trim(); byte[] iv = Hex.Decode(tknz[1].Trim()); keyBytes = PemUtilities.Crypt(false, keyBytes, password, dekAlgName, iv); } try { IAsymmetricKeyParameter pubSpec, privSpec; Asn1Sequence seq = (Asn1Sequence) Asn1Object.FromByteArray(keyBytes); switch (type) { case "RSA": { if (seq.Count != 9) throw new PemException("malformed sequence in RSA private key"); RsaPrivateKeyStructure rsa = new RsaPrivateKeyStructure(seq); pubSpec = new RsaKeyParameters(false, rsa.Modulus, rsa.PublicExponent); privSpec = new RsaPrivateCrtKeyParameters( rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient); break; } case "DSA": { if (seq.Count != 6) throw new PemException("malformed sequence in DSA private key"); // TODO Create an ASN1 object somewhere for this? //DerInteger v = (DerInteger)seq[0]; DerInteger p = (DerInteger)seq[1]; DerInteger q = (DerInteger)seq[2]; DerInteger g = (DerInteger)seq[3]; DerInteger y = (DerInteger)seq[4]; DerInteger x = (DerInteger)seq[5]; DsaParameters parameters = new DsaParameters(p.Value, q.Value, g.Value); privSpec = new DsaPrivateKeyParameters(x.Value, parameters); pubSpec = new DsaPublicKeyParameters(y.Value, parameters); break; } case "EC": { ECPrivateKeyStructure pKey = new ECPrivateKeyStructure(seq); AlgorithmIdentifier algId = new AlgorithmIdentifier( X9ObjectIdentifiers.IdECPublicKey, pKey.GetParameters()); PrivateKeyInfo privInfo = new PrivateKeyInfo(algId, pKey.ToAsn1Object()); // TODO Are the keys returned here ECDSA, as Java version forces? privSpec = PrivateKeyFactory.CreateKey(privInfo); DerBitString pubKey = pKey.GetPublicKey(); if (pubKey != null) { SubjectPublicKeyInfo pubInfo = new SubjectPublicKeyInfo(algId, pubKey.GetBytes()); // TODO Are the keys returned here ECDSA, as Java version forces? pubSpec = PublicKeyFactory.CreateKey(pubInfo); } else { pubSpec = ECKeyPairGenerator.GetCorrespondingPublicKey( (ECPrivateKeyParameters)privSpec); } break; } case "ENCRYPTED": { char[] password = pFinder.GetPassword(); if (password == null) throw new PasswordException("Password is null, but a password is required"); return PrivateKeyFactory.DecryptKey(password, EncryptedPrivateKeyInfo.GetInstance(seq)); } case "": { return PrivateKeyFactory.CreateKey(PrivateKeyInfo.GetInstance(seq)); } default: throw new ArgumentException("Unknown key type: " + type, "type"); } return new AsymmetricCipherKeyPair(pubSpec, privSpec); } catch (IOException e) { throw e; } catch (Exception e) { throw new PemException( "problem creating " + type + " private key: " + e.ToString()); } }
public static AsymmetricKeyParameter CreateKey( PrivateKeyInfo keyInfo) { AlgorithmIdentifier algID = keyInfo.AlgorithmID; if (algID.ObjectID.Equals(PkcsObjectIdentifiers.RsaEncryption)) { RsaPrivateKeyStructure keyStructure = new RsaPrivateKeyStructure( (Asn1Sequence)keyInfo.PrivateKey); return (new RsaPrivateCrtKeyParameters( keyStructure.Modulus, keyStructure.PublicExponent, keyStructure.PrivateExponent, keyStructure.Prime1, keyStructure.Prime2, keyStructure.Exponent1, keyStructure.Exponent2, keyStructure.Coefficient)); } else if (algID.ObjectID.Equals(PkcsObjectIdentifiers.DhKeyAgreement)) { DHParameter para = new DHParameter((Asn1Sequence)algID.Parameters); DerInteger derX = (DerInteger)keyInfo.PrivateKey; return new DHPrivateKeyParameters(derX.Value, new DHParameters(para.P, para.G)); } else if (algID.ObjectID.Equals(OiwObjectIdentifiers.ElGamalAlgorithm)) { ElGamalParameter para = new ElGamalParameter((Asn1Sequence)algID.Parameters); DerInteger derX = (DerInteger)keyInfo.PrivateKey; return new ElGamalPrivateKeyParameters(derX.Value, new ElGamalParameters(para.P, para.G)); } else if (algID.ObjectID.Equals(X9ObjectIdentifiers.IdDsa)) { DsaParameter para = DsaParameter.GetInstance(algID.Parameters); DerInteger derX = (DerInteger) keyInfo.PrivateKey; return new DsaPrivateKeyParameters(derX.Value, new DsaParameters(para.P, para.Q, para.G)); } else if (algID.ObjectID.Equals(X9ObjectIdentifiers.IdECPublicKey)) { X962Parameters para = new X962Parameters((Asn1Object)algID.Parameters); ECDomainParameters dParams = null; if (para.IsNamedCurve) { DerObjectIdentifier oid = (DerObjectIdentifier) para.Parameters; X9ECParameters ecP = X962NamedCurves.GetByOid(oid); if (ecP == null) { ecP = SecNamedCurves.GetByOid(oid); if (ecP == null) { ecP = NistNamedCurves.GetByOid(oid); } } dParams = new ECDomainParameters( ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed()); } else { X9ECParameters ecP = new X9ECParameters( (Asn1Sequence) para.Parameters); dParams = new ECDomainParameters( ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed()); } ECPrivateKeyStructure ec = new ECPrivateKeyStructure((Asn1Sequence)keyInfo.PrivateKey); return new ECPrivateKeyParameters(ec.GetKey(), dParams); } else if (algID.ObjectID.Equals(CryptoProObjectIdentifiers.GostR3410x2001)) { throw new NotImplementedException(); } else if (algID.ObjectID.Equals(CryptoProObjectIdentifiers.GostR3410x94)) { Gost3410PublicKeyAlgParameters algParams = new Gost3410PublicKeyAlgParameters( (Asn1Sequence) algID.Parameters); DerOctetString derX = (DerOctetString) keyInfo.PrivateKey; byte[] keyEnc = derX.GetOctets(); byte[] keyBytes = new byte[keyEnc.Length]; for (int i = 0; i != keyEnc.Length; i++) { keyBytes[i] = keyEnc[keyEnc.Length - 1 - i]; // was little endian } BigInteger x = new BigInteger(1, keyBytes); return new Gost3410PrivateKeyParameters(x, algParams.PublicKeyParamSet); } else { throw new SecurityUtilityException("algorithm identifier in key not recognised"); } }
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"); } }