private void VerifyEnvelopedData(CmsEnvelopedDataParser envelopedParser, string symAlgorithmOID) { byte[] privKeyData = GetRfc4134Data("BobPrivRSAEncrypt.pri"); IAsymmetricKeyParameter privKey = PrivateKeyFactory.CreateKey(privKeyData); Assert.IsTrue(privKey.IsPrivate); Assert.IsTrue(privKey is RsaKeyParameters); RecipientInformationStore recipients = envelopedParser.GetRecipientInfos(); Assert.AreEqual(envelopedParser.EncryptionAlgOid, symAlgorithmOID); ArrayList c = new ArrayList(recipients.GetRecipients()); Assert.LessOrEqual(1, c.Count); Assert.GreaterOrEqual(2, c.Count); VerifyRecipient((RecipientInformation)c[0], privKey); if (c.Count == 2) { RecipientInformation recInfo = (RecipientInformation)c[1]; Assert.AreEqual(PkcsObjectIdentifiers.IdAlgCmsRC2Wrap.Id, recInfo.KeyEncryptionAlgOid); } }
public void TestPkcs8Plain() { IAsymmetricCipherKeyPairGenerator kpGen = GeneratorUtilities.GetKeyPairGenerator("RSA"); kpGen.Init(new KeyGenerationParameters(new SecureRandom(), 1024)); IAsymmetricKeyParameter privKey = kpGen.GenerateKeyPair().Private; StringWriter sw = new StringWriter(); PemWriter pWrt = new PemWriter(sw); Pkcs8Generator pkcs8 = new Pkcs8Generator(privKey); pWrt.WriteObject(pkcs8); pWrt.Writer.Close(); string result = sw.ToString(); PemReader pRd = new PemReader(new StringReader(result), new Password("hello".ToCharArray())); IAsymmetricKeyParameter rdKey = (AsymmetricKeyParameter)pRd.ReadObject(); pRd.Reader.Close(); Assert.AreEqual(privKey, rdKey); }
private void rawModeTest(string sigName, DerObjectIdentifier digestOID, IAsymmetricKeyParameter privKey, IAsymmetricKeyParameter pubKey, SecureRandom random) { byte[] sampleMessage = new byte[1000 + random.Next() % 100]; random.NextBytes(sampleMessage); ISigner normalSig = SignerUtilities.GetSigner(sigName); normalSig.Init(true, privKey); normalSig.BlockUpdate(sampleMessage, 0, sampleMessage.Length); byte[] normalResult = normalSig.GenerateSignature(); byte[] hash = DigestUtilities.CalculateDigest(digestOID.Id, sampleMessage); byte[] digInfo = derEncode(digestOID, hash); ISigner rawSig = SignerUtilities.GetSigner("RSA"); rawSig.Init(true, privKey); rawSig.BlockUpdate(digInfo, 0, digInfo.Length); byte[] rawResult = rawSig.GenerateSignature(); if (!Arrays.AreEqual(normalResult, rawResult)) { Fail("raw mode signature differs from normal one"); } rawSig.Init(false, pubKey); rawSig.BlockUpdate(digInfo, 0, digInfo.Length); if (!rawSig.VerifySignature(rawResult)) { Fail("raw mode signature verification failed"); } }
public AsymmetricKeyEntry( IAsymmetricKeyParameter key, Hashtable attributes) : base(attributes) { this.key = key; }
public virtual void ProcessServerCertificate(Certificate serverCertificate) { if (tlsSigner == null) { throw new TlsFatalAlert(AlertDescription.unexpected_message); } X509CertificateStructure x509Cert = serverCertificate.certs[0]; SubjectPublicKeyInfo keyInfo = x509Cert.SubjectPublicKeyInfo; try { this.serverPublicKey = PublicKeyFactory.CreateKey(keyInfo); } // catch (RuntimeException) catch (Exception) { throw new TlsFatalAlert(AlertDescription.unsupported_certificate); } if (!tlsSigner.IsValidPublicKey(this.serverPublicKey)) { throw new TlsFatalAlert(AlertDescription.certificate_unknown); } TlsUtilities.ValidateKeyUsage(x509Cert, KeyUsage.DigitalSignature); // TODO /* * Perform various checks per RFC2246 7.4.2: "Unless otherwise specified, the * signing algorithm for the certificate must be the same as the algorithm for the * certificate key." */ }
public OcspReq Generate( string signingAlgorithm, IAsymmetricKeyParameter privateKey, X509Certificate[] chain) { return(Generate(signingAlgorithm, privateKey, chain, null)); }
public AsymmetricKeyEntry( IAsymmetricKeyParameter key, IDictionary attributes) : base(attributes) { this.key = key; }
/** * add a signer - no attributes other than the default ones will be * provided here. */ public void AddSigner( IAsymmetricKeyParameter privateKey, byte[] subjectKeyID, string digestOID) { AddSigner(privateKey, subjectKeyID, GetEncOid(privateKey, digestOID), digestOID); }
internal static byte[] GetSignatureForObject( DerObjectIdentifier sigOid, // TODO Redundant now? string sigName, IAsymmetricKeyParameter privateKey, SecureRandom random, Asn1Encodable ae) { if (sigOid == null) { throw new ArgumentNullException("sigOid"); } ISigner sig = SignerUtilities.GetSigner(sigName); if (random != null) { sig.Init(true, new ParametersWithRandom(privateKey, random)); } else { sig.Init(true, privateKey); } byte[] encoded = ae.GetDerEncoded(); sig.BlockUpdate(encoded, 0, encoded.Length); return(sig.GenerateSignature()); }
public static X509Certificate MakeCertificate(IAsymmetricCipherKeyPair _subKP, string _subDN, IAsymmetricCipherKeyPair _issKP, string _issDN, string algorithm, bool _ca) { IAsymmetricKeyParameter _subPub = _subKP.Public; IAsymmetricKeyParameter _issPriv = _issKP.Private; IAsymmetricKeyParameter _issPub = _issKP.Public; X509V3CertificateGenerator _v3CertGen = new X509V3CertificateGenerator(); _v3CertGen.Reset(); _v3CertGen.SetSerialNumber(allocateSerialNumber()); _v3CertGen.SetIssuerDN(new X509Name(_issDN)); _v3CertGen.SetNotBefore(DateTime.UtcNow); _v3CertGen.SetNotAfter(DateTime.UtcNow.AddDays(100)); _v3CertGen.SetSubjectDN(new X509Name(_subDN)); _v3CertGen.SetPublicKey(_subPub); _v3CertGen.SetSignatureAlgorithm(algorithm); _v3CertGen.AddExtension(X509Extensions.SubjectKeyIdentifier, false, createSubjectKeyId(_subPub)); _v3CertGen.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, createAuthorityKeyId(_issPub)); _v3CertGen.AddExtension(X509Extensions.BasicConstraints, false, new BasicConstraints(_ca)); X509Certificate _cert = _v3CertGen.Generate(_issPriv); _cert.CheckValidity(DateTime.UtcNow); _cert.Verify(_issPub); return(_cert); }
private static SubjectKeyIdentifier createSubjectKeyId( IAsymmetricKeyParameter _pubKey) { SubjectPublicKeyInfo _info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(_pubKey); return(new SubjectKeyIdentifier(_info)); }
public override void PerformTest() { IAsymmetricCipherKeyPairGenerator pGen = GeneratorUtilities.GetKeyPairGenerator("RSA"); RsaKeyGenerationParameters genParam = new RsaKeyGenerationParameters( BigInteger.ValueOf(0x10001), new SecureRandom(), 512, 25); pGen.Init(genParam); IAsymmetricCipherKeyPair pair = pGen.GenerateKeyPair(); // // set up the parameters // byte[] salt = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int iterationCount = 100; // // set up the key // char[] password1 = { 'h', 'e', 'l', 'l', 'o' }; EncryptedPrivateKeyInfo encInfo = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo(alg, password1, salt, iterationCount, PrivateKeyInfoFactory.CreatePrivateKeyInfo(pair.Private)); PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(password1, encInfo); IAsymmetricKeyParameter key = PrivateKeyFactory.CreateKey(info); if (!key.Equals(pair.Private)) { Fail("Key corrupted"); } doOpensslTestKeys(); }
/// <summary> /// Generate an X509Certificate using your own SecureRandom. /// </summary> /// <param name="privateKey">The private key of the issuer that is signing this certificate.</param> /// <param name="random">You Secure Random instance.</param> /// <returns>An X509Certificate.</returns> public X509Certificate Generate( IAsymmetricKeyParameter privateKey, SecureRandom random) { TbsCertificateStructure tbsCert = GenerateTbsCert(); byte[] signature; try { signature = X509Utilities.GetSignatureForObject( sigOid, signatureAlgorithm, privateKey, random, tbsCert); } catch (Exception e) { // TODO // throw new ExtCertificateEncodingException("exception encoding TBS cert", e); throw new CertificateEncodingException("exception encoding TBS cert", e); } try { return(GenerateJcaObject(tbsCert, signature)); } catch (CertificateParsingException e) { // TODO // throw new ExtCertificateEncodingException("exception producing certificate object", e); throw new CertificateEncodingException("exception producing certificate object", e); } }
/** * Constructor for an encrypted private key PEM object. * * @param key private key to be encoded * @param algorithm encryption algorithm to use * @param provider provider to use * @throws NoSuchAlgorithmException if algorithm/mode cannot be found */ public Pkcs8Generator(IAsymmetricKeyParameter privKey, string algorithm) { // TODO Check privKey.IsPrivate this.privKey = privKey; this.algorithm = algorithm; this.iterationCount = 2048; }
public OcspReq Generate( string signingAlgorithm, IAsymmetricKeyParameter privateKey, X509Certificate[] chain) { return Generate(signingAlgorithm, privateKey, chain, null); }
public virtual byte[] GenerateAgreement(IAsymmetricKeyParameter serverPublicKey) { basicAgreement.Init(clientPrivateKey); IBigInteger agreementValue = basicAgreement.CalculateAgreement(serverPublicKey); return(BigIntegers.AsUnsignedByteArray(agreementValue)); }
public virtual void ProcessServerCertificate(Certificate serverCertificate) { X509CertificateStructure x509Cert = serverCertificate.certs[0]; SubjectPublicKeyInfo keyInfo = x509Cert.SubjectPublicKeyInfo; try { this.serverPublicKey = PublicKeyFactory.CreateKey(keyInfo); } // catch (RuntimeException) catch (Exception) { throw new TlsFatalAlert(AlertDescription.unsupported_certificate); } // Sanity check the PublicKeyFactory if (this.serverPublicKey.IsPrivate) { throw new TlsFatalAlert(AlertDescription.internal_error); } this.rsaServerPublicKey = ValidateRsaPublicKey((RsaKeyParameters)this.serverPublicKey); TlsUtilities.ValidateKeyUsage(x509Cert, KeyUsage.KeyEncipherment); // TODO /* * Perform various checks per RFC2246 7.4.2: "Unless otherwise specified, the * signing algorithm for the certificate must be the same as the algorithm for the * certificate key." */ }
private static CertID createCertID( AlgorithmIdentifier hashAlg, X509Certificate issuerCert, DerInteger serialNumber) { try { String hashAlgorithm = hashAlg.ObjectID.Id; X509Name issuerName = PrincipalUtilities.GetSubjectX509Principal(issuerCert); byte[] issuerNameHash = DigestUtilities.CalculateDigest( hashAlgorithm, issuerName.GetEncoded()); IAsymmetricKeyParameter issuerKey = issuerCert.GetPublicKey(); SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(issuerKey); byte[] issuerKeyHash = DigestUtilities.CalculateDigest( hashAlgorithm, info.PublicKeyData.GetBytes()); return(new CertID(hashAlg, new DerOctetString(issuerNameHash), new DerOctetString(issuerKeyHash), serialNumber)); } catch (Exception e) { throw new OcspException("problem creating ID: " + e, e); } }
/// <summary> /// Generate an X509 certificate, based on the current issuer and subject, /// using the supplied source of randomness, if required. /// </summary> public IX509AttributeCertificate Generate( IAsymmetricKeyParameter publicKey, SecureRandom random) { if (!extGenerator.IsEmpty) { acInfoGen.SetExtensions(extGenerator.Generate()); } AttributeCertificateInfo acInfo = acInfoGen.GenerateAttributeCertificateInfo(); Asn1EncodableVector v = new Asn1EncodableVector(); v.Add(acInfo, sigAlgId); try { v.Add(new DerBitString(X509Utilities.GetSignatureForObject(sigOID, signatureAlgorithm, publicKey, random, acInfo))); return(new X509V2AttributeCertificate(AttributeCertificate.GetInstance(new DerSequence(v)))); } catch (Exception e) { // TODO // throw new ExtCertificateEncodingException("constructed invalid certificate", e); throw new CertificateEncodingException("constructed invalid certificate", e); } }
public bool VerifyRawSignature(byte[] sigBytes, IAsymmetricKeyParameter publicKey, byte[] md5andsha1) { ISigner s = MakeSigner(new NullDigest(), false, publicKey); // Note: Only use the SHA1 part of the hash s.BlockUpdate(md5andsha1, 16, 20); return s.VerifySignature(sigBytes); }
/** * intermediate cert */ private X509Certificate CreateIntmedCert( IAsymmetricKeyParameter pubKey, IAsymmetricKeyParameter caPrivKey, IAsymmetricKeyParameter caPubKey, Asn1EncodableVector policies, Hashtable policyMap) { string issuer = "C=JP, O=policyMappingAdditionalTest, OU=trustAnchor"; string subject = "C=JP, O=policyMappingAdditionalTest, OU=intmedCA"; v3CertGen.Reset(); v3CertGen.SetSerialNumber(BigInteger.ValueOf(20)); v3CertGen.SetIssuerDN(new X509Name(issuer)); v3CertGen.SetNotBefore(DateTime.UtcNow.AddDays(-30)); v3CertGen.SetNotAfter(DateTime.UtcNow.AddDays(30)); v3CertGen.SetSubjectDN(new X509Name(subject)); v3CertGen.SetPublicKey(pubKey); v3CertGen.SetSignatureAlgorithm("SHA1WithRSAEncryption"); v3CertGen.AddExtension(X509Extensions.CertificatePolicies, true, new DerSequence(policies)); v3CertGen.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true)); v3CertGen.AddExtension(X509Extensions.PolicyMappings, true, new PolicyMappings(policyMap)); X509Certificate cert = v3CertGen.Generate(caPrivKey); return(cert); }
/** * Add multiple key agreement based recipients (sharing a single KeyAgreeRecipientInfo structure). * * @param agreementAlgorithm key agreement algorithm to use. * @param senderPrivateKey private key to initialise sender side of agreement with. * @param senderPublicKey sender public key to include with message. * @param recipientCerts recipients' public key certificates. * @param cekWrapAlgorithm OID for key wrapping algorithm to use. * @exception SecurityUtilityException if the algorithm requested cannot be found * @exception InvalidKeyException if the keys are inappropriate for the algorithm specified */ public void AddKeyAgreementRecipients( string agreementAlgorithm, IAsymmetricKeyParameter senderPrivateKey, IAsymmetricKeyParameter senderPublicKey, ICollection recipientCerts, string cekWrapAlgorithm) { if (!senderPrivateKey.IsPrivate) { throw new ArgumentException(@"Expected private key", "senderPrivateKey"); } if (senderPublicKey.IsPrivate) { throw new ArgumentException(@"Expected public key", "senderPublicKey"); } /* TODO * "a recipient X.509 version 3 certificate that contains a key usage extension MUST * assert the keyAgreement bit." */ KeyAgreeRecipientInfoGenerator karig = new KeyAgreeRecipientInfoGenerator(); karig.KeyAgreementOID = new DerObjectIdentifier(agreementAlgorithm); karig.KeyEncryptionOID = new DerObjectIdentifier(cekWrapAlgorithm); karig.RecipientCerts = recipientCerts; karig.SenderKeyPair = new AsymmetricCipherKeyPair(senderPublicKey, senderPrivateKey); recipientInfoGenerators.Add(karig); }
public override void PerformTest() { IAsymmetricCipherKeyPairGenerator dsaKpg = GeneratorUtilities.GetKeyPairGenerator("DSA"); dsaKpg.Init(new DsaKeyGenerationParameters(random, testDsaParams)); IAsymmetricCipherKeyPair testDsaKp = dsaKpg.GenerateKeyPair(); IAsymmetricKeyParameter testDsaKey = testDsaKp.Private; doWriteReadTest(testDsaKey); doWriteReadTests(testDsaKey, algorithms); doWriteReadTest(testRsaKey); doWriteReadTests(testRsaKey, algorithms); IAsymmetricKeyParameter ecPriv = PrivateKeyFactory.CreateKey(testEcDsaKeyBytes); doWriteReadTest(ecPriv); doWriteReadTests(ecPriv, algorithms); IAsymmetricCipherKeyPairGenerator ecKpg = GeneratorUtilities.GetKeyPairGenerator("ECDSA"); ecKpg.Init(new KeyGenerationParameters(random, 239)); ecPriv = ecKpg.GenerateKeyPair().Private; doWriteReadTest(ecPriv); doWriteReadTests(ecPriv, algorithms); // override test PemWriter pWrt = new PemWriter(new StringWriter()); object o = new PemObject("FRED", new byte[100]); pWrt.WriteObject(o); pWrt.Writer.Close(); }
public virtual void Verify( IAsymmetricKeyParameter publicKey) { if (!cert.SignatureAlgorithm.Equals(cert.ACInfo.Signature)) { throw new CertificateException("Signature algorithm in certificate info not same as outer certificate"); } ISigner signature = SignerUtilities.GetSigner(cert.SignatureAlgorithm.ObjectID.Id); signature.Init(false, publicKey); try { byte[] b = cert.ACInfo.GetEncoded(); signature.BlockUpdate(b, 0, b.Length); } catch (IOException e) { throw new SignatureException("Exception encoding certificate info object", e); } if (!signature.VerifySignature(this.GetSignature())) { throw new InvalidKeyException("Public key presented not for certificate signature"); } }
/** * add a signer - no attributes other than the default ones will be * provided here. * * @param key signing key to use * @param cert certificate containing corresponding public key * @param digestOID digest algorithm OID */ public void AddSigner( IAsymmetricKeyParameter privateKey, X509Certificate cert, string digestOID) { AddSigner(privateKey, cert, GetEncOid(privateKey, digestOID), digestOID); }
/** * Verify the signature against the TBSRequest object we contain. */ public bool Verify( IAsymmetricKeyParameter publicKey) { if (!this.IsSigned) { throw new OcspException("attempt to Verify signature on unsigned object"); } try { ISigner signature = SignerUtilities.GetSigner(this.SignatureAlgOid); signature.Init(false, publicKey); byte[] encoded = req.TbsRequest.GetEncoded(); signature.BlockUpdate(encoded, 0, encoded.Length); return(signature.VerifySignature(this.GetSignature())); } catch (Exception e) { throw new OcspException("exception processing sig: " + e, e); } }
/// <summary> /// Generate a new X509Certificate specifying a SecureRandom instance that you would like to use. /// </summary> /// <param name="privateKey">The private key of the issuer used to sign this certificate.</param> /// <param name="random">The Secure Random you want to use.</param> /// <returns>An X509Certificate.</returns> public X509Certificate Generate( IAsymmetricKeyParameter privateKey, SecureRandom random) { TbsCertificateStructure tbsCert = tbsGen.GenerateTbsCertificate(); byte[] signature; try { signature = X509Utilities.GetSignatureForObject( sigOID, signatureAlgorithm, privateKey, random, tbsCert); } catch (Exception e) { // TODO // throw new ExtCertificateEncodingException("exception encoding TBS cert", e); throw new CertificateEncodingException("exception encoding TBS cert", e); } try { return GenerateJcaObject(tbsCert, signature); } catch (CertificateParsingException e) { // TODO // throw new ExtCertificateEncodingException("exception producing certificate object", e); throw new CertificateEncodingException("exception producing certificate object", e); } }
private void VerifyECMqvKeyAgreeVectors( IAsymmetricKeyParameter privKey, string wrapAlg, byte[] message) { byte[] data = Hex.Decode("504b492d4320434d5320456e76656c6f706564446174612053616d706c65"); CmsEnvelopedData ed = new CmsEnvelopedData(message); RecipientInformationStore recipients = ed.GetRecipientInfos(); ICollection c = recipients.GetRecipients(); Assert.AreEqual(wrapAlg, ed.EncryptionAlgOid); Assert.AreEqual(1, c.Count); foreach (RecipientInformation recipient in c) { Assert.AreEqual("1.3.133.16.840.63.0.16", recipient.KeyEncryptionAlgOid); byte[] recData = recipient.GetContent(privKey); Assert.IsTrue(Arrays.AreEqual(data, recData)); } }
internal SignerInfoGeneratorImpl( CmsSignedDataStreamGenerator outer, IAsymmetricKeyParameter key, SignerIdentifier signerIdentifier, string digestOID, string encOID, CmsAttributeTableGenerator sAttr, CmsAttributeTableGenerator unsAttr) { this.outer = outer; _signerIdentifier = signerIdentifier; _digestOID = digestOID; _encOID = encOID; _sAttr = sAttr; _unsAttr = unsAttr; _encName = Helper.GetEncryptionAlgName(_encOID); string digestName = Helper.GetDigestAlgName(_digestOID); string signatureName = digestName + "with" + _encName; if (_sAttr != null) { _sig = Helper.GetSignatureInstance(signatureName); } else { // Note: Need to use raw signatures here since we have already calculated the digest if (_encName.Equals("RSA")) { _sig = Helper.GetSignatureInstance("RSA"); } else if (_encName.Equals("DSA")) { _sig = Helper.GetSignatureInstance("NONEwithDSA"); } // TODO Add support for raw PSS // else if (_encName.equals("RSAandMGF1")) // { // _sig = CMSSignedHelper.INSTANCE.getSignatureInstance("NONEWITHRSAPSS", _sigProvider); // try // { // // Init the params this way to avoid having a 'raw' version of each PSS algorithm // Signature sig2 = CMSSignedHelper.INSTANCE.getSignatureInstance(signatureName, _sigProvider); // PSSParameterSpec spec = (PSSParameterSpec)sig2.getParameters().getParameterSpec(PSSParameterSpec.class); // _sig.setParameter(spec); // } // catch (Exception e) // { // throw new SignatureException("algorithm: " + _encName + " could not be configured."); // } // } else { throw new SignatureException("algorithm: " + _encName + " not supported in base signatures."); } } _sig.Init(true, new ParametersWithRandom(key, outer.rand)); }
public void TestRfc4134Ex5_1() { byte[] data = Hex.Decode("5468697320697320736f6d652073616d706c6520636f6e74656e742e"); // KeyFactory kFact = KeyFactory.GetInstance("RSA"); // Key key = kFact.generatePrivate(new PKCS8EncodedKeySpec(bobPrivRsaEncrypt)); IAsymmetricKeyParameter key = PrivateKeyFactory.CreateKey(bobPrivRsaEncrypt); CmsEnvelopedData ed = new CmsEnvelopedData(rfc4134ex5_1); RecipientInformationStore recipients = ed.GetRecipientInfos(); Assert.AreEqual("1.2.840.113549.3.7", ed.EncryptionAlgOid); ICollection c = recipients.GetRecipients(); Assert.AreEqual(1, c.Count); foreach (RecipientInformation recipient in c) { byte[] recData = recipient.GetContent(key); Assert.IsTrue(Arrays.AreEqual(data, recData)); } }
internal KeyParameter GetSessionKey( IAsymmetricKeyParameter receiverPrivateKey) { try { string wrapAlg = DerObjectIdentifier.GetInstance( Asn1Sequence.GetInstance(keyEncAlg.Parameters)[0]).Id; IAsymmetricKeyParameter senderPublicKey = GetSenderPublicKey( receiverPrivateKey, info.Originator); KeyParameter agreedWrapKey = CalculateAgreedWrapKey(wrapAlg, senderPublicKey, receiverPrivateKey); return(UnwrapSessionKey(wrapAlg, agreedWrapKey)); } catch (SecurityUtilityException e) { throw new CmsException("couldn't create cipher.", e); } catch (InvalidKeyException e) { throw new CmsException("key invalid in message.", e); } catch (Exception e) { throw new CmsException("originator key invalid.", e); } }
public virtual bool VerifyRawSignature(byte[] sigBytes, IAsymmetricKeyParameter publicKey, byte[] md5andsha1) { ISigner s = MakeSigner(new NullDigest(), false, publicKey); s.BlockUpdate(md5andsha1, 0, md5andsha1.Length); return s.VerifySignature(sigBytes); }
public virtual byte[] CalculateRawSignature(SecureRandom random, IAsymmetricKeyParameter privateKey, byte[] md5andsha1) { ISigner s = MakeSigner(new NullDigest(), true, new ParametersWithRandom(privateKey, random)); s.BlockUpdate(md5andsha1, 0, md5andsha1.Length); return s.GenerateSignature(); }
private IAsymmetricKeyParameter GetSenderPublicKey( IAsymmetricKeyParameter receiverPrivateKey, OriginatorIdentifierOrKey originator) { OriginatorPublicKey opk = originator.OriginatorPublicKey; if (opk != null) { return(GetPublicKeyFromOriginatorPublicKey(receiverPrivateKey, opk)); } OriginatorID origID = new OriginatorID(); Asn1.Cms.IssuerAndSerialNumber iAndSN = originator.IssuerAndSerialNumber; if (iAndSN != null) { origID.Issuer = iAndSN.Name; origID.SerialNumber = iAndSN.SerialNumber.Value; } else { SubjectKeyIdentifier ski = originator.SubjectKeyIdentifier; origID.SubjectKeyIdentifier = ski.GetKeyIdentifier(); } return(GetPublicKeyFromOriginatorID(origID)); }
/// <summary> /// Create a PgpPrivateKey from a regular private key and the ID of its /// associated public key. /// </summary> /// <param name="privateKey">Private key to use.</param> /// <param name="keyId">ID of the corresponding public key.</param> public PgpPrivateKey(IAsymmetricKeyParameter privateKey, long keyId) { if (!privateKey.IsPrivate) throw new ArgumentException(@"Expected a private key", "privateKey"); _privateKey = privateKey; _keyId = keyId; }
public virtual byte[] CalculateRawSignature(SecureRandom random, IAsymmetricKeyParameter privateKey, byte[] md5andsha1) { ISigner s = MakeSigner(new NullDigest(), true, new ParametersWithRandom(privateKey, random)); // Note: Only use the SHA1 part of the hash s.BlockUpdate(md5andsha1, 16, 20); return s.GenerateSignature(); }
/** * basic creation - only the default attributes will be included here. */ public TimeStampTokenGenerator( IAsymmetricKeyParameter key, X509Certificate cert, string digestOID, string tsaPolicyOID) : this(key, cert, digestOID, tsaPolicyOID, null, null) { }
public bool VerifyRawSignature(byte[] sigBytes, IAsymmetricKeyParameter publicKey, byte[] md5andsha1) { ISigner s = MakeSigner(new NullDigest(), false, publicKey); // Note: Only use the SHA1 part of the hash s.BlockUpdate(md5andsha1, 16, 20); return(s.VerifySignature(sigBytes)); }
public PgpKeyPair( PublicKeyAlgorithmTag algorithm, IAsymmetricKeyParameter pubKey, IAsymmetricKeyParameter privKey, DateTime time) { this.pub = new PgpPublicKey(algorithm, pubKey, time); this.priv = new PgpPrivateKey(privKey, pub.KeyId); }
/// <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, IAsymmetricKeyParameter pubKey, DateTime time) { if (pubKey.IsPrivate) throw new ArgumentException(@"Expected a public key", "pubKey"); IBcpgPublicKey bcpgKey; if (pubKey is RsaKeyParameters) { var rK = (RsaKeyParameters)pubKey; bcpgKey = new RsaPublicBcpgKey(rK.Modulus, rK.Exponent); } else if (pubKey is DsaPublicKeyParameters) { var dK = (DsaPublicKeyParameters)pubKey; var dP = dK.Parameters; bcpgKey = new DsaPublicBcpgKey(dP.P, dP.Q, dP.G, dK.Y); } else if (pubKey is ElGamalPublicKeyParameters) { var eK = (ElGamalPublicKeyParameters)pubKey; var eS = eK.Parameters; bcpgKey = new ElGamalPublicBcpgKey(eS.P, eS.G, eK.Y); } else if (pubKey is ECDHPublicKeyParameters) { var ecdh = (ECDHPublicKeyParameters)pubKey; bcpgKey = new ECDHPublicBcpgKey(ecdh.Q, ecdh.PublicKeyParamSet, ecdh.HashAlgorithm, ecdh.SymmetricKeyAlgorithm); } else if (pubKey is ECPublicKeyParameters) { var ecdsa = (ECPublicKeyParameters)pubKey; bcpgKey = new ECDSAPublicBcpgKey(ecdsa.Q, ecdsa.PublicKeyParamSet); } else { throw new PgpException("unknown key class"); } _publicPk = new PublicKeyPacket(algorithm, time, bcpgKey); _ids = Platform.CreateArrayList(); _idSigs = Platform.CreateArrayList<IList<IPgpSignature>>(); try { Init(); } catch (IOException e) { throw new PgpException("exception calculating keyId", e); } }
/** * basic constructor. * * @param publicParam a public key parameters object. * @param privateParam the corresponding private key parameters. */ public AsymmetricCipherKeyPair(IAsymmetricKeyParameter publicParameter, IAsymmetricKeyParameter privateParameter) { if (publicParameter.IsPrivate) throw new ArgumentException(@"Expected a public key", "publicParameter"); if (!privateParameter.IsPrivate) throw new ArgumentException(@"Expected a private key", "privateParameter"); _publicParameter = publicParameter; _privateParameter = privateParameter; }
public static EncryptedPrivateKeyInfo CreateEncryptedPrivateKeyInfo( string algorithm, char[] passPhrase, byte[] salt, int iterationCount, IAsymmetricKeyParameter key) { return CreateEncryptedPrivateKeyInfo( algorithm, passPhrase, salt, iterationCount, PrivateKeyInfoFactory.CreatePrivateKeyInfo(key)); }
public PkixCertPathBuilderResult( PkixCertPath certPath, TrustAnchor trustAnchor, PkixPolicyNode policyTree, IAsymmetricKeyParameter subjectPublicKey) : base(trustAnchor, policyTree, subjectPublicKey) { if (certPath == null) throw new ArgumentNullException("certPath"); this.certPath = certPath; }
/** * create with a signer with extra signed/unsigned attributes. */ public TimeStampTokenGenerator( IAsymmetricKeyParameter key, X509Certificate cert, string digestOID, string tsaPolicyOID, Asn1.Cms.AttributeTable signedAttr, Asn1.Cms.AttributeTable unsignedAttr) { this.key = key; this.cert = cert; this.digestOID = digestOID; this.tsaPolicyOID = tsaPolicyOID; this.unsignedAttr = unsignedAttr; TspUtil.ValidateCertificate(cert); // // Add the ESSCertID attribute // IDictionary signedAttrs; if (signedAttr != null) { signedAttrs = signedAttr.ToDictionary(); } else { signedAttrs = Platform.CreateHashtable(); } try { byte[] hash = DigestUtilities.CalculateDigest("SHA-1", cert.GetEncoded()); EssCertID essCertid = new EssCertID(hash); Asn1.Cms.Attribute attr = new Asn1.Cms.Attribute( PkcsObjectIdentifiers.IdAASigningCertificate, new DerSet(new SigningCertificate(essCertid))); signedAttrs[attr.AttrType] = attr; } catch (CertificateEncodingException e) { throw new TspException("Exception processing certificate.", e); } catch (SecurityUtilityException e) { throw new TspException("Can't find a SHA-1 implementation.", e); } this.signedAttr = new Asn1.Cms.AttributeTable(signedAttrs); }
private static Asn1OctetString FromPublicKey( IAsymmetricKeyParameter pubKey) { try { SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pubKey); return (Asn1OctetString) new SubjectKeyIdentifier(info).ToAsn1Object(); } catch (Exception e) { throw new CertificateParsingException("Exception extracting certificate details: " + e.ToString()); } }
public PgpSecretKey( int certificationLevel, PublicKeyAlgorithmTag algorithm, IAsymmetricKeyParameter pubKey, IAsymmetricKeyParameter privKey, DateTime time, string id, SymmetricKeyAlgorithmTag encAlgorithm, char[] passPhrase, bool useSha1, PgpSignatureSubpacketVector hashedPackets, PgpSignatureSubpacketVector unhashedPackets, SecureRandom rand) : this(certificationLevel, new PgpKeyPair(algorithm, pubKey, privKey, time), id, encAlgorithm, passPhrase, useSha1, hashedPackets, unhashedPackets, rand) { }
public RespID( IAsymmetricKeyParameter publicKey) { try { SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey); byte[] keyHash = DigestUtilities.CalculateDigest("SHA1", info.PublicKeyData.GetBytes()); this.id = new ResponderID(new DerOctetString(keyHash)); } catch (Exception e) { throw new OcspException("problem creating ID: " + e, e); } }
private static void ExportKeyPair( Stream secretOut, Stream publicOut, IAsymmetricKeyParameter publicKey, IAsymmetricKeyParameter privateKey, string identity, char[] passPhrase, bool armor) { if (armor) { secretOut = new ArmoredOutputStream(secretOut); } PgpSecretKey secretKey = new PgpSecretKey( PgpSignature.DefaultCertification, PublicKeyAlgorithmTag.RsaGeneral, publicKey, privateKey, DateTime.UtcNow, identity, SymmetricKeyAlgorithmTag.Cast5, passPhrase, null, null, new SecureRandom() ); secretKey.Encode(secretOut); if (armor) { secretOut.Close(); publicOut = new ArmoredOutputStream(publicOut); } IPgpPublicKey key = secretKey.PublicKey; key.Encode(publicOut); if (armor) { publicOut.Close(); } }
public PkixCertPathValidatorResult( TrustAnchor trustAnchor, PkixPolicyNode policyTree, IAsymmetricKeyParameter subjectPublicKey) { if (subjectPublicKey == null) { throw new NullReferenceException("subjectPublicKey must be non-null"); } if (trustAnchor == null) { throw new NullReferenceException("trustAnchor must be non-null"); } this.trustAnchor = trustAnchor; this.policyTree = policyTree; this.subjectPublicKey = subjectPublicKey; }
public DefaultTlsSignerCredentials(TlsClientContext context, Certificate clientCertificate, IAsymmetricKeyParameter clientPrivateKey) { if (clientCertificate == null) { throw new ArgumentNullException("clientCertificate"); } if (clientCertificate.certs.Length == 0) { throw new ArgumentException(@"cannot be empty", "clientCertificate"); } if (clientPrivateKey == null) { throw new ArgumentNullException("clientPrivateKey"); } if (!clientPrivateKey.IsPrivate) { throw new ArgumentException(@"must be private", "clientPrivateKey"); } if (clientPrivateKey is RsaKeyParameters) { clientSigner = new TlsRsaSigner(); } else if (clientPrivateKey is DsaPrivateKeyParameters) { clientSigner = new TlsDssSigner(); } else if (clientPrivateKey is ECPrivateKeyParameters) { clientSigner = new TlsECDsaSigner(); } else { throw new ArgumentException("type not supported: " + clientPrivateKey.GetType().FullName, "clientPrivateKey"); } this.context = context; this.clientCert = clientCertificate; this.clientPrivateKey = clientPrivateKey; }
static TspTest() { string signDN = "O=Bouncy Castle, C=AU"; IAsymmetricCipherKeyPair signKP = TspTestUtil.MakeKeyPair(); X509Certificate signCert = TspTestUtil.MakeCACertificate(signKP, signDN, signKP, signDN); string origDN = "CN=Eric H. Echidna, [email protected], O=Bouncy Castle, C=AU"; IAsymmetricCipherKeyPair origKP = TspTestUtil.MakeKeyPair(); privateKey = origKP.Private; cert = TspTestUtil.MakeCertificate(origKP, origDN, signKP, signDN); IList certList = new ArrayList(); certList.Add(cert); certList.Add(signCert); certs = X509StoreFactory.Create( "Certificate/Collection", new X509CollectionStoreParameters(certList)); }
public static X509Crl CreateCrl( X509Certificate caCert, IAsymmetricKeyParameter caKey, IBigInteger serialNumber) { X509V2CrlGenerator crlGen = new X509V2CrlGenerator(); DateTime now = DateTime.UtcNow; // BigInteger revokedSerialNumber = BigInteger.Two; crlGen.SetIssuerDN(PrincipalUtilities.GetSubjectX509Principal(caCert)); crlGen.SetThisUpdate(now); crlGen.SetNextUpdate(now.AddSeconds(100)); crlGen.SetSignatureAlgorithm("SHA256WithRSAEncryption"); crlGen.AddCrlEntry(serialNumber, now, CrlReason.PrivilegeWithdrawn); crlGen.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert)); crlGen.AddExtension(X509Extensions.CrlNumber, false, new CrlNumber(BigInteger.One)); return crlGen.Generate(caKey); }
public static X509Certificate GenerateIntermediateCert( IAsymmetricKeyParameter intKey, IAsymmetricKeyParameter caKey, X509Certificate caCert) { X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.SetSerialNumber(BigInteger.One); certGen.SetIssuerDN(PrincipalUtilities.GetSubjectX509Principal(caCert)); certGen.SetNotBefore(DateTime.UtcNow.AddSeconds(-50)); certGen.SetNotAfter(DateTime.UtcNow.AddSeconds(50)); certGen.SetSubjectDN(new X509Name("CN=Test Intermediate Certificate")); certGen.SetPublicKey(intKey); certGen.SetSignatureAlgorithm("SHA256WithRSAEncryption"); certGen.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert)); certGen.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(intKey)); certGen.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(0)); certGen.AddExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.DigitalSignature | KeyUsage.KeyCertSign | KeyUsage.CrlSign)); return certGen.Generate(caKey); }
public DefaultTlsAgreementCredentials(Certificate clientCertificate, IAsymmetricKeyParameter clientPrivateKey) { if (clientCertificate == null) { throw new ArgumentNullException("clientCertificate"); } if (clientCertificate.certs.Length == 0) { throw new ArgumentException(@"cannot be empty", "clientCertificate"); } if (clientPrivateKey == null) { throw new ArgumentNullException("clientPrivateKey"); } if (!clientPrivateKey.IsPrivate) { throw new ArgumentException(@"must be private", "clientPrivateKey"); } if (clientPrivateKey is DHPrivateKeyParameters) { basicAgreement = new DHBasicAgreement(); } else if (clientPrivateKey is ECPrivateKeyParameters) { basicAgreement = new ECDHBasicAgreement(); } else { throw new ArgumentException("type not supported: " + clientPrivateKey.GetType().FullName, "clientPrivateKey"); } this.clientCert = clientCertificate; this.clientPrivateKey = clientPrivateKey; }
/** * Verify the signature against the TBSRequest object we contain. */ public bool Verify( IAsymmetricKeyParameter publicKey) { if (!this.IsSigned) throw new OcspException("attempt to Verify signature on unsigned object"); try { ISigner signature = SignerUtilities.GetSigner(this.SignatureAlgOid); signature.Init(false, publicKey); byte[] encoded = req.TbsRequest.GetEncoded(); signature.BlockUpdate(encoded, 0, encoded.Length); return signature.VerifySignature(this.GetSignature()); } catch (Exception e) { throw new OcspException("exception processing sig: " + e, e); } }
protected string GetEncOid( IAsymmetricKeyParameter key, string digestOID) { string encOID = null; if (key is RsaKeyParameters) { if (!((RsaKeyParameters) key).IsPrivate) throw new ArgumentException("Expected RSA private key"); encOID = EncryptionRsa; } else if (key is DsaPrivateKeyParameters) { if (!digestOID.Equals(DigestSha1)) throw new ArgumentException("can't mix DSA with anything but SHA1"); encOID = EncryptionDsa; } else if (key is ECPrivateKeyParameters) { ECPrivateKeyParameters ecPrivKey = (ECPrivateKeyParameters) key; string algName = ecPrivKey.AlgorithmName; if (algName == "ECGOST3410") { encOID = EncryptionECGost3410; } else { // TODO Should we insist on algName being one of "EC" or "ECDSA", as Java does? encOID = (string) ecAlgorithms[digestOID]; if (encOID == null) throw new ArgumentException("can't mix ECDSA with anything but SHA family digests"); } } else if (key is Gost3410PrivateKeyParameters) { encOID = EncryptionGost3410; } else { throw new ArgumentException("Unknown algorithm in CmsSignedGenerator.GetEncOid"); } return encOID; }