internal PgpPrivateKey DoExtractPrivateKey(byte[] rawPassPhrase, bool clearPassPhrase) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Expected O, but got Unknown if (IsPrivateKeyEmpty) { return(null); } PublicKeyPacket publicKeyPacket = secret.PublicKeyPacket; try { byte[] array = ExtractKeyData(rawPassPhrase, clearPassPhrase); BcpgInputStream bcpgIn = BcpgInputStream.Wrap((Stream) new MemoryStream(array, false)); AsymmetricKeyParameter privateKey; switch (publicKeyPacket.Algorithm) { case PublicKeyAlgorithmTag.RsaGeneral: case PublicKeyAlgorithmTag.RsaEncrypt: case PublicKeyAlgorithmTag.RsaSign: { RsaPublicBcpgKey rsaPublicBcpgKey = (RsaPublicBcpgKey)publicKeyPacket.Key; RsaSecretBcpgKey rsaSecretBcpgKey = new RsaSecretBcpgKey(bcpgIn); RsaPrivateCrtKeyParameters rsaPrivateCrtKeyParameters = new RsaPrivateCrtKeyParameters(rsaSecretBcpgKey.Modulus, rsaPublicBcpgKey.PublicExponent, rsaSecretBcpgKey.PrivateExponent, rsaSecretBcpgKey.PrimeP, rsaSecretBcpgKey.PrimeQ, rsaSecretBcpgKey.PrimeExponentP, rsaSecretBcpgKey.PrimeExponentQ, rsaSecretBcpgKey.CrtCoefficient); privateKey = rsaPrivateCrtKeyParameters; break; } case PublicKeyAlgorithmTag.Dsa: { DsaPublicBcpgKey dsaPublicBcpgKey = (DsaPublicBcpgKey)publicKeyPacket.Key; DsaSecretBcpgKey dsaSecretBcpgKey = new DsaSecretBcpgKey(bcpgIn); DsaParameters parameters2 = new DsaParameters(dsaPublicBcpgKey.P, dsaPublicBcpgKey.Q, dsaPublicBcpgKey.G); privateKey = new DsaPrivateKeyParameters(dsaSecretBcpgKey.X, parameters2); break; } case PublicKeyAlgorithmTag.EC: privateKey = GetECKey("ECDH", bcpgIn); break; case PublicKeyAlgorithmTag.ECDsa: privateKey = GetECKey("ECDSA", bcpgIn); break; case PublicKeyAlgorithmTag.ElGamalEncrypt: case PublicKeyAlgorithmTag.ElGamalGeneral: { ElGamalPublicBcpgKey elGamalPublicBcpgKey = (ElGamalPublicBcpgKey)publicKeyPacket.Key; ElGamalSecretBcpgKey elGamalSecretBcpgKey = new ElGamalSecretBcpgKey(bcpgIn); ElGamalParameters parameters = new ElGamalParameters(elGamalPublicBcpgKey.P, elGamalPublicBcpgKey.G); privateKey = new ElGamalPrivateKeyParameters(elGamalSecretBcpgKey.X, parameters); break; } default: throw new PgpException("unknown public key algorithm encountered"); } return(new PgpPrivateKey(KeyId, publicKeyPacket, privateKey)); } catch (PgpException ex) { throw ex; } catch (global::System.Exception exception) { throw new PgpException("Exception constructing key", exception); } }
/// <summary> /// Create a Subject Public Key Info object for a given public key. /// </summary> /// <param name="key">One of ElGammalPublicKeyParameters, DSAPublicKeyParameter, DHPublicKeyParameters, RsaKeyParameters or ECPublicKeyParameters</param> /// <returns>A subject public key info object.</returns> /// <exception cref="Exception">Throw exception if object provided is not one of the above.</exception> public static SubjectPublicKeyInfo CreateSubjectPublicKeyInfo( AsymmetricKeyParameter key) { if (key == null) { throw new ArgumentNullException("key"); } if (key.IsPrivate) { throw new ArgumentException("Private key passed - public key expected.", "key"); } if (key is ElGamalPublicKeyParameters) { ElGamalPublicKeyParameters _key = (ElGamalPublicKeyParameters)key; ElGamalParameters kp = _key.Parameters; SubjectPublicKeyInfo info = new SubjectPublicKeyInfo( new AlgorithmIdentifier( OiwObjectIdentifiers.ElGamalAlgorithm, new ElGamalParameter(kp.P, kp.G).ToAsn1Object()), new DerInteger(_key.Y)); return(info); } if (key is DsaPublicKeyParameters) { DsaPublicKeyParameters _key = (DsaPublicKeyParameters)key; DsaParameters kp = _key.Parameters; Asn1Encodable ae = kp == null ? null : new DsaParameter(kp.P, kp.Q, kp.G).ToAsn1Object(); return(new SubjectPublicKeyInfo( new AlgorithmIdentifier(X9ObjectIdentifiers.IdDsa, ae), new DerInteger(_key.Y))); } if (key is DHPublicKeyParameters) { DHPublicKeyParameters _key = (DHPublicKeyParameters)key; DHParameters kp = _key.Parameters; SubjectPublicKeyInfo info = new SubjectPublicKeyInfo( new AlgorithmIdentifier( _key.AlgorithmOid, new DHParameter(kp.P, kp.G, kp.L).ToAsn1Object()), new DerInteger(_key.Y)); return(info); } // End of DH if (key is RsaKeyParameters) { RsaKeyParameters _key = (RsaKeyParameters)key; SubjectPublicKeyInfo info = new SubjectPublicKeyInfo( new AlgorithmIdentifier(PkcsObjectIdentifiers.RsaEncryption, DerNull.Instance), new RsaPublicKeyStructure(_key.Modulus, _key.Exponent).ToAsn1Object()); return(info); } // End of RSA. if (key is ECPublicKeyParameters) { ECPublicKeyParameters _key = (ECPublicKeyParameters)key; if (_key.AlgorithmName == "ECGOST3410") { if (_key.PublicKeyParamSet == null) { throw Platform.CreateNotImplementedException("Not a CryptoPro parameter set"); } ECPoint q = _key.Q; BigInteger bX = q.X.ToBigInteger(); BigInteger bY = q.Y.ToBigInteger(); byte[] encKey = new byte[64]; ExtractBytes(encKey, 0, bX); ExtractBytes(encKey, 32, bY); Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters( _key.PublicKeyParamSet, CryptoProObjectIdentifiers.GostR3411x94CryptoProParamSet); AlgorithmIdentifier algID = new AlgorithmIdentifier( CryptoProObjectIdentifiers.GostR3410x2001, gostParams.ToAsn1Object()); return(new SubjectPublicKeyInfo(algID, new DerOctetString(encKey))); } else { X962Parameters x962; if (_key.PublicKeyParamSet == null) { ECDomainParameters kp = _key.Parameters; X9ECParameters ecP = new X9ECParameters(kp.Curve, kp.G, kp.N, kp.H, kp.GetSeed()); x962 = new X962Parameters(ecP); } else { x962 = new X962Parameters(_key.PublicKeyParamSet); } Asn1OctetString p = (Asn1OctetString)(new X9ECPoint(_key.Q).ToAsn1Object()); AlgorithmIdentifier algID = new AlgorithmIdentifier( X9ObjectIdentifiers.IdECPublicKey, x962.ToAsn1Object()); return(new SubjectPublicKeyInfo(algID, p.GetOctets())); } } // End of EC if (key is Gost3410PublicKeyParameters) { Gost3410PublicKeyParameters _key = (Gost3410PublicKeyParameters)key; if (_key.PublicKeyParamSet == null) { throw Platform.CreateNotImplementedException("Not a CryptoPro parameter set"); } byte[] keyEnc = _key.Y.ToByteArrayUnsigned(); byte[] 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); AlgorithmIdentifier algID = new AlgorithmIdentifier( CryptoProObjectIdentifiers.GostR3410x94, algParams.ToAsn1Object()); return(new SubjectPublicKeyInfo(algID, new DerOctetString(keyBytes))); } throw new ArgumentException("Class provided no convertible: " + key.GetType().FullName); }
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"); } }
/** * Create a PrivateKeyInfo representation of a private key with attributes. * * @param privateKey the key to be encoded into the info object. * @param attributes the set of attributes to be included. * @return the appropriate PrivateKeyInfo * @throws java.io.IOException on an error encoding the key */ public static PrivateKeyInfo CreatePrivateKeyInfo(AsymmetricKeyParameter privateKey, Asn1Set attributes) { if (privateKey == null) { throw new ArgumentNullException("privateKey"); } if (!privateKey.IsPrivate) { throw new ArgumentException("Public key passed - private key expected", "privateKey"); } if (privateKey is ElGamalPrivateKeyParameters) { ElGamalPrivateKeyParameters _key = (ElGamalPrivateKeyParameters)privateKey; ElGamalParameters egp = _key.Parameters; return(new PrivateKeyInfo( new AlgorithmIdentifier(OiwObjectIdentifiers.ElGamalAlgorithm, new ElGamalParameter(egp.P, egp.G).ToAsn1Object()), new DerInteger(_key.X), attributes)); } if (privateKey is DsaPrivateKeyParameters) { DsaPrivateKeyParameters _key = (DsaPrivateKeyParameters)privateKey; DsaParameters dp = _key.Parameters; return(new PrivateKeyInfo( new AlgorithmIdentifier(X9ObjectIdentifiers.IdDsa, new DsaParameter(dp.P, dp.Q, dp.G).ToAsn1Object()), new DerInteger(_key.X), attributes)); } if (privateKey is DHPrivateKeyParameters) { DHPrivateKeyParameters _key = (DHPrivateKeyParameters)privateKey; DHParameter p = new DHParameter( _key.Parameters.P, _key.Parameters.G, _key.Parameters.L); return(new PrivateKeyInfo( new AlgorithmIdentifier(_key.AlgorithmOid, p.ToAsn1Object()), new DerInteger(_key.X), attributes)); } if (privateKey is RsaKeyParameters) { AlgorithmIdentifier algID = new AlgorithmIdentifier( PkcsObjectIdentifiers.RsaEncryption, DerNull.Instance); RsaPrivateKeyStructure keyStruct; if (privateKey is RsaPrivateCrtKeyParameters) { RsaPrivateCrtKeyParameters _key = (RsaPrivateCrtKeyParameters)privateKey; keyStruct = new RsaPrivateKeyStructure( _key.Modulus, _key.PublicExponent, _key.Exponent, _key.P, _key.Q, _key.DP, _key.DQ, _key.QInv); } else { RsaKeyParameters _key = (RsaKeyParameters)privateKey; keyStruct = new RsaPrivateKeyStructure( _key.Modulus, BigInteger.Zero, _key.Exponent, BigInteger.Zero, BigInteger.Zero, BigInteger.Zero, BigInteger.Zero, BigInteger.Zero); } return(new PrivateKeyInfo(algID, keyStruct.ToAsn1Object(), attributes)); } if (privateKey is ECPrivateKeyParameters) { ECPrivateKeyParameters priv = (ECPrivateKeyParameters)privateKey; ECDomainParameters dp = priv.Parameters; int orderBitLength = dp.N.BitLength; AlgorithmIdentifier algID; ECPrivateKeyStructure ec; if (priv.AlgorithmName == "ECGOST3410") { if (priv.PublicKeyParamSet == null) { throw Platform.CreateNotImplementedException("Not a CryptoPro parameter set"); } Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters( priv.PublicKeyParamSet, CryptoProObjectIdentifiers.GostR3411x94CryptoProParamSet); algID = new AlgorithmIdentifier(CryptoProObjectIdentifiers.GostR3410x2001, gostParams); // TODO Do we need to pass any parameters here? ec = new ECPrivateKeyStructure(orderBitLength, priv.D); } else { X962Parameters x962; if (priv.PublicKeyParamSet == null) { X9ECParameters ecP = new X9ECParameters(dp.Curve, dp.G, dp.N, dp.H, dp.GetSeed()); x962 = new X962Parameters(ecP); } else { x962 = new X962Parameters(priv.PublicKeyParamSet); } // TODO Possible to pass the publicKey bitstring here? ec = new ECPrivateKeyStructure(orderBitLength, priv.D, x962); algID = new AlgorithmIdentifier(X9ObjectIdentifiers.IdECPublicKey, x962); } return(new PrivateKeyInfo(algID, ec, attributes)); } if (privateKey is Gost3410PrivateKeyParameters) { Gost3410PrivateKeyParameters _key = (Gost3410PrivateKeyParameters)privateKey; if (_key.PublicKeyParamSet == null) { throw Platform.CreateNotImplementedException("Not a CryptoPro parameter set"); } byte[] keyEnc = _key.X.ToByteArrayUnsigned(); byte[] 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), attributes)); } if (privateKey is X448PrivateKeyParameters) { X448PrivateKeyParameters key = (X448PrivateKeyParameters)privateKey; return(new PrivateKeyInfo(new AlgorithmIdentifier(EdECObjectIdentifiers.id_X448), new DerOctetString(key.GetEncoded()), attributes, key.GeneratePublicKey().GetEncoded())); } if (privateKey is X25519PrivateKeyParameters) { X25519PrivateKeyParameters key = (X25519PrivateKeyParameters)privateKey; return(new PrivateKeyInfo(new AlgorithmIdentifier(EdECObjectIdentifiers.id_X25519), new DerOctetString(key.GetEncoded()), attributes, key.GeneratePublicKey().GetEncoded())); } if (privateKey is Ed448PrivateKeyParameters) { Ed448PrivateKeyParameters key = (Ed448PrivateKeyParameters)privateKey; return(new PrivateKeyInfo(new AlgorithmIdentifier(EdECObjectIdentifiers.id_Ed448), new DerOctetString(key.GetEncoded()), attributes, key.GeneratePublicKey().GetEncoded())); } if (privateKey is Ed25519PrivateKeyParameters) { Ed25519PrivateKeyParameters key = (Ed25519PrivateKeyParameters)privateKey; return(new PrivateKeyInfo(new AlgorithmIdentifier(EdECObjectIdentifiers.id_Ed25519), new DerOctetString(key.GetEncoded()), attributes, key.GeneratePublicKey().GetEncoded())); } throw new ArgumentException("Class provided is not convertible: " + Platform.GetTypeName(privateKey)); }
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) { ecP = ECKeyPairGenerator.FindECCurveByOid((DerObjectIdentifier)para.Parameters); } 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("ECGOST3410", 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( SubjectPublicKeyInfo keyInfo) { AlgorithmIdentifier algID = keyInfo.AlgorithmID; 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)) { RsaPublicKeyStructure pubKey = RsaPublicKeyStructure.GetInstance( keyInfo.ParsePublicKey()); return(new RsaKeyParameters(false, pubKey.Modulus, pubKey.PublicExponent)); } else if (algOid.Equals(X9ObjectIdentifiers.DHPublicNumber)) { Asn1Sequence seq = Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object()); DHPublicKey dhPublicKey = DHPublicKey.GetInstance(keyInfo.ParsePublicKey()); BigInteger y = dhPublicKey.Y.Value; if (IsPkcsDHParam(seq)) { return(ReadPkcsDHParam(algOid, y, seq)); } DHDomainParameters dhParams = DHDomainParameters.GetInstance(seq); BigInteger p = dhParams.P.Value; BigInteger g = dhParams.G.Value; BigInteger q = dhParams.Q.Value; BigInteger j = null; if (dhParams.J != null) { j = dhParams.J.Value; } DHValidationParameters validation = null; DHValidationParms dhValidationParms = dhParams.ValidationParms; if (dhValidationParms != null) { byte[] seed = dhValidationParms.Seed.GetBytes(); BigInteger pgenCounter = dhValidationParms.PgenCounter.Value; // TODO Check pgenCounter size? validation = new DHValidationParameters(seed, pgenCounter.IntValue); } return(new DHPublicKeyParameters(y, new DHParameters(p, g, q, j, validation))); } else if (algOid.Equals(PkcsObjectIdentifiers.DhKeyAgreement)) { Asn1Sequence seq = Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object()); DerInteger derY = (DerInteger)keyInfo.ParsePublicKey(); return(ReadPkcsDHParam(algOid, derY.Value, seq)); } else if (algOid.Equals(OiwObjectIdentifiers.ElGamalAlgorithm)) { ElGamalParameter para = new ElGamalParameter( Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object())); DerInteger derY = (DerInteger)keyInfo.ParsePublicKey(); return(new ElGamalPublicKeyParameters( derY.Value, new ElGamalParameters(para.P, para.G))); } else if (algOid.Equals(X9ObjectIdentifiers.IdDsa) || algOid.Equals(OiwObjectIdentifiers.DsaWithSha1)) { DerInteger derY = (DerInteger)keyInfo.ParsePublicKey(); 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 DsaPublicKeyParameters(derY.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); } Asn1OctetString key = new DerOctetString(keyInfo.PublicKeyData.GetBytes()); X9ECPoint derQ = new X9ECPoint(x9.Curve, key); ECPoint q = derQ.Point; if (para.IsNamedCurve) { return(new ECPublicKeyParameters("EC", q, (DerObjectIdentifier)para.Parameters)); } ECDomainParameters dParams = new ECDomainParameters(x9.Curve, x9.G, x9.N, x9.H, x9.GetSeed()); return(new ECPublicKeyParameters(q, dParams)); } else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x2001)) { Gost3410PublicKeyAlgParameters gostParams = Gost3410PublicKeyAlgParameters.GetInstance(algID.Parameters); DerObjectIdentifier publicKeyParamSet = gostParams.PublicKeyParamSet; ECDomainParameters ecP = ECGost3410NamedCurves.GetByOid(publicKeyParamSet); if (ecP == null) { return(null); } Asn1OctetString key; try { key = (Asn1OctetString)keyInfo.ParsePublicKey(); } catch (IOException e) { throw new ArgumentException("error recovering GOST3410_2001 public key", e); } int fieldSize = 32; int keySize = 2 * fieldSize; byte[] keyEnc = key.GetOctets(); if (keyEnc.Length != keySize) { throw new ArgumentException("invalid length for GOST3410_2001 public key"); } byte[] x9Encoding = new byte[1 + keySize]; x9Encoding[0] = 0x04; for (int i = 1; i <= fieldSize; ++i) { x9Encoding[i] = keyEnc[fieldSize - i]; x9Encoding[i + fieldSize] = keyEnc[keySize - i]; } ECPoint q = ecP.Curve.DecodePoint(x9Encoding); return(new ECPublicKeyParameters("ECGOST3410", q, publicKeyParamSet)); } else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x94)) { Gost3410PublicKeyAlgParameters algParams = Gost3410PublicKeyAlgParameters.GetInstance(algID.Parameters); Asn1OctetString key; try { key = (Asn1OctetString)keyInfo.ParsePublicKey(); } catch (IOException e) { throw new ArgumentException("error recovering GOST3410_94 public key", e); } byte[] keyBytes = Arrays.Reverse(key.GetOctets()); // was little endian BigInteger y = new BigInteger(1, keyBytes); return(new Gost3410PublicKeyParameters(y, algParams.PublicKeyParamSet)); } else if (algOid.Equals(EdECObjectIdentifiers.id_X25519)) { return(new X25519PublicKeyParameters(GetRawKey(keyInfo, X25519PublicKeyParameters.KeySize), 0)); } else if (algOid.Equals(EdECObjectIdentifiers.id_X448)) { return(new X448PublicKeyParameters(GetRawKey(keyInfo, X448PublicKeyParameters.KeySize), 0)); } else if (algOid.Equals(EdECObjectIdentifiers.id_Ed25519)) { return(new Ed25519PublicKeyParameters(GetRawKey(keyInfo, Ed25519PublicKeyParameters.KeySize), 0)); } else if (algOid.Equals(EdECObjectIdentifiers.id_Ed448)) { return(new Ed448PublicKeyParameters(GetRawKey(keyInfo, Ed448PublicKeyParameters.KeySize), 0)); } else if (algOid.Equals(RosstandartObjectIdentifiers.id_tc26_gost_3410_12_256) || algOid.Equals(RosstandartObjectIdentifiers.id_tc26_gost_3410_12_512)) { Gost3410PublicKeyAlgParameters gostParams = Gost3410PublicKeyAlgParameters.GetInstance(algID.Parameters); DerObjectIdentifier publicKeyParamSet = gostParams.PublicKeyParamSet; ECGost3410Parameters ecDomainParameters = new ECGost3410Parameters( new ECNamedDomainParameters(publicKeyParamSet, ECGost3410NamedCurves.GetByOid(publicKeyParamSet)), publicKeyParamSet, gostParams.DigestParamSet, gostParams.EncryptionParamSet); Asn1OctetString key; try { key = (Asn1OctetString)keyInfo.ParsePublicKey(); } catch (IOException e) { throw new ArgumentException("error recovering GOST3410_2012 public key", e); } int fieldSize = 32; if (algOid.Equals(RosstandartObjectIdentifiers.id_tc26_gost_3410_12_512)) { fieldSize = 64; } int keySize = 2 * fieldSize; byte[] keyEnc = key.GetOctets(); if (keyEnc.Length != keySize) { throw new ArgumentException("invalid length for GOST3410_2012 public key"); } byte[] x9Encoding = new byte[1 + keySize]; x9Encoding[0] = 0x04; for (int i = 1; i <= fieldSize; ++i) { x9Encoding[i] = keyEnc[fieldSize - i]; x9Encoding[i + fieldSize] = keyEnc[keySize - i]; } ECPoint q = ecDomainParameters.Curve.DecodePoint(x9Encoding); return(new ECPublicKeyParameters(q, ecDomainParameters)); } else { throw new SecurityUtilityException("algorithm identifier in public key not recognised: " + algOid); } }
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 override void PerformTest() { PgpPublicKey pubKey = null; // // Read the public key // PgpPublicKeyRing pgpPub = new PgpPublicKeyRing(testPubKey); pubKey = pgpPub.GetPublicKey(); // // Read the private key // PgpSecretKeyRing sKey = new PgpSecretKeyRing(testPrivKey); PgpSecretKey secretKey = sKey.GetSecretKey(); PgpPrivateKey pgpPrivKey = secretKey.ExtractPrivateKey(pass); // // test signature message // PgpObjectFactory pgpFact = new PgpObjectFactory(sig1); PgpCompressedData c1 = (PgpCompressedData)pgpFact.NextPgpObject(); pgpFact = new PgpObjectFactory(c1.GetDataStream()); PgpOnePassSignatureList p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject(); PgpOnePassSignature ops = p1[0]; PgpLiteralData p2 = (PgpLiteralData)pgpFact.NextPgpObject(); Stream dIn = p2.GetInputStream(); ops.InitVerify(pubKey); int ch; while ((ch = dIn.ReadByte()) >= 0) { ops.Update((byte)ch); } PgpSignatureList p3 = (PgpSignatureList)pgpFact.NextPgpObject(); if (!ops.Verify(p3[0])) { Fail("Failed signature check"); } // // signature generation // GenerateTest(sKey, pubKey, pgpPrivKey); // // signature generation - canonical text // const string data = "hello world!"; byte[] dataBytes = Encoding.ASCII.GetBytes(data); MemoryStream bOut = new MemoryStream(); MemoryStream testIn = new MemoryStream(dataBytes, false); PgpSignatureGenerator sGen = new PgpSignatureGenerator( PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1); sGen.InitSign(PgpSignature.CanonicalTextDocument, pgpPrivKey); PgpCompressedDataGenerator cGen = new PgpCompressedDataGenerator( CompressionAlgorithmTag.Zip); BcpgOutputStream bcOut = new BcpgOutputStream(cGen.Open(new UncloseableStream(bOut))); sGen.GenerateOnePassVersion(false).Encode(bcOut); PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator(); DateTime testDateTime = new DateTime(1973, 7, 27); Stream lOut = lGen.Open( new UncloseableStream(bcOut), PgpLiteralData.Text, "_CONSOLE", dataBytes.Length, testDateTime); while ((ch = testIn.ReadByte()) >= 0) { lOut.WriteByte((byte)ch); sGen.Update((byte)ch); } lGen.Close(); sGen.Generate().Encode(bcOut); cGen.Close(); // // verify Generated signature - canconical text // pgpFact = new PgpObjectFactory(bOut.ToArray()); c1 = (PgpCompressedData)pgpFact.NextPgpObject(); pgpFact = new PgpObjectFactory(c1.GetDataStream()); p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject(); ops = p1[0]; p2 = (PgpLiteralData)pgpFact.NextPgpObject(); if (!p2.ModificationTime.Equals(testDateTime)) { Fail("Modification time not preserved"); } dIn = p2.GetInputStream(); ops.InitVerify(pubKey); while ((ch = dIn.ReadByte()) >= 0) { ops.Update((byte)ch); } p3 = (PgpSignatureList)pgpFact.NextPgpObject(); if (!ops.Verify(p3[0])) { Fail("Failed generated signature check"); } // // Read the public key with user attributes // pgpPub = new PgpPublicKeyRing(testPubWithUserAttr); pubKey = pgpPub.GetPublicKey(); int count = 0; foreach (PgpUserAttributeSubpacketVector attributes in pubKey.GetUserAttributes()) { int sigCount = 0; foreach (object sigs in pubKey.GetSignaturesForUserAttribute(attributes)) { if (sigs == null) { Fail("null signature found"); } sigCount++; } if (sigCount != 1) { Fail("Failed user attributes signature check"); } count++; } if (count != 1) { Fail("Failed user attributes check"); } byte[] pgpPubBytes = pgpPub.GetEncoded(); pgpPub = new PgpPublicKeyRing(pgpPubBytes); pubKey = pgpPub.GetPublicKey(); count = 0; foreach (object ua in pubKey.GetUserAttributes()) { if (ua == null) { Fail("null user attribute found"); } count++; } if (count != 1) { Fail("Failed user attributes reread"); } // // reading test extra data - key with edge condition for DSA key password. // char[] passPhrase = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; sKey = new PgpSecretKeyRing(testPrivKey2); pgpPrivKey = sKey.GetSecretKey().ExtractPrivateKey(passPhrase); // // reading test - aes256 encrypted passphrase. // sKey = new PgpSecretKeyRing(aesSecretKey); pgpPrivKey = sKey.GetSecretKey().ExtractPrivateKey(pass); // // reading test - twofish encrypted passphrase. // sKey = new PgpSecretKeyRing(twofishSecretKey); pgpPrivKey = sKey.GetSecretKey().ExtractPrivateKey(pass); // // use of PgpKeyPair // DsaParametersGenerator pGen = new DsaParametersGenerator(); pGen.Init(512, 80, new SecureRandom()); // TODO Is the certainty okay? DsaParameters dsaParams = pGen.GenerateParameters(); DsaKeyGenerationParameters kgp = new DsaKeyGenerationParameters(new SecureRandom(), dsaParams); IAsymmetricCipherKeyPairGenerator kpg = GeneratorUtilities.GetKeyPairGenerator("DSA"); kpg.Init(kgp); AsymmetricCipherKeyPair kp = kpg.GenerateKeyPair(); PgpKeyPair pgpKp = new PgpKeyPair(PublicKeyAlgorithmTag.Dsa, kp.Public, kp.Private, DateTime.UtcNow); PgpPublicKey k1 = pgpKp.PublicKey; PgpPrivateKey k2 = pgpKp.PrivateKey; }
private void Dsa2Test1() { byte[] seed = Hex.Decode("ED8BEE8D1CB89229D2903CBF0E51EE7377F48698"); DsaParametersGenerator pGen = new DsaParametersGenerator(); pGen.Init(new DsaParameterGenerationParameters(1024, 160, 80, new DsaTestSecureRandom(seed))); DsaParameters parameters = pGen.GenerateParameters(); DsaValidationParameters pv = parameters.ValidationParameters; if (pv.Counter != 5) { Fail("counter incorrect"); } if (!AreEqual(seed, pv.GetSeed())) { Fail("seed incorrect"); } if (!parameters.Q.Equals(new BigInteger("E950511EAB424B9A19A2AEB4E159B7844C589C4F", 16))) { Fail("Q incorrect"); } if (!parameters.P.Equals(new BigInteger( "E0A67598CD1B763B" + "C98C8ABB333E5DDA0CD3AA0E5E1FB5BA8A7B4EABC10BA338" + "FAE06DD4B90FDA70D7CF0CB0C638BE3341BEC0AF8A7330A3" + "307DED2299A0EE606DF035177A239C34A912C202AA5F83B9" + "C4A7CF0235B5316BFC6EFB9A248411258B30B839AF172440" + "F32563056CB67A861158DDD90E6A894C72A5BBEF9E286C6B", 16))) { Fail("P incorrect"); } if (!parameters.G.Equals(new BigInteger( "D29D5121B0423C27" + "69AB21843E5A3240FF19CACC792264E3BB6BE4F78EDD1B15" + "C4DFF7F1D905431F0AB16790E1F773B5CE01C804E509066A" + "9919F5195F4ABC58189FD9FF987389CB5BEDF21B4DAB4F8B" + "76A055FFE2770988FE2EC2DE11AD92219F0B351869AC24DA" + "3D7BA87011A701CE8EE7BFE49486ED4527B7186CA4610A75", 16))) { Fail("G incorrect"); } DsaKeyPairGenerator kpGen = new DsaKeyPairGenerator(); kpGen.Init(new DsaKeyGenerationParameters(FixedSecureRandom.From(Hex.Decode("D0EC4E50BB290A42E9E355C73D8809345DE2E139")), parameters)); AsymmetricCipherKeyPair kp = kpGen.GenerateKeyPair(); DsaPublicKeyParameters pub = (DsaPublicKeyParameters)kp.Public; DsaPrivateKeyParameters priv = (DsaPrivateKeyParameters)kp.Private; if (!pub.Y.Equals(new BigInteger( "25282217F5730501" + "DD8DBA3EDFCF349AAFFEC20921128D70FAC44110332201BB" + "A3F10986140CBB97C726938060473C8EC97B4731DB004293" + "B5E730363609DF9780F8D883D8C4D41DED6A2F1E1BBBDC97" + "9E1B9D6D3C940301F4E978D65B19041FCF1E8B518F5C0576" + "C770FE5A7A485D8329EE2914A2DE1B5DA4A6128CEAB70F79", 16))) { Fail("Y value incorrect"); } if (!priv.X.Equals( new BigInteger("D0EC4E50BB290A42E9E355C73D8809345DE2E139", 16))) { Fail("X value incorrect"); } DsaSigner signer = new DsaSigner(); signer.Init(true, new ParametersWithRandom(kp.Private, FixedSecureRandom.From(Hex.Decode("349C55648DCF992F3F33E8026CFAC87C1D2BA075")))); byte[] msg = Hex.Decode("A9993E364706816ABA3E25717850C26C9CD0D89D"); BigInteger[] sig = signer.GenerateSignature(msg); if (!sig[0].Equals(new BigInteger("636155AC9A4633B4665D179F9E4117DF68601F34", 16))) { Fail("R value incorrect"); } if (!sig[1].Equals(new BigInteger("6C540B02D9D4852F89DF8CFC99963204F4347704", 16))) { Fail("S value incorrect"); } signer.Init(false, kp.Public); if (!signer.VerifySignature(msg, sig[0], sig[1])) { Fail("signature not verified"); } }
public static SubjectPublicKeyInfo CreateSubjectPublicKeyInfo(AsymmetricKeyParameter key) { if (key == null) { throw new ArgumentNullException("key"); } if (key.IsPrivate) { throw new ArgumentException("Private key passed - public key expected.", "key"); } if (key is ElGamalPublicKeyParameters) { ElGamalPublicKeyParameters elGamalPublicKeyParameters = (ElGamalPublicKeyParameters)key; ElGamalParameters parameters = elGamalPublicKeyParameters.Parameters; return(new SubjectPublicKeyInfo(new AlgorithmIdentifier(OiwObjectIdentifiers.ElGamalAlgorithm, new ElGamalParameter(parameters.P, parameters.G).ToAsn1Object()), new DerInteger(elGamalPublicKeyParameters.Y))); } if (key is DsaPublicKeyParameters) { DsaPublicKeyParameters dsaPublicKeyParameters = (DsaPublicKeyParameters)key; DsaParameters parameters2 = dsaPublicKeyParameters.Parameters; Asn1Encodable parameters3 = (parameters2 == null) ? null : new DsaParameter(parameters2.P, parameters2.Q, parameters2.G).ToAsn1Object(); return(new SubjectPublicKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.IdDsa, parameters3), new DerInteger(dsaPublicKeyParameters.Y))); } if (key is DHPublicKeyParameters) { DHPublicKeyParameters dHPublicKeyParameters = (DHPublicKeyParameters)key; DHParameters parameters4 = dHPublicKeyParameters.Parameters; return(new SubjectPublicKeyInfo(new AlgorithmIdentifier(dHPublicKeyParameters.AlgorithmOid, new DHParameter(parameters4.P, parameters4.G, parameters4.L).ToAsn1Object()), new DerInteger(dHPublicKeyParameters.Y))); } if (key is RsaKeyParameters) { RsaKeyParameters rsaKeyParameters = (RsaKeyParameters)key; return(new SubjectPublicKeyInfo(new AlgorithmIdentifier(PkcsObjectIdentifiers.RsaEncryption, DerNull.Instance), new RsaPublicKeyStructure(rsaKeyParameters.Modulus, rsaKeyParameters.Exponent).ToAsn1Object())); } if (key is ECPublicKeyParameters) { ECPublicKeyParameters eCPublicKeyParameters = (ECPublicKeyParameters)key; if (eCPublicKeyParameters.AlgorithmName == "ECGOST3410") { if (eCPublicKeyParameters.PublicKeyParamSet == null) { throw Platform.CreateNotImplementedException("Not a CryptoPro parameter set"); } ECPoint eCPoint = eCPublicKeyParameters.Q.Normalize(); BigInteger bI = eCPoint.AffineXCoord.ToBigInteger(); BigInteger bI2 = eCPoint.AffineYCoord.ToBigInteger(); byte[] array = new byte[64]; ExtractBytes(array, 0, bI); ExtractBytes(array, 32, bI2); Gost3410PublicKeyAlgParameters gost3410PublicKeyAlgParameters = new Gost3410PublicKeyAlgParameters(eCPublicKeyParameters.PublicKeyParamSet, CryptoProObjectIdentifiers.GostR3411x94CryptoProParamSet); AlgorithmIdentifier algID = new AlgorithmIdentifier(CryptoProObjectIdentifiers.GostR3410x2001, gost3410PublicKeyAlgParameters.ToAsn1Object()); return(new SubjectPublicKeyInfo(algID, new DerOctetString(array))); } X962Parameters x962Parameters; if (eCPublicKeyParameters.PublicKeyParamSet == null) { ECDomainParameters parameters5 = eCPublicKeyParameters.Parameters; X9ECParameters ecParameters = new X9ECParameters(parameters5.Curve, parameters5.G, parameters5.N, parameters5.H, parameters5.GetSeed()); x962Parameters = new X962Parameters(ecParameters); } else { x962Parameters = new X962Parameters(eCPublicKeyParameters.PublicKeyParamSet); } Asn1OctetString asn1OctetString = (Asn1OctetString) new X9ECPoint(eCPublicKeyParameters.Q).ToAsn1Object(); AlgorithmIdentifier algID2 = new AlgorithmIdentifier(X9ObjectIdentifiers.IdECPublicKey, x962Parameters.ToAsn1Object()); return(new SubjectPublicKeyInfo(algID2, asn1OctetString.GetOctets())); } if (key is Gost3410PublicKeyParameters) { Gost3410PublicKeyParameters gost3410PublicKeyParameters = (Gost3410PublicKeyParameters)key; if (gost3410PublicKeyParameters.PublicKeyParamSet == null) { throw Platform.CreateNotImplementedException("Not a CryptoPro parameter set"); } byte[] array2 = gost3410PublicKeyParameters.Y.ToByteArrayUnsigned(); byte[] array3 = new byte[array2.Length]; for (int i = 0; i != array3.Length; i++) { array3[i] = array2[array2.Length - 1 - i]; } Gost3410PublicKeyAlgParameters gost3410PublicKeyAlgParameters2 = new Gost3410PublicKeyAlgParameters(gost3410PublicKeyParameters.PublicKeyParamSet, CryptoProObjectIdentifiers.GostR3411x94CryptoProParamSet); AlgorithmIdentifier algID3 = new AlgorithmIdentifier(CryptoProObjectIdentifiers.GostR3410x94, gost3410PublicKeyAlgParameters2.ToAsn1Object()); return(new SubjectPublicKeyInfo(algID3, new DerOctetString(array3))); } throw new ArgumentException("Class provided no convertible: " + Platform.GetTypeName(key)); }
public void TestAlgorithms() { // // RSA parameters // BigInteger rsaMod = new BigInteger("a7295693155b1813bb84877fb45343556e0568043de5910872a3a518cc11e23e2db74eaf4545068c4e3d258a2718fbacdcc3eafa457695b957e88fbf110aed049a992d9c430232d02f3529c67a3419935ea9b569f85b1bcd37de6b899cd62697e843130ff0529d09c97d813cb15f293751ff56f943fbdabb63971cc7f4f6d5bff1594416b1f5907bde5a84a44f9802ef29b43bda1960f948f8afb8766c1ab80d32eec88ed66d0b65aebe44a6d0b3c5e0ab051aaa1b912fbcc17b8e751ddecc5365b6db6dab0020c3057db4013a51213a5798a3aab67985b0f4d88627a54a0f3f0285fbcb4afdfeb65cb153af66825656d43238b75503231500753f4e421e3c57", 16); BigInteger rsaPubExp = new BigInteger("10001", 16); BigInteger rsaPrivExp = new BigInteger("65dad56ac7df7abb434e4cb5eeadb16093aa6da7f0033aad3815289b04757d32bfee6ade7749c8e4a323b5050a2fb9e2a99e23469e1ed4ba5bab54336af20a5bfccb8b3424cc6923db2ffca5787ed87aa87aa614cd04cedaebc8f623a2d2063017910f436dff18bb06f01758610787f8b258f0a8efd8bd7de30007c47b2a1031696c7d6523bc191d4d918927a7e0b09584ed205bd2ff4fc4382678df82353f7532b3bbb81d69e3f39070aed3fb64fce032a089e8e64955afa5213a6eb241231bd98d702fba725a9b205952fda186412d9e0d9344d2998c455ad8c2bae85ee672751466d5288304032b5b7e02f7e558c7af82c7fbf58eea0bb4ef0f001e6cd0a9", 16); BigInteger rsaPrivP = new BigInteger("d4fd9ac3474fb83aaf832470643609659e511b322632b239b688f3cd2aad87527d6cf652fb9c9ca67940e84789444f2e99b0cb0cfabbd4de95396106c865f38e2fb7b82b231260a94df0e01756bf73ce0386868d9c41645560a81af2f53c18e4f7cdf3d51d80267372e6e0216afbf67f655c9450769cca494e4f6631b239ce1b", 16); BigInteger rsaPrivQ = new BigInteger("c8eaa0e2a1b3a4412a702bccda93f4d150da60d736c99c7c566fdea4dd1b401cbc0d8c063daaf0b579953d36343aa18b33dbf8b9eae94452490cc905245f8f7b9e29b1a288bc66731a29e1dd1a45c9fd7f8238ff727adc49fff73991d0dc096206b9d3a08f61e7462e2b804d78cb8c5eccdb9b7fbd2ad6a8fea46c1053e1be75", 16); BigInteger rsaPrivDP = new BigInteger("10edcb544421c0f9e123624d1099feeb35c72a8b34e008ac6fa6b90210a7543f293af4e5299c8c12eb464e70092805c7256e18e5823455ba0f504d36f5ccacac1b7cd5c58ff710f9c3f92646949d88fdd1e7ea5fed1081820bb9b0d2a8cd4b093fecfdb96dabd6e28c3a6f8c186dc86cddc89afd3e403e0fcf8a9e0bcb27af0b", 16); BigInteger rsaPrivDQ = new BigInteger("97fc25484b5a415eaa63c03e6efa8dafe9a1c8b004d9ee6e80548fefd6f2ce44ee5cb117e77e70285798f57d137566ce8ea4503b13e0f1b5ed5ca6942537c4aa96b2a395782a4cb5b58d0936e0b0fa63b1192954d39ced176d71ef32c6f42c84e2e19f9d4dd999c2151b032b97bd22aa73fd8c5bcd15a2dca4046d5acc997021", 16); BigInteger rsaPrivQinv = new BigInteger("4bb8064e1eff7e9efc3c4578fcedb59ca4aef0993a8312dfdcb1b3decf458aa6650d3d0866f143cbf0d3825e9381181170a0a1651eefcd7def786b8eb356555d9fa07c85b5f5cbdd74382f1129b5e36b4166b6cc9157923699708648212c484958351fdc9cf14f218dbe7fbf7cbd93a209a4681fe23ceb44bab67d66f45d1c9d", 16); RsaKeyParameters rsaPublic = new RsaKeyParameters(false, rsaMod, rsaPubExp); RsaPrivateCrtKeyParameters rsaPrivate = new RsaPrivateCrtKeyParameters( rsaMod, rsaPubExp, rsaPrivExp, rsaPrivP, rsaPrivQ, rsaPrivDP, rsaPrivDQ, rsaPrivQinv); // // ECDSA parameters // BigInteger ECParraGX = new BigInteger(Base64.Decode("D/qWPNyogWzMM7hkK+35BcPTWFc9Pyf7vTs8uaqv")); BigInteger ECParraGY = new BigInteger(Base64.Decode("AhQXGxb1olGRv6s1LPRfuatMF+cx3ZTGgzSE/Q5R")); BigInteger ECParraH = new BigInteger(Base64.Decode("AQ==")); BigInteger ECParraN = new BigInteger(Base64.Decode("f///////////////f///nl6an12QcfvRUiaIkJ0L")); BigInteger ECPubQX = new BigInteger(Base64.Decode("HWWi17Yb+Bm3PYr/DMjLOYNFhyOwX1QY7ZvqqM+l")); BigInteger ECPubQY = new BigInteger(Base64.Decode("JrlJfxu3WGhqwtL/55BOs/wsUeiDFsvXcGhB8DGx")); BigInteger ECPrivD = new BigInteger(Base64.Decode("GYQmd/NF1B+He1iMkWt3by2Az6Eu07t0ynJ4YCAo")); FpCurve curve = new FpCurve( new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b ECDomainParameters ecDomain = new ECDomainParameters(curve, new FpPoint(curve, curve.FromBigInteger(ECParraGX), curve.FromBigInteger(ECParraGY)), ECParraN); ECPublicKeyParameters ecPub = new ECPublicKeyParameters( new FpPoint(curve, curve.FromBigInteger(ECPubQX), curve.FromBigInteger(ECPubQY)), ecDomain); ECPrivateKeyParameters ecPriv = new ECPrivateKeyParameters(ECPrivD, ecDomain); // // DSA parameters // BigInteger DSAParaG = new BigInteger(Base64.Decode("AL0fxOTq10OHFbCf8YldyGembqEu08EDVzxyLL29Zn/t4It661YNol1rnhPIs+cirw+yf9zeCe+KL1IbZ/qIMZM=")); BigInteger DSAParaP = new BigInteger(Base64.Decode("AM2b/UeQA+ovv3dL05wlDHEKJ+qhnJBsRT5OB9WuyRC830G79y0R8wuq8jyIYWCYcTn1TeqVPWqiTv6oAoiEeOs=")); BigInteger DSAParaQ = new BigInteger(Base64.Decode("AIlJT7mcKL6SUBMmvm24zX1EvjNx")); BigInteger DSAPublicY = new BigInteger(Base64.Decode("TtWy2GuT9yGBWOHi1/EpCDa/bWJCk2+yAdr56rAcqP0eHGkMnA9s9GJD2nGU8sFjNHm55swpn6JQb8q0agrCfw==")); BigInteger DsaPrivateX = new BigInteger(Base64.Decode("MMpBAxNlv7eYfxLTZ2BItJeD31A=")); DsaParameters para = new DsaParameters(DSAParaP, DSAParaQ, DSAParaG); DsaPrivateKeyParameters dsaPriv = new DsaPrivateKeyParameters(DsaPrivateX, para); DsaPublicKeyParameters dsaPub = new DsaPublicKeyParameters(DSAPublicY, para); // // ECGOST3410 parameters // IAsymmetricCipherKeyPairGenerator ecGostKpg = GeneratorUtilities.GetKeyPairGenerator("ECGOST3410"); ecGostKpg.Init( new ECKeyGenerationParameters( CryptoProObjectIdentifiers.GostR3410x2001CryptoProA, new SecureRandom())); AsymmetricCipherKeyPair ecGostPair = ecGostKpg.GenerateKeyPair(); // // GOST3410 parameters // IAsymmetricCipherKeyPairGenerator gostKpg = GeneratorUtilities.GetKeyPairGenerator("GOST3410"); gostKpg.Init( new Gost3410KeyGenerationParameters( new SecureRandom(), CryptoProObjectIdentifiers.GostR3410x94CryptoProA)); AsymmetricCipherKeyPair gostPair = gostKpg.GenerateKeyPair(); // // signer loop // byte[] shortMsg = new byte[] { 1, 4, 5, 6, 8, 8, 4, 2, 1, 3 }; byte[] longMsg = new byte[100]; new SecureRandom().NextBytes(longMsg); foreach (string algorithm in SignerUtilities.Algorithms) { ISigner signer = SignerUtilities.GetSigner(algorithm); string upper = algorithm.ToUpperInvariant(); int withPos = upper.LastIndexOf("WITH"); string cipherName = withPos < 0 ? upper : upper.Substring(withPos + "WITH".Length); ICipherParameters signParams = null, verifyParams = null; if (cipherName == "RSA" || cipherName == "RSAANDMGF1") { signParams = rsaPrivate; verifyParams = rsaPublic; } else if (cipherName == "ECDSA") { signParams = ecPriv; verifyParams = ecPub; } else if (cipherName == "DSA") { signParams = dsaPriv; verifyParams = dsaPub; } else if (cipherName == "ECGOST3410") { signParams = ecGostPair.Private; verifyParams = ecGostPair.Public; } else if (cipherName == "GOST3410") { signParams = gostPair.Private; verifyParams = gostPair.Public; } else { Assert.Fail("Unknown algorithm encountered: " + cipherName); } signer.Init(true, signParams); foreach (byte b in shortMsg) { signer.Update(b); } signer.BlockUpdate(longMsg, 0, longMsg.Length); byte[] sig = signer.GenerateSignature(); signer.Init(false, verifyParams); foreach (byte b in shortMsg) { signer.Update(b); } signer.BlockUpdate(longMsg, 0, longMsg.Length); Assert.IsTrue(signer.VerifySignature(sig), cipherName + " signer " + algorithm + " failed."); } }
public void TestCreationDSA() { BigInteger DSAParaG = new BigInteger(Base64.Decode("AL0fxOTq10OHFbCf8YldyGembqEu08EDVzxyLL29Zn/t4It661YNol1rnhPIs+cirw+yf9zeCe+KL1IbZ/qIMZM=")); BigInteger DSAParaP = new BigInteger(Base64.Decode("AM2b/UeQA+ovv3dL05wlDHEKJ+qhnJBsRT5OB9WuyRC830G79y0R8wuq8jyIYWCYcTn1TeqVPWqiTv6oAoiEeOs=")); BigInteger DSAParaQ = new BigInteger(Base64.Decode("AIlJT7mcKL6SUBMmvm24zX1EvjNx")); BigInteger DSAPublicY = new BigInteger(Base64.Decode("TtWy2GuT9yGBWOHi1/EpCDa/bWJCk2+yAdr56rAcqP0eHGkMnA9s9GJD2nGU8sFjNHm55swpn6JQb8q0agrCfw==")); BigInteger DsaPrivateX = new BigInteger(Base64.Decode("MMpBAxNlv7eYfxLTZ2BItJeD31A=")); DsaParameters para = new DsaParameters(DSAParaP, DSAParaQ, DSAParaG); DsaPrivateKeyParameters dsaPriv = new DsaPrivateKeyParameters(DsaPrivateX, para); DsaPublicKeyParameters dsaPub = new DsaPublicKeyParameters(DSAPublicY, para); IDictionary attrs = new Hashtable(); attrs[X509Name.C] = "AU"; attrs[X509Name.O] = "The Legion of the Bouncy Castle"; attrs[X509Name.L] = "Melbourne"; attrs[X509Name.ST] = "Victoria"; attrs[X509Name.E] = "*****@*****.**"; IList ord = new ArrayList(); ord.Add(X509Name.C); ord.Add(X509Name.O); ord.Add(X509Name.L); ord.Add(X509Name.ST); ord.Add(X509Name.E); IList values = new ArrayList(); values.Add("AU"); values.Add("The Legion of the Bouncy Castle"); values.Add("Melbourne"); values.Add("Victoria"); values.Add("*****@*****.**"); X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.SetSerialNumber(BigInteger.One); certGen.SetIssuerDN(new X509Name(ord, attrs)); certGen.SetNotBefore(DateTime.UtcNow.AddDays(-1)); certGen.SetNotAfter(DateTime.UtcNow.AddDays(1)); certGen.SetSubjectDN(new X509Name(ord, attrs)); certGen.SetPublicKey(dsaPub); certGen.SetSignatureAlgorithm("SHA1WITHDSA"); X509Certificate cert = certGen.Generate(dsaPriv); // Assert.IsTrue((cert.IsValidNow && cert.Verify(dsaPub)), "Certificate failed to be valid (DSA Test)"); cert.CheckValidity(); cert.Verify(dsaPub); //ISet dummySet = cert.GetNonCriticalExtensionOids(); //if (dummySet != null) //{ // foreach (string key in dummySet) // { // Console.WriteLine("\t{0}:\t{1}", key); // } //} //Console.WriteLine(); //dummySet = cert.GetNonCriticalExtensionOids(); //if (dummySet != null) //{ // foreach (string key in dummySet) // { // Console.WriteLine("\t{0}:\t{1}", key); // } //} //Console.WriteLine(); }
protected DsaKeyParameters(bool isPrivate, DsaParameters parameters) : base(isPrivate) { this.parameters = parameters; }
public static SshKey CreateKey(SshVersion version, PublicKeyAlgorithm algorithm, string comment = "") { if (version == SshVersion.SSH1 && algorithm != PublicKeyAlgorithm.SSH_RSA) { throw new Exception("unsupported version/algorithm combination"); } switch (algorithm) { case PublicKeyAlgorithm.SSH_RSA: case PublicKeyAlgorithm.SSH_RSA_CERT_V1: KeyGenerationParameters keyGenParam = new KeyGenerationParameters(secureRandom, 512); var rsaKeyPairGen = new RsaKeyPairGenerator(); rsaKeyPairGen.Init(keyGenParam); var keyPair = rsaKeyPairGen.GenerateKeyPair(); var rsaKey = new SshKey(version, keyPair, comment); return(rsaKey); case PublicKeyAlgorithm.SSH_DSS: case PublicKeyAlgorithm.SSH_DSS_CERT_V1: DsaParametersGenerator dsaParamGen = new DsaParametersGenerator(); dsaParamGen.Init(512, 10, secureRandom); DsaParameters dsaParam = dsaParamGen.GenerateParameters(); DsaKeyGenerationParameters dsaKeyGenParam = new DsaKeyGenerationParameters(secureRandom, dsaParam); DsaKeyPairGenerator dsaKeyPairGen = new DsaKeyPairGenerator(); dsaKeyPairGen.Init(dsaKeyGenParam); keyPair = dsaKeyPairGen.GenerateKeyPair(); var dsaKey = new SshKey(SshVersion.SSH2, keyPair); dsaKey.Comment = comment; return(dsaKey); case PublicKeyAlgorithm.ECDSA_SHA2_NISTP256: case PublicKeyAlgorithm.ECDSA_SHA2_NISTP256_CERT_V1: X9ECParameters ecdsa256X9Params = SecNamedCurves.GetByName("secp256r1"); ECDomainParameters ecdsa256DomainParams = new ECDomainParameters(ecdsa256X9Params.Curve, ecdsa256X9Params.G, ecdsa256X9Params.N, ecdsa256X9Params.H); ECKeyGenerationParameters ecdsa256GenParams = new ECKeyGenerationParameters(ecdsa256DomainParams, secureRandom); ECKeyPairGenerator ecdsa256Gen = new ECKeyPairGenerator(); ecdsa256Gen.Init(ecdsa256GenParams); keyPair = ecdsa256Gen.GenerateKeyPair(); var ecdsa256Key = new SshKey(SshVersion.SSH2, keyPair); ecdsa256Key.Comment = comment; return(ecdsa256Key); case PublicKeyAlgorithm.ECDSA_SHA2_NISTP384: case PublicKeyAlgorithm.ECDSA_SHA2_NISTP384_CERT_V1: X9ECParameters ecdsa384X9Params = SecNamedCurves.GetByName("secp384r1"); ECDomainParameters ecdsa384DomainParams = new ECDomainParameters(ecdsa384X9Params.Curve, ecdsa384X9Params.G, ecdsa384X9Params.N, ecdsa384X9Params.H); ECKeyGenerationParameters ecdsa384GenParams = new ECKeyGenerationParameters(ecdsa384DomainParams, secureRandom); ECKeyPairGenerator ecdsa384Gen = new ECKeyPairGenerator(); ecdsa384Gen.Init(ecdsa384GenParams); keyPair = ecdsa384Gen.GenerateKeyPair(); var ecdsa384Key = new SshKey(SshVersion.SSH2, keyPair); ecdsa384Key.Comment = comment; return(ecdsa384Key); case PublicKeyAlgorithm.ECDSA_SHA2_NISTP521: case PublicKeyAlgorithm.ECDSA_SHA2_NISTP521_CERT_V1: X9ECParameters ecdsa521X9Params = SecNamedCurves.GetByName("secp521r1"); ECDomainParameters ecdsa521DomainParams = new ECDomainParameters(ecdsa521X9Params.Curve, ecdsa521X9Params.G, ecdsa521X9Params.N, ecdsa521X9Params.H); ECKeyGenerationParameters ecdsa521GenParams = new ECKeyGenerationParameters(ecdsa521DomainParams, secureRandom); ECKeyPairGenerator ecdsa521Gen = new ECKeyPairGenerator(); ecdsa521Gen.Init(ecdsa521GenParams); keyPair = ecdsa521Gen.GenerateKeyPair(); var ecdsa521Key = new SshKey(SshVersion.SSH2, keyPair); ecdsa521Key.Comment = comment; return(ecdsa521Key); case PublicKeyAlgorithm.ED25519: case PublicKeyAlgorithm.ED25519_CERT_V1: var privateKeySeed = secureRandom.GenerateSeed(Ed25519.PrivateKeySeedSizeInBytes); var publicKeyBytes = new byte[Ed25519.PublicKeySizeInBytes]; var privateKeyBytes = new byte[Ed25519.ExpandedPrivateKeySizeInBytes]; Ed25519.KeyPairFromSeed(out publicKeyBytes, out privateKeyBytes, privateKeySeed); var publicKey = new Ed25519PublicKeyParameter(publicKeyBytes); var privateKey = new Ed25519PrivateKeyParameter(privateKeyBytes); var ed25519Key = new SshKey(SshVersion.SSH2, publicKey, privateKey, comment); return(ed25519Key); default: throw new Exception("unsupported algorithm"); } }
public void TestDsa2Parameters() { byte[] seed = Hex.Decode("4783081972865EA95D43318AB2EAF9C61A2FC7BBF1B772A09017BDF5A58F4FF0"); //AlgorithmParameterGenerator a = AlgorithmParameterGenerator.getInstance("DSA", "BC"); //a.init(2048, new DSATestSecureRandom(seed)); DsaParametersGenerator a = new DsaParametersGenerator(new Sha256Digest()); a.Init(new DsaParameterGenerationParameters(2048, 256, 80, new DsaTestSecureRandom(seed))); //AlgorithmParameters parameters = a.generateParameters(); //DSAParameterSpec dsaP = (DSAParameterSpec)parameters.getParameterSpec(DSAParameterSpec.class); DsaParameters dsaP = a.GenerateParameters(); if (!dsaP.Q.Equals(new BigInteger("C24ED361870B61E0D367F008F99F8A1F75525889C89DB1B673C45AF5867CB467", 16))) { Fail("Q incorrect"); } if (!dsaP.P.Equals(new BigInteger( "F56C2A7D366E3EBDEAA1891FD2A0D099" + "436438A673FED4D75F594959CFFEBCA7BE0FC72E4FE67D91" + "D801CBA0693AC4ED9E411B41D19E2FD1699C4390AD27D94C" + "69C0B143F1DC88932CFE2310C886412047BD9B1C7A67F8A2" + "5909132627F51A0C866877E672E555342BDF9355347DBD43" + "B47156B2C20BAD9D2B071BC2FDCF9757F75C168C5D9FC431" + "31BE162A0756D1BDEC2CA0EB0E3B018A8B38D3EF2487782A" + "EB9FBF99D8B30499C55E4F61E5C7DCEE2A2BB55BD7F75FCD" + "F00E48F2E8356BDB59D86114028F67B8E07B127744778AFF" + "1CF1399A4D679D92FDE7D941C5C85C5D7BFF91BA69F9489D" + "531D1EBFA727CFDA651390F8021719FA9F7216CEB177BD75", 16))) { Fail("P incorrect"); } if (!dsaP.G.Equals(new BigInteger( "8DC6CC814CAE4A1C05A3E186A6FE27EA" + "BA8CDB133FDCE14A963A92E809790CBA096EAA26140550C1" + "29FA2B98C16E84236AA33BF919CD6F587E048C52666576DB" + "6E925C6CBE9B9EC5C16020F9A44C9F1C8F7A8E611C1F6EC2" + "513EA6AA0B8D0F72FED73CA37DF240DB57BBB27431D61869" + "7B9E771B0B301D5DF05955425061A30DC6D33BB6D2A32BD0" + "A75A0A71D2184F506372ABF84A56AEEEA8EB693BF29A6403" + "45FA1298A16E85421B2208D00068A5A42915F82CF0B858C8" + "FA39D43D704B6927E0B2F916304E86FB6A1B487F07D8139E" + "428BB096C6D67A76EC0B8D4EF274B8A2CF556D279AD267CC" + "EF5AF477AFED029F485B5597739F5D0240F67C2D948A6279", 16))) { Fail("G incorrect"); } //KeyPairGenerator g = KeyPairGenerator.getInstance("DSA", "BC"); IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("DSA"); //g.initialize(dsaP, FixedSecureRandom.From(Hex.Decode("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C"))); g.Init(new DsaKeyGenerationParameters(FixedSecureRandom.From(Hex.Decode("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C")), dsaP)); //KeyPair p = g.generateKeyPair(); AsymmetricCipherKeyPair p = g.GenerateKeyPair(); //DSAPrivateKey sKey = (DSAPrivateKey)p.getPrivate(); //DSAPublicKey vKey = (DSAPublicKey)p.getPublic(); DsaPrivateKeyParameters sKey = (DsaPrivateKeyParameters)p.Private; DsaPublicKeyParameters vKey = (DsaPublicKeyParameters)p.Public; if (!vKey.Y.Equals(new BigInteger( "2828003D7C747199143C370FDD07A286" + "1524514ACC57F63F80C38C2087C6B795B62DE1C224BF8D1D" + "1424E60CE3F5AE3F76C754A2464AF292286D873A7A30B7EA" + "CBBC75AAFDE7191D9157598CDB0B60E0C5AA3F6EBE425500" + "C611957DBF5ED35490714A42811FDCDEB19AF2AB30BEADFF" + "2907931CEE7F3B55532CFFAEB371F84F01347630EB227A41" + "9B1F3F558BC8A509D64A765D8987D493B007C4412C297CAF" + "41566E26FAEE475137EC781A0DC088A26C8804A98C23140E" + "7C936281864B99571EE95C416AA38CEEBB41FDBFF1EB1D1D" + "C97B63CE1355257627C8B0FD840DDB20ED35BE92F08C49AE" + "A5613957D7E5C7A6D5A5834B4CB069E0831753ECF65BA02B", 16))) { Fail("Y value incorrect"); } if (!sKey.X.Equals( new BigInteger("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C", 16))) { Fail("X value incorrect"); } //byte[] encodeParams = parameters.getEncoded(); byte[] encodeParams = new DsaParameter(dsaP.P, dsaP.Q, dsaP.G).GetDerEncoded(); //AlgorithmParameters a2 = AlgorithmParameters.getInstance("DSA", "BC"); //a2.init(encodeParams); DsaParameter dsaP2 = DsaParameter.GetInstance(Asn1Object.FromByteArray(encodeParams)); DsaParameters p2 = new DsaParameters(dsaP.P, dsaP.Q, dsaP.G); // a and a2 should be equivalent! //byte[] encodeParams_2 = a2.GetEncoded(); byte[] encodeParams_2 = new DsaParameter(p2.P, p2.Q, p2.G).GetDerEncoded(); if (!AreEqual(encodeParams, encodeParams_2)) { Fail("encode/decode parameters failed"); } ISigner s = SignerUtilities.GetSigner("DSA"); byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; s.Init(true, sKey); s.BlockUpdate(data, 0, data.Length); byte[] sigBytes = s.GenerateSignature(); s = SignerUtilities.GetSigner("DSA"); s.Init(false, vKey); s.BlockUpdate(data, 0, data.Length); if (!s.VerifySignature(sigBytes)) { Fail("DSA verification failed"); } }
private void Dsa2Test2() { byte[] seed = Hex.Decode("5AFCC1EFFC079A9CCA6ECA86D6E3CC3B18642D9BE1CC6207C84002A9"); DsaParametersGenerator pGen = new DsaParametersGenerator(new Sha224Digest()); pGen.Init(new DsaParameterGenerationParameters(2048, 224, 80, new DsaTestSecureRandom(seed))); DsaParameters parameters = pGen.GenerateParameters(); DsaValidationParameters pv = parameters.ValidationParameters; if (pv.Counter != 21) { Fail("counter incorrect"); } if (!AreEqual(seed, pv.GetSeed())) { Fail("seed incorrect"); } if (!parameters.Q.Equals(new BigInteger("90EAF4D1AF0708B1B612FF35E0A2997EB9E9D263C9CE659528945C0D", 16))) { Fail("Q incorrect"); } if (!parameters.P.Equals(new BigInteger( "C196BA05AC29E1F9C3C72D56DFFC6154" + "A033F1477AC88EC37F09BE6C5BB95F51C296DD20D1A28A06" + "7CCC4D4316A4BD1DCA55ED1066D438C35AEBAABF57E7DAE4" + "28782A95ECA1C143DB701FD48533A3C18F0FE23557EA7AE6" + "19ECACC7E0B51652A8776D02A425567DED36EABD90CA33A1" + "E8D988F0BBB92D02D1D20290113BB562CE1FC856EEB7CDD9" + "2D33EEA6F410859B179E7E789A8F75F645FAE2E136D252BF" + "FAFF89528945C1ABE705A38DBC2D364AADE99BE0D0AAD82E" + "5320121496DC65B3930E38047294FF877831A16D5228418D" + "E8AB275D7D75651CEFED65F78AFC3EA7FE4D79B35F62A040" + "2A1117599ADAC7B269A59F353CF450E6982D3B1702D9CA83", 16))) { Fail("P incorrect"); } if (!parameters.G.Equals(new BigInteger( "A59A749A11242C58C894E9E5A91804E8" + "FA0AC64B56288F8D47D51B1EDC4D65444FECA0111D78F35F" + "C9FDD4CB1F1B79A3BA9CBEE83A3F811012503C8117F98E50" + "48B089E387AF6949BF8784EBD9EF45876F2E6A5A495BE64B" + "6E770409494B7FEE1DBB1E4B2BC2A53D4F893D418B715959" + "2E4FFFDF6969E91D770DAEBD0B5CB14C00AD68EC7DC1E574" + "5EA55C706C4A1C5C88964E34D09DEB753AD418C1AD0F4FDF" + "D049A955E5D78491C0B7A2F1575A008CCD727AB376DB6E69" + "5515B05BD412F5B8C2F4C77EE10DA48ABD53F5DD498927EE" + "7B692BBBCDA2FB23A516C5B4533D73980B2A3B60E384ED20" + "0AE21B40D273651AD6060C13D97FD69AA13C5611A51B9085", 16))) { Fail("G incorrect"); } DsaKeyPairGenerator kpGen = new DsaKeyPairGenerator(); kpGen.Init(new DsaKeyGenerationParameters( FixedSecureRandom.From(Hex.Decode("00D0F09ED3E2568F6CADF9224117DA2AEC5A4300E009DE1366023E17")), parameters)); AsymmetricCipherKeyPair kp = kpGen.GenerateKeyPair(); DsaPublicKeyParameters pub = (DsaPublicKeyParameters)kp.Public; DsaPrivateKeyParameters priv = (DsaPrivateKeyParameters)kp.Private; if (!pub.Y.Equals(new BigInteger( "70035C9A3B225B258F16741F3941FBF0" + "6F3D056CD7BD864604CBB5EE9DD85304EE8E8E4ABD5E9032" + "11DDF25CE149075510ACE166970AFDC7DF552B7244F342FA" + "02F7A621405B754909D757F97290E1FE5036E904CF593446" + "0C046D95659821E1597ED9F2B1F0E20863A6BBD0CE74DACB" + "A5D8C68A90B29C2157CDEDB82EC12B81EE3068F9BF5F7F34" + "6ECA41ED174CCCD7D154FA4F42F80FFE1BF46AE9D8125DEB" + "5B4BA08A72BDD86596DBEDDC9550FDD650C58F5AE5133509" + "A702F79A31ECB490F7A3C5581631F7C5BE4FF7F9E9F27FA3" + "90E47347AD1183509FED6FCF198BA9A71AB3335B4F38BE8D" + "15496A00B6DC2263E20A5F6B662320A3A1EC033AA61E3B68", 16))) { Fail("Y value incorrect"); } if (!priv.X.Equals( new BigInteger("00D0F09ED3E2568F6CADF9224117DA2AEC5A4300E009DE1366023E17", 16))) { Fail("X value incorrect"); } DsaSigner signer = new DsaSigner(); signer.Init(true, new ParametersWithRandom(kp.Private, FixedSecureRandom.From(Hex.Decode("735959CC4463B8B440E407EECA8A473BF6A6D1FE657546F67D401F05")))); byte[] msg = Hex.Decode("23097D223405D8228642A477BDA255B32AADBCE4BDA0B3F7E36C9DA7"); BigInteger[] sig = signer.GenerateSignature(msg); if (!sig[0].Equals(new BigInteger("4400138D05F9639CAF54A583CAAF25D2B76D0C3EAD752CE17DBC85FE", 16))) { Fail("R value incorrect"); } if (!sig[1].Equals(new BigInteger("874D4F12CB13B61732D398445698CFA9D92381D938AA57EE2C9327B3", 16))) { Fail("S value incorrect"); } signer.Init(false, kp.Public); if (!signer.VerifySignature(msg, sig[0], sig[1])) { Fail("signature not verified"); } }
/// <summary> /// Create a Subject Public Key Info object for a given public key. /// </summary> /// <param name="publicKey">One of ElGammalPublicKeyParameters, DSAPublicKeyParameter, DHPublicKeyParameters, RsaKeyParameters or ECPublicKeyParameters</param> /// <returns>A subject public key info object.</returns> /// <exception cref="Exception">Throw exception if object provided is not one of the above.</exception> public static SubjectPublicKeyInfo CreateSubjectPublicKeyInfo( AsymmetricKeyParameter publicKey) { if (publicKey == null) { throw new ArgumentNullException("publicKey"); } if (publicKey.IsPrivate) { throw new ArgumentException("Private key passed - public key expected.", "publicKey"); } if (publicKey is ElGamalPublicKeyParameters) { ElGamalPublicKeyParameters _key = (ElGamalPublicKeyParameters)publicKey; ElGamalParameters kp = _key.Parameters; SubjectPublicKeyInfo info = new SubjectPublicKeyInfo( new AlgorithmIdentifier( OiwObjectIdentifiers.ElGamalAlgorithm, new ElGamalParameter(kp.P, kp.G).ToAsn1Object()), new DerInteger(_key.Y)); return(info); } if (publicKey is DsaPublicKeyParameters) { DsaPublicKeyParameters _key = (DsaPublicKeyParameters)publicKey; DsaParameters kp = _key.Parameters; Asn1Encodable ae = kp == null ? null : new DsaParameter(kp.P, kp.Q, kp.G).ToAsn1Object(); return(new SubjectPublicKeyInfo( new AlgorithmIdentifier(X9ObjectIdentifiers.IdDsa, ae), new DerInteger(_key.Y))); } if (publicKey is DHPublicKeyParameters) { DHPublicKeyParameters _key = (DHPublicKeyParameters)publicKey; DHParameters kp = _key.Parameters; SubjectPublicKeyInfo info = new SubjectPublicKeyInfo( new AlgorithmIdentifier( _key.AlgorithmOid, new DHParameter(kp.P, kp.G, kp.L).ToAsn1Object()), new DerInteger(_key.Y)); return(info); } // End of DH if (publicKey is RsaKeyParameters) { RsaKeyParameters _key = (RsaKeyParameters)publicKey; SubjectPublicKeyInfo info = new SubjectPublicKeyInfo( new AlgorithmIdentifier(PkcsObjectIdentifiers.RsaEncryption, DerNull.Instance), new RsaPublicKeyStructure(_key.Modulus, _key.Exponent).ToAsn1Object()); return(info); } // End of RSA. if (publicKey is ECPublicKeyParameters) { ECPublicKeyParameters _key = (ECPublicKeyParameters)publicKey; if (_key.Parameters is ECGost3410Parameters) { ECGost3410Parameters gostParams = (ECGost3410Parameters)_key.Parameters; BigInteger bX = _key.Q.AffineXCoord.ToBigInteger(); BigInteger bY = _key.Q.AffineYCoord.ToBigInteger(); bool is512 = (bX.BitLength > 256); Gost3410PublicKeyAlgParameters parameters = new Gost3410PublicKeyAlgParameters( gostParams.PublicKeyParamSet, gostParams.DigestParamSet, gostParams.EncryptionParamSet); int encKeySize; int offset; DerObjectIdentifier algIdentifier; if (is512) { encKeySize = 128; offset = 64; algIdentifier = RosstandartObjectIdentifiers.id_tc26_gost_3410_12_512; } else { encKeySize = 64; offset = 32; algIdentifier = RosstandartObjectIdentifiers.id_tc26_gost_3410_12_256; } byte[] encKey = new byte[encKeySize]; ExtractBytes(encKey, encKeySize / 2, 0, bX); ExtractBytes(encKey, encKeySize / 2, offset, bY); return(new SubjectPublicKeyInfo(new AlgorithmIdentifier(algIdentifier, parameters), new DerOctetString(encKey))); } // End of ECGOST3410_2012 if (_key.AlgorithmName == "ECGOST3410") { if (_key.PublicKeyParamSet == null) { throw BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateNotImplementedException("Not a CryptoPro parameter set"); } ECPoint q = _key.Q.Normalize(); BigInteger bX = q.AffineXCoord.ToBigInteger(); BigInteger bY = q.AffineYCoord.ToBigInteger(); byte[] encKey = new byte[64]; ExtractBytes(encKey, 0, bX); ExtractBytes(encKey, 32, bY); Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters( _key.PublicKeyParamSet, CryptoProObjectIdentifiers.GostR3411x94CryptoProParamSet); AlgorithmIdentifier algID = new AlgorithmIdentifier( CryptoProObjectIdentifiers.GostR3410x2001, gostParams.ToAsn1Object()); return(new SubjectPublicKeyInfo(algID, new DerOctetString(encKey))); } else { X962Parameters x962; if (_key.PublicKeyParamSet == null) { ECDomainParameters kp = _key.Parameters; X9ECParameters ecP = new X9ECParameters(kp.Curve, kp.G, kp.N, kp.H, kp.GetSeed()); x962 = new X962Parameters(ecP); } else { x962 = new X962Parameters(_key.PublicKeyParamSet); } byte[] pubKey = _key.Q.GetEncoded(false); AlgorithmIdentifier algID = new AlgorithmIdentifier( X9ObjectIdentifiers.IdECPublicKey, x962.ToAsn1Object()); return(new SubjectPublicKeyInfo(algID, pubKey)); } } // End of EC if (publicKey is Gost3410PublicKeyParameters) { Gost3410PublicKeyParameters _key = (Gost3410PublicKeyParameters)publicKey; if (_key.PublicKeyParamSet == null) { throw BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateNotImplementedException("Not a CryptoPro parameter set"); } byte[] keyEnc = _key.Y.ToByteArrayUnsigned(); byte[] 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); AlgorithmIdentifier algID = new AlgorithmIdentifier( CryptoProObjectIdentifiers.GostR3410x94, algParams.ToAsn1Object()); return(new SubjectPublicKeyInfo(algID, new DerOctetString(keyBytes))); } if (publicKey is X448PublicKeyParameters) { X448PublicKeyParameters key = (X448PublicKeyParameters)publicKey; return(new SubjectPublicKeyInfo(new AlgorithmIdentifier(EdECObjectIdentifiers.id_X448), key.GetEncoded())); } if (publicKey is X25519PublicKeyParameters) { X25519PublicKeyParameters key = (X25519PublicKeyParameters)publicKey; return(new SubjectPublicKeyInfo(new AlgorithmIdentifier(EdECObjectIdentifiers.id_X25519), key.GetEncoded())); } if (publicKey is Ed448PublicKeyParameters) { Ed448PublicKeyParameters key = (Ed448PublicKeyParameters)publicKey; return(new SubjectPublicKeyInfo(new AlgorithmIdentifier(EdECObjectIdentifiers.id_Ed448), key.GetEncoded())); } if (publicKey is Ed25519PublicKeyParameters) { Ed25519PublicKeyParameters key = (Ed25519PublicKeyParameters)publicKey; return(new SubjectPublicKeyInfo(new AlgorithmIdentifier(EdECObjectIdentifiers.id_Ed25519), key.GetEncoded())); } throw new ArgumentException("Class provided no convertible: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(publicKey)); }
private void Dsa2Test3() { byte[] seed = Hex.Decode("4783081972865EA95D43318AB2EAF9C61A2FC7BBF1B772A09017BDF5A58F4FF0"); DsaParametersGenerator pGen = new DsaParametersGenerator(new Sha256Digest()); pGen.Init(new DsaParameterGenerationParameters(2048, 256, 80, new DsaTestSecureRandom(seed))); DsaParameters parameters = pGen.GenerateParameters(); DsaValidationParameters pv = parameters.ValidationParameters; if (pv.Counter != 12) { Fail("counter incorrect"); } if (!AreEqual(seed, pv.GetSeed())) { Fail("seed incorrect"); } if (!parameters.Q.Equals(new BigInteger("C24ED361870B61E0D367F008F99F8A1F75525889C89DB1B673C45AF5867CB467", 16))) { Fail("Q incorrect"); } if (!parameters.P.Equals(new BigInteger( "F56C2A7D366E3EBDEAA1891FD2A0D099" + "436438A673FED4D75F594959CFFEBCA7BE0FC72E4FE67D91" + "D801CBA0693AC4ED9E411B41D19E2FD1699C4390AD27D94C" + "69C0B143F1DC88932CFE2310C886412047BD9B1C7A67F8A2" + "5909132627F51A0C866877E672E555342BDF9355347DBD43" + "B47156B2C20BAD9D2B071BC2FDCF9757F75C168C5D9FC431" + "31BE162A0756D1BDEC2CA0EB0E3B018A8B38D3EF2487782A" + "EB9FBF99D8B30499C55E4F61E5C7DCEE2A2BB55BD7F75FCD" + "F00E48F2E8356BDB59D86114028F67B8E07B127744778AFF" + "1CF1399A4D679D92FDE7D941C5C85C5D7BFF91BA69F9489D" + "531D1EBFA727CFDA651390F8021719FA9F7216CEB177BD75", 16))) { Fail("P incorrect"); } if (!parameters.G.Equals(new BigInteger( "8DC6CC814CAE4A1C05A3E186A6FE27EA" + "BA8CDB133FDCE14A963A92E809790CBA096EAA26140550C1" + "29FA2B98C16E84236AA33BF919CD6F587E048C52666576DB" + "6E925C6CBE9B9EC5C16020F9A44C9F1C8F7A8E611C1F6EC2" + "513EA6AA0B8D0F72FED73CA37DF240DB57BBB27431D61869" + "7B9E771B0B301D5DF05955425061A30DC6D33BB6D2A32BD0" + "A75A0A71D2184F506372ABF84A56AEEEA8EB693BF29A6403" + "45FA1298A16E85421B2208D00068A5A42915F82CF0B858C8" + "FA39D43D704B6927E0B2F916304E86FB6A1B487F07D8139E" + "428BB096C6D67A76EC0B8D4EF274B8A2CF556D279AD267CC" + "EF5AF477AFED029F485B5597739F5D0240F67C2D948A6279", 16))) { Fail("G incorrect"); } DsaKeyPairGenerator kpGen = new DsaKeyPairGenerator(); kpGen.Init(new DsaKeyGenerationParameters( FixedSecureRandom.From(Hex.Decode("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C")), parameters)); AsymmetricCipherKeyPair kp = kpGen.GenerateKeyPair(); DsaPublicKeyParameters pub = (DsaPublicKeyParameters)kp.Public; DsaPrivateKeyParameters priv = (DsaPrivateKeyParameters)kp.Private; if (!pub.Y.Equals(new BigInteger( "2828003D7C747199143C370FDD07A286" + "1524514ACC57F63F80C38C2087C6B795B62DE1C224BF8D1D" + "1424E60CE3F5AE3F76C754A2464AF292286D873A7A30B7EA" + "CBBC75AAFDE7191D9157598CDB0B60E0C5AA3F6EBE425500" + "C611957DBF5ED35490714A42811FDCDEB19AF2AB30BEADFF" + "2907931CEE7F3B55532CFFAEB371F84F01347630EB227A41" + "9B1F3F558BC8A509D64A765D8987D493B007C4412C297CAF" + "41566E26FAEE475137EC781A0DC088A26C8804A98C23140E" + "7C936281864B99571EE95C416AA38CEEBB41FDBFF1EB1D1D" + "C97B63CE1355257627C8B0FD840DDB20ED35BE92F08C49AE" + "A5613957D7E5C7A6D5A5834B4CB069E0831753ECF65BA02B", 16))) { Fail("Y value incorrect"); } if (!priv.X.Equals( new BigInteger("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C", 16))) { Fail("X value incorrect"); } DsaSigner signer = new DsaSigner(); signer.Init(true, new ParametersWithRandom(kp.Private, FixedSecureRandom.From(Hex.Decode("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C")))); byte[] msg = Hex.Decode("BA7816BF8F01CFEA414140DE5DAE2223B00361A396177A9CB410FF61F20015AD"); BigInteger[] sig = signer.GenerateSignature(msg); if (!sig[0].Equals(new BigInteger("315C875DCD4850E948B8AC42824E9483A32D5BA5ABE0681B9B9448D444F2BE3C", 16))) { Fail("R value incorrect"); } if (!sig[1].Equals(new BigInteger("89718D12E54A8D9ED066E4A55F7ED5A2229CD23B9A3CEE78F83ED6AA61F6BCB9", 16))) { Fail("S value incorrect"); } signer.Init(false, kp.Public); if (!signer.VerifySignature(msg, sig[0], sig[1])) { Fail("signature not verified"); } }
/** * 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 { AsymmetricKeyParameter 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()); } }
private void Dsa2Test4() { byte[] seed = Hex.Decode("193AFCA7C1E77B3C1ECC618C81322E47B8B8B997C9C83515C59CC446C2D9BD47"); DsaParametersGenerator pGen = new DsaParametersGenerator(new Sha256Digest()); pGen.Init(new DsaParameterGenerationParameters(3072, 256, 80, new DsaTestSecureRandom(seed))); DsaParameters parameters = pGen.GenerateParameters(); DsaValidationParameters pv = parameters.ValidationParameters; if (pv.Counter != 20) { Fail("counter incorrect"); } if (!AreEqual(seed, pv.GetSeed())) { Fail("seed incorrect"); } if (!parameters.Q.Equals(new BigInteger("CFA0478A54717B08CE64805B76E5B14249A77A4838469DF7F7DC987EFCCFB11D", 16))) { Fail("Q incorrect"); } if (!parameters.P.Equals(new BigInteger( "90066455B5CFC38F9CAA4A48B4281F292C260FEEF01FD610" + "37E56258A7795A1C7AD46076982CE6BB956936C6AB4DCFE0" + "5E6784586940CA544B9B2140E1EB523F009D20A7E7880E4E" + "5BFA690F1B9004A27811CD9904AF70420EEFD6EA11EF7DA1" + "29F58835FF56B89FAA637BC9AC2EFAAB903402229F491D8D" + "3485261CD068699B6BA58A1DDBBEF6DB51E8FE34E8A78E54" + "2D7BA351C21EA8D8F1D29F5D5D15939487E27F4416B0CA63" + "2C59EFD1B1EB66511A5A0FBF615B766C5862D0BD8A3FE7A0" + "E0DA0FB2FE1FCB19E8F9996A8EA0FCCDE538175238FC8B0E" + "E6F29AF7F642773EBE8CD5402415A01451A840476B2FCEB0" + "E388D30D4B376C37FE401C2A2C2F941DAD179C540C1C8CE0" + "30D460C4D983BE9AB0B20F69144C1AE13F9383EA1C08504F" + "B0BF321503EFE43488310DD8DC77EC5B8349B8BFE97C2C56" + "0EA878DE87C11E3D597F1FEA742D73EEC7F37BE43949EF1A" + "0D15C3F3E3FC0A8335617055AC91328EC22B50FC15B941D3" + "D1624CD88BC25F3E941FDDC6200689581BFEC416B4B2CB73", 16))) { Fail("P incorrect"); } if (!parameters.G.Equals(new BigInteger( "5E5CBA992E0A680D885EB903AEA78E4A45A469103D448EDE" + "3B7ACCC54D521E37F84A4BDD5B06B0970CC2D2BBB715F7B8" + "2846F9A0C393914C792E6A923E2117AB805276A975AADB52" + "61D91673EA9AAFFEECBFA6183DFCB5D3B7332AA19275AFA1" + "F8EC0B60FB6F66CC23AE4870791D5982AAD1AA9485FD8F4A" + "60126FEB2CF05DB8A7F0F09B3397F3937F2E90B9E5B9C9B6" + "EFEF642BC48351C46FB171B9BFA9EF17A961CE96C7E7A7CC" + "3D3D03DFAD1078BA21DA425198F07D2481622BCE45969D9C" + "4D6063D72AB7A0F08B2F49A7CC6AF335E08C4720E31476B6" + "7299E231F8BD90B39AC3AE3BE0C6B6CACEF8289A2E2873D5" + "8E51E029CAFBD55E6841489AB66B5B4B9BA6E2F784660896" + "AFF387D92844CCB8B69475496DE19DA2E58259B090489AC8" + "E62363CDF82CFD8EF2A427ABCD65750B506F56DDE3B98856" + "7A88126B914D7828E2B63A6D7ED0747EC59E0E0A23CE7D8A" + "74C1D2C2A7AFB6A29799620F00E11C33787F7DED3B30E1A2" + "2D09F1FBDA1ABBBFBF25CAE05A13F812E34563F99410E73B", 16))) { Fail("G incorrect"); } DsaKeyPairGenerator kpGen = new DsaKeyPairGenerator(); kpGen.Init(new DsaKeyGenerationParameters( FixedSecureRandom.From(Hex.Decode("3ABC1587297CE7B9EA1AD6651CF2BC4D7F92ED25CABC8553F567D1B40EBB8764")), parameters)); AsymmetricCipherKeyPair kp = kpGen.GenerateKeyPair(); DsaPublicKeyParameters pub = (DsaPublicKeyParameters)kp.Public; DsaPrivateKeyParameters priv = (DsaPrivateKeyParameters)kp.Private; if (!pub.Y.Equals(new BigInteger( "8B891C8692D3DE875879390F2698B26FBECCA6B075535DCE" + "6B0C862577F9FA0DEF6074E7A7624121224A595896ABD4CD" + "A56B2CEFB942E025D2A4282FFAA98A48CDB47E1A6FCB5CFB" + "393EF35AF9DF913102BB303C2B5C36C3F8FC04ED7B8B69FE" + "FE0CF3E1FC05CFA713B3435B2656E913BA8874AEA9F93600" + "6AEB448BCD005D18EC3562A33D04CF25C8D3D69844343442" + "FA3DB7DE618C5E2DA064573E61E6D5581BFB694A23AC87FD" + "5B52D62E954E1376DB8DDB524FFC0D469DF978792EE44173" + "8E5DB05A7DC43E94C11A2E7A4FBE383071FA36D2A7EC8A93" + "88FE1C4F79888A99D3B6105697C2556B79BB4D7E781CEBB3" + "D4866AD825A5E830846072289FDBC941FA679CA82F5F78B7" + "461B2404DB883D215F4E0676CF5493950AC5591697BFEA8D" + "1EE6EC016B89BA51CAFB5F9C84C989FA117375E94578F28B" + "E0B34CE0545DA46266FD77F62D8F2CEE92AB77012AFEBC11" + "008985A821CD2D978C7E6FE7499D1AAF8DE632C21BB48CA5" + "CBF9F31098FD3FD3854C49A65D9201744AACE540354974F9", 16))) { Fail("Y value incorrect"); } if (!priv.X.Equals( new BigInteger("3ABC1587297CE7B9EA1AD6651CF2BC4D7F92ED25CABC8553F567D1B40EBB8764", 16))) { Fail("X value incorrect"); } DsaSigner signer = new DsaSigner(); signer.Init(true, new ParametersWithRandom(kp.Private, FixedSecureRandom.From(Hex.Decode("A6902C1E6E3943C5628061588A8B007BCCEA91DBF12915483F04B24AB0678BEE")))); byte[] msg = Hex.Decode("BA7816BF8F01CFEA414140DE5DAE2223B00361A396177A9CB410FF61F20015AD"); BigInteger[] sig = signer.GenerateSignature(msg); if (!sig[0].Equals(new BigInteger("5F184E645A38BE8FB4A6871B6503A9D12924C7ABE04B71410066C2ECA6E3BE3E", 16))) { Fail("R value incorrect"); } if (!sig[1].Equals(new BigInteger("91EB0C7BA3D4B9B60B825C3D9F2CADA8A2C9D7723267B033CBCDCF8803DB9C18", 16))) { Fail("S value incorrect"); } signer.Init(false, kp.Public); if (!signer.VerifySignature(msg, sig[0], sig[1])) { Fail("signature not verified"); } }
/// <summary> /// Create a PgpPublicKey from the passed in lightweight one. /// </summary> /// <remarks> /// Note: the time passed in affects the value of the key's keyId, so you probably only want /// to do this once for a lightweight key, or make sure you keep track of the time you used. /// </remarks> /// <param name="algorithm">Asymmetric algorithm type representing the public key.</param> /// <param name="pubKey">Actual public key to associate.</param> /// <param name="time">Date of creation.</param> /// <exception cref="ArgumentException">If <c>pubKey</c> is not public.</exception> /// <exception cref="PgpException">On key creation problem.</exception> public PgpPublicKey( PublicKeyAlgorithmTag algorithm, AsymmetricKeyParameter pubKey, DateTime time) { if (pubKey.IsPrivate) { throw new ArgumentException("Expected a public key", "pubKey"); } IBcpgKey bcpgKey; if (pubKey is RsaKeyParameters) { RsaKeyParameters rK = (RsaKeyParameters)pubKey; bcpgKey = new RsaPublicBcpgKey(rK.Modulus, rK.Exponent); } else if (pubKey is DsaPublicKeyParameters) { DsaPublicKeyParameters dK = (DsaPublicKeyParameters)pubKey; DsaParameters dP = dK.Parameters; bcpgKey = new DsaPublicBcpgKey(dP.P, dP.Q, dP.G, dK.Y); } else if (pubKey is ECPublicKeyParameters) { ECPublicKeyParameters ecK = (ECPublicKeyParameters)pubKey; if (algorithm == PublicKeyAlgorithmTag.ECDH) { bcpgKey = new ECDHPublicBcpgKey(ecK.PublicKeyParamSet, ecK.Q, HashAlgorithmTag.Sha256, SymmetricKeyAlgorithmTag.Aes128); } else if (algorithm == PublicKeyAlgorithmTag.ECDsa) { bcpgKey = new ECDsaPublicBcpgKey(ecK.PublicKeyParamSet, ecK.Q); } else { throw new PgpException("unknown EC algorithm"); } } else if (pubKey is ElGamalPublicKeyParameters) { ElGamalPublicKeyParameters eK = (ElGamalPublicKeyParameters)pubKey; ElGamalParameters eS = eK.Parameters; bcpgKey = new ElGamalPublicBcpgKey(eS.P, eS.G, eK.Y); } else { throw new PgpException("unknown key class"); } this.publicPk = new PublicKeyPacket(algorithm, time, bcpgKey); this.ids = Platform.CreateArrayList(); this.idSigs = Platform.CreateArrayList(); try { Init(); } catch (IOException e) { throw new PgpException("exception calculating keyId", e); } }
/** * 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; } 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()); } }
public static AsymmetricKeyParameter CreateKey(SubjectPublicKeyInfo keyInfo) { AlgorithmIdentifier algorithmID = keyInfo.AlgorithmID; DerObjectIdentifier objectID = algorithmID.ObjectID; if (objectID.Equals(PkcsObjectIdentifiers.RsaEncryption) || objectID.Equals(X509ObjectIdentifiers.IdEARsa) || objectID.Equals(PkcsObjectIdentifiers.IdRsassaPss) || objectID.Equals(PkcsObjectIdentifiers.IdRsaesOaep)) { RsaPublicKeyStructure instance = RsaPublicKeyStructure.GetInstance(keyInfo.GetPublicKey()); return(new RsaKeyParameters(isPrivate: false, instance.Modulus, instance.PublicExponent)); } if (objectID.Equals(X9ObjectIdentifiers.DHPublicNumber)) { Asn1Sequence instance2 = Asn1Sequence.GetInstance(algorithmID.Parameters.ToAsn1Object()); DHPublicKey instance3 = DHPublicKey.GetInstance(keyInfo.GetPublicKey()); BigInteger value = instance3.Y.Value; if (IsPkcsDHParam(instance2)) { return(ReadPkcsDHParam(objectID, value, instance2)); } DHDomainParameters instance4 = DHDomainParameters.GetInstance(instance2); BigInteger value2 = instance4.P.Value; BigInteger value3 = instance4.G.Value; BigInteger value4 = instance4.Q.Value; BigInteger j = null; if (instance4.J != null) { j = instance4.J.Value; } DHValidationParameters validation = null; DHValidationParms validationParms = instance4.ValidationParms; if (validationParms != null) { byte[] bytes = validationParms.Seed.GetBytes(); BigInteger value5 = validationParms.PgenCounter.Value; validation = new DHValidationParameters(bytes, value5.IntValue); } return(new DHPublicKeyParameters(value, new DHParameters(value2, value3, value4, j, validation))); } if (objectID.Equals(PkcsObjectIdentifiers.DhKeyAgreement)) { Asn1Sequence instance5 = Asn1Sequence.GetInstance(algorithmID.Parameters.ToAsn1Object()); DerInteger derInteger = (DerInteger)keyInfo.GetPublicKey(); return(ReadPkcsDHParam(objectID, derInteger.Value, instance5)); } if (objectID.Equals(OiwObjectIdentifiers.ElGamalAlgorithm)) { ElGamalParameter elGamalParameter = new ElGamalParameter(Asn1Sequence.GetInstance(algorithmID.Parameters.ToAsn1Object())); DerInteger derInteger2 = (DerInteger)keyInfo.GetPublicKey(); return(new ElGamalPublicKeyParameters(derInteger2.Value, new ElGamalParameters(elGamalParameter.P, elGamalParameter.G))); } if (objectID.Equals(X9ObjectIdentifiers.IdDsa) || objectID.Equals(OiwObjectIdentifiers.DsaWithSha1)) { DerInteger derInteger3 = (DerInteger)keyInfo.GetPublicKey(); Asn1Encodable parameters = algorithmID.Parameters; DsaParameters parameters2 = null; if (parameters != null) { DsaParameter instance6 = DsaParameter.GetInstance(parameters.ToAsn1Object()); parameters2 = new DsaParameters(instance6.P, instance6.Q, instance6.G); } return(new DsaPublicKeyParameters(derInteger3.Value, parameters2)); } if (objectID.Equals(X9ObjectIdentifiers.IdECPublicKey)) { X962Parameters x962Parameters = new X962Parameters(algorithmID.Parameters.ToAsn1Object()); X9ECParameters x9ECParameters = (!x962Parameters.IsNamedCurve) ? new X9ECParameters((Asn1Sequence)x962Parameters.Parameters) : ECKeyPairGenerator.FindECCurveByOid((DerObjectIdentifier)x962Parameters.Parameters); Asn1OctetString s = new DerOctetString(keyInfo.PublicKeyData.GetBytes()); X9ECPoint x9ECPoint = new X9ECPoint(x9ECParameters.Curve, s); ECPoint point = x9ECPoint.Point; if (x962Parameters.IsNamedCurve) { return(new ECPublicKeyParameters("EC", point, (DerObjectIdentifier)x962Parameters.Parameters)); } ECDomainParameters parameters3 = new ECDomainParameters(x9ECParameters.Curve, x9ECParameters.G, x9ECParameters.N, x9ECParameters.H, x9ECParameters.GetSeed()); return(new ECPublicKeyParameters(point, parameters3)); } if (objectID.Equals(CryptoProObjectIdentifiers.GostR3410x2001)) { Gost3410PublicKeyAlgParameters gost3410PublicKeyAlgParameters = new Gost3410PublicKeyAlgParameters((Asn1Sequence)algorithmID.Parameters); Asn1OctetString asn1OctetString; try { asn1OctetString = (Asn1OctetString)keyInfo.GetPublicKey(); } catch (IOException) { throw new ArgumentException("invalid info structure in GOST3410 public key"); IL_038b :; } byte[] octets = asn1OctetString.GetOctets(); byte[] array = new byte[32]; byte[] array2 = new byte[32]; for (int i = 0; i != array2.Length; i++) { array[i] = octets[31 - i]; } for (int k = 0; k != array.Length; k++) { array2[k] = octets[63 - k]; } ECDomainParameters byOid = ECGost3410NamedCurves.GetByOid(gost3410PublicKeyAlgParameters.PublicKeyParamSet); if (byOid == null) { return(null); } ECPoint q = byOid.Curve.CreatePoint(new BigInteger(1, array), new BigInteger(1, array2)); return(new ECPublicKeyParameters("ECGOST3410", q, gost3410PublicKeyAlgParameters.PublicKeyParamSet)); } if (objectID.Equals(CryptoProObjectIdentifiers.GostR3410x94)) { Gost3410PublicKeyAlgParameters gost3410PublicKeyAlgParameters2 = new Gost3410PublicKeyAlgParameters((Asn1Sequence)algorithmID.Parameters); DerOctetString derOctetString; try { derOctetString = (DerOctetString)keyInfo.GetPublicKey(); } catch (IOException) { throw new ArgumentException("invalid info structure in GOST3410 public key"); IL_0480 :; } byte[] octets2 = derOctetString.GetOctets(); byte[] array3 = new byte[octets2.Length]; for (int l = 0; l != octets2.Length; l++) { array3[l] = octets2[octets2.Length - 1 - l]; } BigInteger y = new BigInteger(1, array3); return(new Gost3410PublicKeyParameters(y, gost3410PublicKeyAlgParameters2.PublicKeyParamSet)); } throw new SecurityUtilityException("algorithm identifier in key not recognised: " + objectID); }
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()); X9ECParameters ecP = ECGost3410NamedCurves.GetByOidX9(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)) { X9ECParameters ecP = ECGost3410NamedCurves.GetByOidX9(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); ecSpec = new ECGost3410Parameters(new ECNamedDomainParameters(oid, ecP), 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), 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"); } }
public void GenerateSignature(byte[] data_to_sign_byte_array, ref byte[] r_byte_array, ref byte[] s_byte_array) { if (data_to_sign_byte_array == null || data_to_sign_byte_array.Length < 1) { throw new ArgumentException("GenerateSignature: The data byte array to sign cannot be null/empty"); } if (_private_key_param == null) { throw new ArgumentException("GenerateSignature: The DSA private key cannot be null"); } if (_secure_random == null) { _secure_random = new SecureRandom(); } BigInteger _data_to_sign = null; DsaParameters _parameters = null; BigInteger _k; BigInteger _r; BigInteger _s; int _q_bit_length; bool _do_again = false; int _failure_count = 0; _parameters = _private_key_param.Parameters; _data_to_sign = new BigInteger(1, data_to_sign_byte_array); _q_bit_length = _parameters.Q.BitLength; /* */ // if (IsValidPQLength(_parameters.P.BitLength, _parameters.Q.BitLength) == false) //throw new InvalidDataException("GenerateSignature: The Length of the DSA key P parameter does not correspond to that of the Q parameter"); do { try { do { _k = new BigInteger(1, _secure_random); }while (_k.CompareTo(_parameters.Q) >= 0); _r = _parameters.G.ModPow(_k, _parameters.P).Mod(_parameters.Q); _k = _k.ModInverse(_parameters.Q).Multiply(_data_to_sign.Add((_private_key_param).X.Multiply(_r))); _s = _k.Mod(_parameters.Q); r_byte_array = _r.ToByteArray(); s_byte_array = _s.ToByteArray(); _do_again = false; } catch (Exception) { if (MAX_FAILURE_COUNT == _failure_count) { throw new InvalidDataException("GenerateSignature: Failed sign data after " + MAX_FAILURE_COUNT.ToString() + " tries."); } _do_again = true; _failure_count++; } }while (_do_again == true); Utility.SetAsMinimalLengthBE(ref r_byte_array); Utility.SetAsMinimalLengthBE(ref s_byte_array); /* * Console.WriteLine("Q Length {0} \n", _parameters.Q.BitLength/8); * Console.WriteLine("R Length {0} \n", r_byte_array.Length); * Console.WriteLine("S Length {0} \n", s_byte_array.Length);//*/ }
public override void PerformTest() { byte[] k1 = Hex.Decode("d5014e4b60ef2ba8b6211b4062ba3224e0427dd3"); byte[] k2 = Hex.Decode("345e8d05c075c3a508df729a1685690e68fcfb8c8117847e89063bca1f85d968fd281540b6e13bd1af989a1fbf17e06462bf511f9d0b140fb48ac1b1baa5bded"); SecureRandom random = FixedSecureRandom.From(k1, k2); byte[] keyData = Hex.Decode("b5014e4b60ef2ba8b6211b4062ba3224e0427dd3"); SecureRandom keyRandom = FixedSecureRandom.From(keyData, keyData); IBigInteger r = new BigInteger("68076202252361894315274692543577577550894681403"); IBigInteger s = new BigInteger("1089214853334067536215539335472893651470583479365"); DsaParametersGenerator pGen = new DsaParametersGenerator(); pGen.Init(512, 80, random); DsaParameters parameters = pGen.GenerateParameters(); DsaValidationParameters pValid = parameters.ValidationParameters; if (pValid.Counter != 105) { Fail("Counter wrong"); } if (!pValue.Equals(parameters.P) || !qValue.Equals(parameters.Q)) { Fail("p or q wrong"); } DsaKeyPairGenerator dsaKeyGen = new DsaKeyPairGenerator(); DsaKeyGenerationParameters genParam = new DsaKeyGenerationParameters(keyRandom, parameters); dsaKeyGen.Init(genParam); IAsymmetricCipherKeyPair pair = dsaKeyGen.GenerateKeyPair(); ParametersWithRandom param = new ParametersWithRandom(pair.Private, keyRandom); DsaSigner dsa = new DsaSigner(); dsa.Init(true, param); byte[] message = new BigInteger("968236873715988614170569073515315707566766479517").ToByteArrayUnsigned(); IBigInteger[] sig = dsa.GenerateSignature(message); if (!r.Equals(sig[0])) { Fail("r component wrong." + SimpleTest.NewLine + " expecting: " + r + SimpleTest.NewLine + " got : " + sig[0]); } if (!s.Equals(sig[1])) { Fail("s component wrong." + SimpleTest.NewLine + " expecting: " + s + SimpleTest.NewLine + " got : " + sig[1]); } dsa.Init(false, pair.Public); if (!dsa.VerifySignature(message, sig[0], sig[1])) { Fail("verification fails"); } }
/// <summary>Extract a <c>PgpPrivateKey</c> from this secret key's encrypted contents.</summary> public PgpPrivateKey ExtractPrivateKey( char[] passPhrase) { byte[] secKeyData = secret.GetSecretKeyData(); if (secKeyData == null || secKeyData.Length < 1) { return(null); } PublicKeyPacket pubPk = secret.PublicKeyPacket; try { byte[] data = ExtractKeyData(passPhrase); BcpgInputStream bcpgIn = BcpgInputStream.Wrap(new MemoryStream(data, false)); AsymmetricKeyParameter privateKey; switch (pubPk.Algorithm) { case PublicKeyAlgorithmTag.RsaEncrypt: case PublicKeyAlgorithmTag.RsaGeneral: case PublicKeyAlgorithmTag.RsaSign: RsaPublicBcpgKey rsaPub = (RsaPublicBcpgKey)pubPk.Key; RsaSecretBcpgKey rsaPriv = new RsaSecretBcpgKey(bcpgIn); RsaPrivateCrtKeyParameters rsaPrivSpec = new RsaPrivateCrtKeyParameters( rsaPriv.Modulus, rsaPub.PublicExponent, rsaPriv.PrivateExponent, rsaPriv.PrimeP, rsaPriv.PrimeQ, rsaPriv.PrimeExponentP, rsaPriv.PrimeExponentQ, rsaPriv.CrtCoefficient); privateKey = rsaPrivSpec; break; case PublicKeyAlgorithmTag.Dsa: DsaPublicBcpgKey dsaPub = (DsaPublicBcpgKey)pubPk.Key; DsaSecretBcpgKey dsaPriv = new DsaSecretBcpgKey(bcpgIn); DsaParameters dsaParams = new DsaParameters(dsaPub.P, dsaPub.Q, dsaPub.G); privateKey = new DsaPrivateKeyParameters(dsaPriv.X, dsaParams); break; case PublicKeyAlgorithmTag.ElGamalEncrypt: case PublicKeyAlgorithmTag.ElGamalGeneral: ElGamalPublicBcpgKey elPub = (ElGamalPublicBcpgKey)pubPk.Key; ElGamalSecretBcpgKey elPriv = new ElGamalSecretBcpgKey(bcpgIn); ElGamalParameters elParams = new ElGamalParameters(elPub.P, elPub.G); privateKey = new ElGamalPrivateKeyParameters(elPriv.X, elParams); break; default: throw new PgpException("unknown public key algorithm encountered"); } return(new PgpPrivateKey(privateKey, KeyId)); } catch (PgpException e) { throw e; } catch (Exception e) { throw new PgpException("Exception constructing key", e); } }
public void TestParameters() { // AlgorithmParameterGenerator a = AlgorithmParameterGenerator.GetInstance("DSA"); // a.init(512, random); DsaParametersGenerator a = new DsaParametersGenerator(); a.Init(512, 20, random); // AlgorithmParameters parameters = a.generateParameters(); DsaParameters p = a.GenerateParameters(); // byte[] encodeParams = parameters.GetEncoded(); byte[] encodeParams = new DsaParameter(p.P, p.Q, p.G).GetDerEncoded(); // AlgorithmParameters a2 = AlgorithmParameters.GetInstance("DSA"); // a2.init(encodeParams); DsaParameter dsaP = DsaParameter.GetInstance(Asn1Object.FromByteArray(encodeParams)); DsaParameters p2 = new DsaParameters(dsaP.P, dsaP.Q, dsaP.G); // a and a2 should be equivalent! // byte[] encodeParams_2 = a2.GetEncoded(); byte[] encodeParams_2 = new DsaParameter(p2.P, p2.Q, p2.G).GetDerEncoded(); if (!AreEqual(encodeParams, encodeParams_2)) { Fail("encode/Decode parameters failed"); } // DSAParameterSpec dsaP = (DSAParameterSpec)parameters.getParameterSpec(typeof(DSAParameterSpec)); // KeyPairGenerator g = KeyPairGenerator.GetInstance("DSA"); IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("DSA"); // g.initialize(dsaP, new SecureRandom()); g.Init(new DsaKeyGenerationParameters(new SecureRandom(), p)); // KeyPair p = g.generateKeyPair(); AsymmetricCipherKeyPair pair = g.GenerateKeyPair(); // PrivateKey sKey = p.Private; // PublicKey vKey = p.Public; AsymmetricKeyParameter sKey = pair.Private; AsymmetricKeyParameter vKey = pair.Public; ISigner s = SignerUtilities.GetSigner("DSA"); byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; s.Init(true, sKey); s.BlockUpdate(data, 0, data.Length); byte[] sigBytes = s.GenerateSignature(); s = SignerUtilities.GetSigner("DSA"); s.Init(false, vKey); s.BlockUpdate(data, 0, data.Length); if (!s.VerifySignature(sigBytes)) { Fail("DSA verification failed"); } }
public static AsymmetricKeyParameter CreateKey( SubjectPublicKeyInfo keyInfo) { AlgorithmIdentifier algID = keyInfo.AlgorithmID; 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)) { RsaPublicKeyStructure pubKey = RsaPublicKeyStructure.GetInstance( keyInfo.GetPublicKey()); return(new RsaKeyParameters(false, pubKey.Modulus, pubKey.PublicExponent)); } else if (algOid.Equals(X9ObjectIdentifiers.DHPublicNumber)) { Asn1Sequence seq = Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object()); DHPublicKey dhPublicKey = DHPublicKey.GetInstance(keyInfo.GetPublicKey()); BigInteger y = dhPublicKey.Y.Value; if (IsPkcsDHParam(seq)) { return(ReadPkcsDHParam(algOid, y, seq)); } DHDomainParameters dhParams = DHDomainParameters.GetInstance(seq); BigInteger p = dhParams.P.Value; BigInteger g = dhParams.G.Value; BigInteger q = dhParams.Q.Value; BigInteger j = null; if (dhParams.J != null) { j = dhParams.J.Value; } DHValidationParameters validation = null; DHValidationParms dhValidationParms = dhParams.ValidationParms; if (dhValidationParms != null) { byte[] seed = dhValidationParms.Seed.GetBytes(); BigInteger pgenCounter = dhValidationParms.PgenCounter.Value; // TODO Check pgenCounter size? validation = new DHValidationParameters(seed, pgenCounter.IntValue); } return(new DHPublicKeyParameters(y, new DHParameters(p, g, q, j, validation))); } else if (algOid.Equals(PkcsObjectIdentifiers.DhKeyAgreement)) { Asn1Sequence seq = Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object()); DerInteger derY = (DerInteger)keyInfo.GetPublicKey(); return(ReadPkcsDHParam(algOid, derY.Value, seq)); } else if (algOid.Equals(OiwObjectIdentifiers.ElGamalAlgorithm)) { ElGamalParameter para = new ElGamalParameter( Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object())); DerInteger derY = (DerInteger)keyInfo.GetPublicKey(); return(new ElGamalPublicKeyParameters( derY.Value, new ElGamalParameters(para.P, para.G))); } else if (algOid.Equals(X9ObjectIdentifiers.IdDsa) || algOid.Equals(OiwObjectIdentifiers.DsaWithSha1)) { DerInteger derY = (DerInteger)keyInfo.GetPublicKey(); 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 DsaPublicKeyParameters(derY.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); } Asn1OctetString key = new DerOctetString(keyInfo.PublicKeyData.GetBytes()); X9ECPoint derQ = new X9ECPoint(x9.Curve, key); ECPoint q = derQ.Point; if (para.IsNamedCurve) { return(new ECPublicKeyParameters("EC", q, (DerObjectIdentifier)para.Parameters)); } ECDomainParameters dParams = new ECDomainParameters(x9.Curve, x9.G, x9.N, x9.H, x9.GetSeed()); return(new ECPublicKeyParameters(q, dParams)); } else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x2001)) { Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters( (Asn1Sequence)algID.Parameters); Asn1OctetString key; try { key = (Asn1OctetString)keyInfo.GetPublicKey(); } catch (IOException) { throw new ArgumentException("invalid info structure in GOST3410 public key"); } byte[] keyEnc = key.GetOctets(); byte[] x = new byte[32]; byte[] y = new byte[32]; for (int i = 0; i != y.Length; i++) { x[i] = keyEnc[32 - 1 - i]; } for (int i = 0; i != x.Length; i++) { y[i] = keyEnc[64 - 1 - i]; } ECDomainParameters ecP = ECGost3410NamedCurves.GetByOid(gostParams.PublicKeyParamSet); if (ecP == null) { return(null); } ECPoint q = ecP.Curve.CreatePoint(new BigInteger(1, x), new BigInteger(1, y)); return(new ECPublicKeyParameters("ECGOST3410", q, gostParams.PublicKeyParamSet)); } else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x94)) { Gost3410PublicKeyAlgParameters algParams = new Gost3410PublicKeyAlgParameters( (Asn1Sequence)algID.Parameters); DerOctetString derY; try { derY = (DerOctetString)keyInfo.GetPublicKey(); } catch (IOException) { throw new ArgumentException("invalid info structure in GOST3410 public key"); } byte[] keyEnc = derY.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 y = new BigInteger(1, keyBytes); return(new Gost3410PublicKeyParameters(y, algParams.PublicKeyParamSet)); } else { throw new SecurityUtilityException("algorithm identifier in key not recognised: " + algOid); } }
public static AsymmetricKeyParameter CreateKey(PrivateKeyInfo keyInfo) { AlgorithmIdentifier privateKeyAlgorithm = keyInfo.PrivateKeyAlgorithm; DerObjectIdentifier objectID = privateKeyAlgorithm.ObjectID; if (objectID.Equals(PkcsObjectIdentifiers.RsaEncryption) || objectID.Equals(X509ObjectIdentifiers.IdEARsa) || objectID.Equals(PkcsObjectIdentifiers.IdRsassaPss) || objectID.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 (objectID.Equals(PkcsObjectIdentifiers.DhKeyAgreement)) { DHParameter dHParameter = new DHParameter(Asn1Sequence.GetInstance(privateKeyAlgorithm.Parameters.ToAsn1Object())); DerInteger derInteger = (DerInteger)keyInfo.ParsePrivateKey(); BigInteger l = dHParameter.L; int l2 = (l == null) ? 0 : l.IntValue; DHParameters parameters = new DHParameters(dHParameter.P, dHParameter.G, null, l2); return(new DHPrivateKeyParameters(derInteger.Value, parameters, objectID)); } if (objectID.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 (objectID.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 (objectID.Equals(X9ObjectIdentifiers.IdECPublicKey)) { X962Parameters x962Parameters = new X962Parameters(privateKeyAlgorithm.Parameters.ToAsn1Object()); X9ECParameters x9ECParameters; if (x962Parameters.IsNamedCurve) { x9ECParameters = ECKeyPairGenerator.FindECCurveByOid((DerObjectIdentifier)x962Parameters.Parameters); } else { x9ECParameters = new X9ECParameters((Asn1Sequence)x962Parameters.Parameters); } ECPrivateKeyStructure eCPrivateKeyStructure = new ECPrivateKeyStructure(Asn1Sequence.GetInstance(keyInfo.ParsePrivateKey())); BigInteger key = eCPrivateKeyStructure.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)); } else if (objectID.Equals(CryptoProObjectIdentifiers.GostR3410x2001)) { Gost3410PublicKeyAlgParameters gost3410PublicKeyAlgParameters = new Gost3410PublicKeyAlgParameters(Asn1Sequence.GetInstance(privateKeyAlgorithm.Parameters.ToAsn1Object())); Asn1Object asn1Object = keyInfo.ParsePrivateKey(); ECPrivateKeyStructure eCPrivateKeyStructure2; if (asn1Object is DerInteger) { eCPrivateKeyStructure2 = new ECPrivateKeyStructure(((DerInteger)asn1Object).Value); } else { eCPrivateKeyStructure2 = ECPrivateKeyStructure.GetInstance(asn1Object); } if (ECGost3410NamedCurves.GetByOid(gost3410PublicKeyAlgParameters.PublicKeyParamSet) == null) { throw new ArgumentException("Unrecognized curve OID for GostR3410x2001 private key"); } return(new ECPrivateKeyParameters("ECGOST3410", eCPrivateKeyStructure2.GetKey(), gost3410PublicKeyAlgParameters.PublicKeyParamSet)); } else { if (objectID.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"); } }