private OcspReq GenerateOcspRequest(CertificateID id) { OcspReqGenerator ocspRequestGenerator = new OcspReqGenerator(); ocspRequestGenerator.AddRequest(id); BigInteger nonce = BigInteger.ValueOf(new DateTime().Ticks); ArrayList oids = new ArrayList(); Hashtable values = new Hashtable(); oids.Add(OcspObjectIdentifiers.PkixOcsp); Asn1OctetString asn1 = new DerOctetString(new DerOctetString(new byte[] { 1, 3, 6, 1, 5, 5, 7, 48, 1, 1 })); values.Add(OcspObjectIdentifiers.PkixOcsp, new X509Extension(false, asn1)); ocspRequestGenerator.SetRequestExtensions(new X509Extensions(oids, values)); return ocspRequestGenerator.Generate(); }
public override void PerformTest() { int dataGroupNumber = 1; Asn1OctetString dataHash = new DerOctetString(GenerateHash()); DataGroupHash dg = new DataGroupHash(dataGroupNumber, dataHash); CheckConstruction(dg, dataGroupNumber, dataHash); try { DataGroupHash.GetInstance(null); } catch (Exception) { Fail("GetInstance() failed to handle null."); } try { DataGroupHash.GetInstance(new object()); Fail("GetInstance() failed to detect bad object."); } catch (ArgumentException) { // expected } }
public const int Unauthorized = 6; // Request unauthorized public OcspResp Generate( int status, object response) { if (response == null) { return new OcspResp(new OcspResponse(new OcspResponseStatus(status),null)); } if (response is BasicOcspResp) { BasicOcspResp r = (BasicOcspResp)response; Asn1OctetString octs; try { octs = new DerOctetString(r.GetEncoded()); } catch (Exception e) { throw new OcspException("can't encode object.", e); } ResponseBytes rb = new ResponseBytes( OcspObjectIdentifiers.PkixOcspBasic, octs); return new OcspResp(new OcspResponse( new OcspResponseStatus(status), rb)); } throw new OcspException("unknown response object"); }
public static string GetAuthorityKeyFromCertificate(X509Certificate2 certificate) { try { foreach (var extension in certificate.Extensions.Cast<X509Extension>() .Where(extension => extension.Oid.Value.Equals(AuthorityKeyOid))) { using (var asnStream = new Asn1InputStream(extension.RawData)) { var asnObject = asnStream.ReadObject(); var taggedObject = new DerTaggedObject(0, asnObject); var authorityKey = AuthorityKeyIdentifier.GetInstance(taggedObject, true); var octetString = new DerOctetString(authorityKey.GetKeyIdentifier()); return NormalizeOctetString(octetString.ToString()); } } return ""; } catch (Exception e) { Log.WarnFormat("An issue occurred while attempting to extract the authority key from a certificate: {0}", e.Message); return ""; } }
public RecipientInfo Generate(KeyParameter contentEncryptionKey, SecureRandom random) { byte[] keyBytes = contentEncryptionKey.GetKey(); string rfc3211WrapperName = Helper.GetRfc3211WrapperName(keyEncryptionKeyOID); IWrapper keyWrapper = Helper.CreateWrapper(rfc3211WrapperName); // Note: In Java build, the IV is automatically generated in JCE layer int ivLength = Platform.StartsWith(rfc3211WrapperName, "DESEDE") ? 8 : 16; byte[] iv = new byte[ivLength]; random.NextBytes(iv); ICipherParameters parameters = new ParametersWithIV(keyEncryptionKey, iv); keyWrapper.Init(true, new ParametersWithRandom(parameters, random)); Asn1OctetString encryptedKey = new DerOctetString( keyWrapper.Wrap(keyBytes, 0, keyBytes.Length)); DerSequence seq = new DerSequence( new DerObjectIdentifier(keyEncryptionKeyOID), new DerOctetString(iv)); AlgorithmIdentifier keyEncryptionAlgorithm = new AlgorithmIdentifier( PkcsObjectIdentifiers.IdAlgPwriKek, seq); return new RecipientInfo(new PasswordRecipientInfo( keyDerivationAlgorithm, keyEncryptionAlgorithm, encryptedKey)); }
public override void PerformTest() { TypeOfBiometricData dataType = new TypeOfBiometricData(TypeOfBiometricData.HandwrittenSignature); AlgorithmIdentifier hashAlgorithm = new AlgorithmIdentifier(OiwObjectIdentifiers.IdSha1, DerNull.Instance); Asn1OctetString dataHash = new DerOctetString(GenerateHash()); BiometricData bd = new BiometricData(dataType, hashAlgorithm, dataHash); CheckConstruction(bd, dataType, hashAlgorithm, dataHash, null); DerIA5String dataUri = new DerIA5String("http://test"); bd = new BiometricData(dataType, hashAlgorithm, dataHash, dataUri); CheckConstruction(bd, dataType, hashAlgorithm, dataHash, dataUri); bd = BiometricData.GetInstance(null); if (bd != null) { Fail("null GetInstance() failed."); } try { BiometricData.GetInstance(new object()); Fail("GetInstance() failed to detect bad object."); } catch (ArgumentException) { // expected } }
public RecipientInfo Generate(KeyParameter contentEncryptionKey, SecureRandom random) { byte[] keyBytes = contentEncryptionKey.GetKey(); IWrapper keyWrapper = Helper.CreateWrapper(keyEncryptionAlgorithm.Algorithm.Id); keyWrapper.Init(true, new ParametersWithRandom(keyEncryptionKey, random)); Asn1OctetString encryptedKey = new DerOctetString( keyWrapper.Wrap(keyBytes, 0, keyBytes.Length)); return new RecipientInfo(new KekRecipientInfo(kekIdentifier, keyEncryptionAlgorithm, encryptedKey)); }
public override void Write( byte[] buf, int offSet, int len) { byte[] bytes = new byte[len]; Array.Copy(buf, offSet, bytes, 0, len); byte[] encoded = new DerOctetString(bytes).GetEncoded(); _gen.Out.Write(encoded, 0, encoded.Length); }
public override void Write( byte[] buf, int offSet, int len) { byte[] bytes = new byte[len]; Array.Copy(buf, offSet, bytes, 0, len); byte[] encoded = new Asn1.DerOctetString(bytes).GetEncoded(); _gen.Out.Write(encoded, 0, encoded.Length); }
/** * create from an issuer certificate and the serial number of the * certificate it signed. * @exception OcspException if any problems occur creating the id fields. */ public CertificateID( string hashAlgorithm, X509Certificate issuerCert, BigInteger number) { try { IDigest digest = DigestUtilities.GetDigest(hashAlgorithm); AlgorithmIdentifier hashAlg = new AlgorithmIdentifier( new DerObjectIdentifier(hashAlgorithm), DerNull.Instance); X509Name issuerName = PrincipalUtilities.GetSubjectX509Principal(issuerCert); byte[] encodedIssuerName = issuerName.GetEncoded(); digest.BlockUpdate(encodedIssuerName, 0, encodedIssuerName.Length); byte[] hash = DigestUtilities.DoFinal(digest); Asn1OctetString issuerNameHash = new DerOctetString(hash); AsymmetricKeyParameter issuerKey = issuerCert.GetPublicKey(); SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(issuerKey); byte[] encodedPublicKey = info.PublicKeyData.GetBytes(); digest.BlockUpdate(encodedPublicKey, 0, encodedPublicKey.Length); hash = DigestUtilities.DoFinal(digest); Asn1OctetString issuerKeyHash = new DerOctetString(hash); DerInteger serialNumber = new DerInteger(number); this.id = new CertID(hashAlg, issuerNameHash, issuerKeyHash, serialNumber); } catch (Exception e) { throw new OcspException("problem creating ID: " + e, e); } }
public RespID( AsymmetricKeyParameter publicKey) { try { IDigest digest = DigestUtilities.GetDigest("SHA1"); SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey); byte[] encoded = info.PublicKeyData.GetBytes(); digest.BlockUpdate(encoded, 0, encoded.Length); byte[] hash = DigestUtilities.DoFinal(digest); Asn1OctetString keyHash = new DerOctetString(hash); this.id = new ResponderID(keyHash); } catch (Exception e) { throw new OcspException("problem creating ID: " + e, e); } }
internal Asn1.Cms.SignerInfo ToSignerInfo( DerObjectIdentifier contentType, CmsProcessable content, SecureRandom random, bool isCounterSignature) { AlgorithmIdentifier digAlgId = new AlgorithmIdentifier( new DerObjectIdentifier(this.DigestAlgOid), DerNull.Instance); AlgorithmIdentifier encAlgId = CmsSignedGenerator.GetEncAlgorithmIdentifier(this.EncryptionAlgOid); string digestName = Helper.GetDigestAlgName(digestOID); string signatureName = digestName + "with" + Helper.GetEncryptionAlgName(encOID); ISigner sig = Helper.GetSignatureInstance(signatureName); IDigest dig = Helper.GetDigestInstance(digestName); byte[] hash = null; if (content != null) { content.Write(new DigOutputStream(dig)); hash = DigestUtilities.DoFinal(dig); outer._digests.Add(digestOID, hash.Clone()); } IDictionary parameters = outer.GetBaseParameters(contentType, digAlgId, hash); Asn1.Cms.AttributeTable signed = (sAttr != null) // ? sAttr.GetAttributes(Collections.unmodifiableMap(parameters)) ? sAttr.GetAttributes(parameters) : null; if (isCounterSignature) { Hashtable ats = signed.ToHashtable(); ats.Remove(CmsAttributes.ContentType); signed = new Asn1.Cms.AttributeTable(ats); } Asn1Set signedAttr = outer.GetAttributeSet(signed); // // sig must be composed from the DER encoding. // byte[] tmp; if (signedAttr != null) { tmp = signedAttr.GetEncoded(Asn1Encodable.Der); } else { MemoryStream bOut = new MemoryStream(); content.Write(bOut); tmp = bOut.ToArray(); } sig.Init(true, new ParametersWithRandom(key, random)); sig.BlockUpdate(tmp, 0, tmp.Length); Asn1OctetString encDigest = new DerOctetString(sig.GenerateSignature()); IDictionary baseParameters = outer.GetBaseParameters(contentType, digAlgId, hash); baseParameters[CmsAttributeTableParameter.Signature] = encDigest.GetOctets().Clone(); Asn1.Cms.AttributeTable unsigned = (unsAttr != null) // ? unsAttr.GetAttributes(Collections.unmodifiableMap(baseParameters)) ? unsAttr.GetAttributes(baseParameters) : null; Asn1Set unsignedAttr = outer.GetAttributeSet(unsigned); X509Certificate cert = this.GetCertificate(); SignerIdentifier identifier; if (cert != null) { TbsCertificateStructure tbs = TbsCertificateStructure.GetInstance( Asn1Object.FromByteArray(cert.GetTbsCertificate())); Asn1.Cms.IssuerAndSerialNumber encSid = new Asn1.Cms.IssuerAndSerialNumber( tbs.Issuer, tbs.SerialNumber.Value); identifier = new SignerIdentifier(encSid); } else { identifier = new SignerIdentifier(new DerOctetString(keyIdentifier)); } return new Asn1.Cms.SignerInfo(identifier, digAlgId, signedAttr, encAlgId, encDigest, unsignedAttr); }
public static byte[] PostSign(String digestAlgorithmName, byte[] content, X509Certificate2[] signerCertificateChain, byte[] signature, byte[] signedAttributes) { if (signerCertificateChain == null || signerCertificateChain.Length == 0) { throw new ArgumentException("La cadena de certificados debe contener al menos una entrada"); } TbsCertificateStructure tbsCertificateStructure; //TODO Revisar esta parte del código /** * * Revisar esta parte del código * */ tbsCertificateStructure = TbsCertificateStructure.GetInstance( Asn1Object.FromByteArray( new Org.BouncyCastle.X509.X509Certificate( X509CertificateStructure.GetInstance(Asn1Object.FromByteArray(signerCertificateChain[0].GetRawCertData()))).GetTbsCertificate() ) ); SignerIdentifier signerIdentifier = new SignerIdentifier( new IssuerAndSerialNumber(X509Name.GetInstance(tbsCertificateStructure.Issuer), tbsCertificateStructure.SerialNumber) ); // Algoritmo de huella digital AlgorithmIdentifier digestAlgorithmOID; digestAlgorithmOID = SigUtils.MakeAlgId(AOAlgorithmID.GetOID(digestAlgorithmName)); // EncryptionAlgorithm AlgorithmIdentifier keyAlgorithmIdentifier; keyAlgorithmIdentifier = SigUtils.MakeAlgId(AOAlgorithmID.GetOID("RSA")); // Firma PKCS#1 codificada Asn1OctetString encodedPKCS1Signature = new DerOctetString(signature); // Atributos firmados Asn1Set asn1SignedAttributes; asn1SignedAttributes = (Asn1Set) Asn1Object.FromByteArray(signedAttributes); // SignerInfo Asn1EncodableVector signerInfo = new Asn1EncodableVector(); signerInfo.Add(new SignerInfo(signerIdentifier, digestAlgorithmOID, asn1SignedAttributes, keyAlgorithmIdentifier, encodedPKCS1Signature, null)); // ContentInfo ContentInfo contentInfo; if (content != null) { MemoryStream baos = new MemoryStream(); CmsProcessable msg = new CmsProcessableByteArray(content); msg.Write(baos); contentInfo = new ContentInfo(new DerObjectIdentifier(Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.Data.Id), new BerOctetString(baos.ToArray())); } else { contentInfo = new ContentInfo(new DerObjectIdentifier(Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.Data.Id), null); } // Certificados List<Asn1Encodable> ce = new List<Asn1Encodable>(); foreach (X509Certificate2 cert in signerCertificateChain) { /** * * Revisar el uso que hacemos de X509CertificateStructure * ya que puede ser un posible punto de errores * */ ce.Add(X509CertificateStructure.GetInstance(Asn1Object.FromByteArray(cert.GetRawCertData()))); } Asn1Set certificates = SigUtils.CreateBerSetFromList(ce); // Algoritmos de huella digital Asn1EncodableVector digestAlgorithms = new Asn1EncodableVector(); digestAlgorithms.Add(digestAlgorithmOID); return new ContentInfo( Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.SignedData, new SignedData( new DerSet(digestAlgorithms), contentInfo, certificates, null, new DerSet(signerInfo) ) ).GetEncoded("DER"); }
public AttributeTable GetAttributes( IDictionary parameters) { DerOctetString val = new DerOctetString((byte[])parameters[CmsAttributeTableParameter.Signature]); Asn1.Cms.Attribute attr = new Asn1.Cms.Attribute(dummyOid2, new DerSet(val)); return new AttributeTable(new DerSet(attr)); }
public override AttributeTable GetAttributes( IDictionary parameters) { IDictionary table = createStandardAttributeTable(parameters); DerOctetString val = new DerOctetString((byte[])parameters[CmsAttributeTableParameter.Digest]); Asn1.Cms.Attribute attr = new Asn1.Cms.Attribute(dummyOid1, new DerSet(val)); table[attr.AttrType] = attr; return new AttributeTable(table); }
public RecipientInfo Generate(KeyParameter contentEncryptionKey, SecureRandom random) { byte[] keyBytes = contentEncryptionKey.GetKey(); IAsymmetricKeyParameter senderPublicKey = senderKeyPair.Public; ICipherParameters senderPrivateParams = senderKeyPair.Private; OriginatorIdentifierOrKey originator; try { originator = new OriginatorIdentifierOrKey( CreateOriginatorPublicKey(senderPublicKey)); } catch (IOException e) { throw new InvalidKeyException("cannot extract originator public key: " + e); } Asn1OctetString ukm = null; if (keyAgreementOID.Id.Equals(CmsEnvelopedGenerator.ECMqvSha1Kdf)) { try { IAsymmetricCipherKeyPairGenerator ephemKPG = GeneratorUtilities.GetKeyPairGenerator(keyAgreementOID); ephemKPG.Init( ((ECPublicKeyParameters)senderPublicKey).CreateKeyGenerationParameters(random)); IAsymmetricCipherKeyPair ephemKP = ephemKPG.GenerateKeyPair(); ukm = new DerOctetString( new MQVuserKeyingMaterial( CreateOriginatorPublicKey(ephemKP.Public), null)); senderPrivateParams = new MqvPrivateParameters( (ECPrivateKeyParameters)senderPrivateParams, (ECPrivateKeyParameters)ephemKP.Private, (ECPublicKeyParameters)ephemKP.Public); } catch (IOException e) { throw new InvalidKeyException("cannot extract MQV ephemeral public key: " + e); } catch (SecurityUtilityException e) { throw new InvalidKeyException("cannot determine MQV ephemeral key pair parameters from public key: " + e); } } DerSequence paramSeq = new DerSequence( keyEncryptionOID, DerNull.Instance); AlgorithmIdentifier keyEncAlg = new AlgorithmIdentifier(keyAgreementOID, paramSeq); Asn1EncodableVector recipientEncryptedKeys = new Asn1EncodableVector(); foreach (X509Certificate recipientCert in recipientCerts) { TbsCertificateStructure tbsCert; try { tbsCert = TbsCertificateStructure.GetInstance( Asn1Object.FromByteArray(recipientCert.GetTbsCertificate())); } catch (Exception) { throw new ArgumentException("can't extract TBS structure from certificate"); } // TODO Should there be a SubjectKeyIdentifier-based alternative? IssuerAndSerialNumber issuerSerial = new IssuerAndSerialNumber( tbsCert.Issuer, tbsCert.SerialNumber.Value); KeyAgreeRecipientIdentifier karid = new KeyAgreeRecipientIdentifier(issuerSerial); ICipherParameters recipientPublicParams = recipientCert.GetPublicKey(); if (keyAgreementOID.Id.Equals(CmsEnvelopedGenerator.ECMqvSha1Kdf)) { recipientPublicParams = new MqvPublicParameters( (ECPublicKeyParameters)recipientPublicParams, (ECPublicKeyParameters)recipientPublicParams); } // Use key agreement to choose a wrap key for this recipient IBasicAgreement keyAgreement = AgreementUtilities.GetBasicAgreementWithKdf( keyAgreementOID, keyEncryptionOID.Id); keyAgreement.Init(new ParametersWithRandom(senderPrivateParams, random)); IBigInteger agreedValue = keyAgreement.CalculateAgreement(recipientPublicParams); int keyEncryptionKeySize = GeneratorUtilities.GetDefaultKeySize(keyEncryptionOID) / 8; byte[] keyEncryptionKeyBytes = X9IntegerConverter.IntegerToBytes(agreedValue, keyEncryptionKeySize); KeyParameter keyEncryptionKey = ParameterUtilities.CreateKeyParameter( keyEncryptionOID, keyEncryptionKeyBytes); // Wrap the content encryption key with the agreement key IWrapper keyWrapper = Helper.CreateWrapper(keyEncryptionOID.Id); keyWrapper.Init(true, new ParametersWithRandom(keyEncryptionKey, random)); byte[] encryptedKeyBytes = keyWrapper.Wrap(keyBytes, 0, keyBytes.Length); Asn1OctetString encryptedKey = new DerOctetString(encryptedKeyBytes); recipientEncryptedKeys.Add(new RecipientEncryptedKey(karid, encryptedKey)); } return new RecipientInfo(new KeyAgreeRecipientInfo(originator, ukm, keyEncAlg, new DerSequence(recipientEncryptedKeys))); }
protected override bool Asn1Equals(Asn1Object asn1Object) { DerOctetString derOctetString = asn1Object as DerOctetString; return(derOctetString != null && Arrays.AreEqual(this.GetOctets(), derOctetString.GetOctets())); }
public override void WriteByte( byte b) { _buf[0] = b; byte[] bytes = new DerOctetString(_buf).GetEncoded(); _gen.Out.Write(bytes, 0, bytes.Length); }
private DerSet GetAuthenticatedAttributeSet(byte[] secondDigest, DateTime signingTime, byte[] ocsp) { Asn1EncodableVector attribute = new Asn1EncodableVector(); Asn1EncodableVector v = new Asn1EncodableVector(); v.Add(new DerObjectIdentifier(ID_CONTENT_TYPE)); v.Add(new DerSet(new DerObjectIdentifier(ID_PKCS7_DATA))); attribute.Add(new DerSequence(v)); v = new Asn1EncodableVector(); v.Add(new DerObjectIdentifier(ID_SIGNING_TIME)); v.Add(new DerSet(new DerUtcTime(signingTime))); attribute.Add(new DerSequence(v)); v = new Asn1EncodableVector(); v.Add(new DerObjectIdentifier(ID_MESSAGE_DIGEST)); v.Add(new DerSet(new DerOctetString(secondDigest))); attribute.Add(new DerSequence(v)); if (ocsp != null) { v = new Asn1EncodableVector(); v.Add(new DerObjectIdentifier(ID_ADBE_REVOCATION)); DerOctetString doctet = new DerOctetString(ocsp); Asn1EncodableVector vo1 = new Asn1EncodableVector(); Asn1EncodableVector v2 = new Asn1EncodableVector(); v2.Add(OcspObjectIdentifiers.PkixOcspBasic); v2.Add(doctet); DerEnumerated den = new DerEnumerated(0); Asn1EncodableVector v3 = new Asn1EncodableVector(); v3.Add(den); v3.Add(new DerTaggedObject(true, 0, new DerSequence(v2))); vo1.Add(new DerSequence(v3)); v.Add(new DerSet(new DerSequence(new DerTaggedObject(true, 1, new DerSequence(vo1))))); attribute.Add(new DerSequence(v)); } return new DerSet(attribute); }
private Asn1Object CreateDERForRecipient(byte[] inp, X509Certificate cert) { String s = "1.2.840.113549.3.2"; byte[] outp = new byte[100]; DerObjectIdentifier derob = new DerObjectIdentifier(s); byte[] keyp = IVGenerator.GetIV(16); IBufferedCipher cf = CipherUtilities.GetCipher(derob); KeyParameter kp = new KeyParameter(keyp); byte[] iv = IVGenerator.GetIV(cf.GetBlockSize()); ParametersWithIV piv = new ParametersWithIV(kp, iv); cf.Init(true, piv); int len = cf.DoFinal(inp, outp, 0); byte[] abyte1 = new byte[len]; System.Array.Copy(outp, 0, abyte1, 0, len); DerOctetString deroctetstring = new DerOctetString(abyte1); KeyTransRecipientInfo keytransrecipientinfo = ComputeRecipientInfo(cert, keyp); DerSet derset = new DerSet(new RecipientInfo(keytransrecipientinfo)); Asn1EncodableVector ev = new Asn1EncodableVector(); ev.Add(new DerInteger(58)); ev.Add(new DerOctetString(iv)); DerSequence seq = new DerSequence(ev); AlgorithmIdentifier algorithmidentifier = new AlgorithmIdentifier(derob, seq); EncryptedContentInfo encryptedcontentinfo = new EncryptedContentInfo(PkcsObjectIdentifiers.Data, algorithmidentifier, deroctetstring); Asn1Set set = null; EnvelopedData env = new EnvelopedData(null, derset, encryptedcontentinfo, set); Org.BouncyCastle.Asn1.Cms.ContentInfo contentinfo = new Org.BouncyCastle.Asn1.Cms.ContentInfo(PkcsObjectIdentifiers.EnvelopedData, env); return contentinfo.ToAsn1Object(); }
public static AsymmetricKeyParameter CreateKey( SubjectPublicKeyInfo 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)) { RsaPublicKeyStructure pubKey = RsaPublicKeyStructure.GetInstance( keyInfo.GetPublicKey()); return new RsaKeyParameters(false, pubKey.Modulus, pubKey.PublicExponent); } else if (algOid.Equals(PkcsObjectIdentifiers.DhKeyAgreement) || algOid.Equals(X9ObjectIdentifiers.DHPublicNumber)) { DHParameter para = new DHParameter( Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object())); DerInteger derY = (DerInteger) keyInfo.GetPublicKey(); BigInteger lVal = para.L; int l = lVal == null ? 0 : lVal.IntValue; DHParameters dhParams = new DHParameters(para.P, para.G, null, l); return new DHPublicKeyParameters(derY.Value, dhParams); } 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 ecP; if (para.IsNamedCurve) { // TODO ECGost3410NamedCurves support (returns ECDomainParameters though) DerObjectIdentifier oid = (DerObjectIdentifier)para.Parameters; ecP = X962NamedCurves.GetByOid(oid); if (ecP == null) { ecP = SecNamedCurves.GetByOid(oid); if (ecP == null) { ecP = NistNamedCurves.GetByOid(oid); if (ecP == null) { ecP = TeleTrusTNamedCurves.GetByOid(oid); } } } } else { ecP = new X9ECParameters((Asn1Sequence)para.Parameters); } ECDomainParameters dParams = new ECDomainParameters( ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed()); DerBitString bits = keyInfo.PublicKeyData; byte[] data = bits.GetBytes(); Asn1OctetString key = new DerOctetString(data); X9ECPoint derQ = new X9ECPoint(dParams.Curve, key); return new ECPublicKeyParameters(derQ.Point, 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), false); return new ECPublicKeyParameters(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); } }
internal RecipientInfo ToRecipientInfo( KeyParameter key, SecureRandom random) { byte[] keyBytes = key.GetKey(); if (pubKey != null) { IWrapper keyWrapper = Helper.CreateWrapper(keyEncAlg.ObjectID.Id); keyWrapper.Init(true, new ParametersWithRandom(pubKey, random)); Asn1OctetString encKey = new DerOctetString( keyWrapper.Wrap(keyBytes, 0, keyBytes.Length)); RecipientIdentifier recipId; if (cert != null) { TbsCertificateStructure tbs = TbsCertificateStructure.GetInstance( Asn1Object.FromByteArray(cert.GetTbsCertificate())); Asn1.Cms.IssuerAndSerialNumber encSid = new Asn1.Cms.IssuerAndSerialNumber( tbs.Issuer, tbs.SerialNumber.Value); recipId = new RecipientIdentifier(encSid); } else { recipId = new RecipientIdentifier(subKeyId); } return new RecipientInfo(new KeyTransRecipientInfo(recipId, keyEncAlg, encKey)); } else if (originator != null) { IWrapper keyWrapper = Helper.CreateWrapper( DerObjectIdentifier.GetInstance( Asn1Sequence.GetInstance(keyEncAlg.Parameters)[0]).Id); keyWrapper.Init(true, new ParametersWithRandom(secKey, random)); Asn1OctetString encKey = new DerOctetString( keyWrapper.Wrap(keyBytes, 0, keyBytes.Length)); RecipientEncryptedKey rKey = new RecipientEncryptedKey( new KeyAgreeRecipientIdentifier( new Asn1.Cms.IssuerAndSerialNumber( PrincipalUtilities.GetIssuerX509Principal(cert), cert.SerialNumber)), encKey); return new RecipientInfo( new KeyAgreeRecipientInfo(originator, ukm, keyEncAlg, new DerSequence(rKey))); } else if (derivationAlg != null) { string rfc3211WrapperName = Helper.GetRfc3211WrapperName(secKeyAlgorithm); IWrapper keyWrapper = Helper.CreateWrapper(rfc3211WrapperName); // Note: In Java build, the IV is automatically generated in JCE layer int ivLength = rfc3211WrapperName.StartsWith("DESEDE") ? 8 : 16; byte[] iv = new byte[ivLength]; random.NextBytes(iv); ICipherParameters parameters = new ParametersWithIV(secKey, iv); keyWrapper.Init(true, new ParametersWithRandom(parameters, random)); Asn1OctetString encKey = new DerOctetString( keyWrapper.Wrap(keyBytes, 0, keyBytes.Length)); // byte[] iv = keyWrapper.GetIV(); DerSequence seq = new DerSequence( new DerObjectIdentifier(secKeyAlgorithm), new DerOctetString(iv)); keyEncAlg = new AlgorithmIdentifier(PkcsObjectIdentifiers.IdAlgPwriKek, seq); return new RecipientInfo(new PasswordRecipientInfo(derivationAlg, keyEncAlg, encKey)); } else { IWrapper keyWrapper = Helper.CreateWrapper(keyEncAlg.ObjectID.Id); keyWrapper.Init(true, new ParametersWithRandom(secKey, random)); Asn1OctetString encKey = new DerOctetString( keyWrapper.Wrap(keyBytes, 0, keyBytes.Length)); return new RecipientInfo(new KekRecipientInfo(secKeyId, keyEncAlg, encKey)); } }
/** * This method provides that encoding and the parameters must be * exactly the same as in {@link #getEncodedPKCS7(byte[],Calendar)}. * * @param secondDigest the content digest * @param signingTime the signing time * @return the byte array representation of the authenticatedAttributes ready to be signed */ private DerSet GetAuthenticatedAttributeSet(byte[] secondDigest, DateTime signingTime, byte[] ocsp, ICollection<byte[]> crlBytes, CryptoStandard sigtype) { Asn1EncodableVector attribute = new Asn1EncodableVector(); Asn1EncodableVector v = new Asn1EncodableVector(); v.Add(new DerObjectIdentifier(SecurityIDs.ID_CONTENT_TYPE)); v.Add(new DerSet(new DerObjectIdentifier(SecurityIDs.ID_PKCS7_DATA))); attribute.Add(new DerSequence(v)); v = new Asn1EncodableVector(); v.Add(new DerObjectIdentifier(SecurityIDs.ID_SIGNING_TIME)); v.Add(new DerSet(new DerUtcTime(signingTime))); attribute.Add(new DerSequence(v)); v = new Asn1EncodableVector(); v.Add(new DerObjectIdentifier(SecurityIDs.ID_MESSAGE_DIGEST)); v.Add(new DerSet(new DerOctetString(secondDigest))); attribute.Add(new DerSequence(v)); bool haveCrl = false; if (crlBytes != null) { foreach (byte[] bCrl in crlBytes) { if (bCrl != null) { haveCrl = true; break; } } } if (ocsp != null || haveCrl) { v = new Asn1EncodableVector(); v.Add(new DerObjectIdentifier(SecurityIDs.ID_ADBE_REVOCATION)); Asn1EncodableVector revocationV = new Asn1EncodableVector(); if (haveCrl) { Asn1EncodableVector v2 = new Asn1EncodableVector(); foreach (byte[] bCrl in crlBytes) { if (bCrl == null) continue; Asn1InputStream t = new Asn1InputStream(bCrl); v2.Add(t.ReadObject()); } revocationV.Add(new DerTaggedObject(true, 0, new DerSequence(v2))); } if (ocsp != null) { DerOctetString doctet = new DerOctetString(ocsp); Asn1EncodableVector vo1 = new Asn1EncodableVector(); Asn1EncodableVector v2 = new Asn1EncodableVector(); v2.Add(OcspObjectIdentifiers.PkixOcspBasic); v2.Add(doctet); DerEnumerated den = new DerEnumerated(0); Asn1EncodableVector v3 = new Asn1EncodableVector(); v3.Add(den); v3.Add(new DerTaggedObject(true, 0, new DerSequence(v2))); vo1.Add(new DerSequence(v3)); revocationV.Add(new DerTaggedObject(true, 1, new DerSequence(vo1))); } v.Add(new DerSet(new DerSequence(revocationV))); attribute.Add(new DerSequence(v)); } if (sigtype == CryptoStandard.CADES) { v = new Asn1EncodableVector(); v.Add(new DerObjectIdentifier(SecurityIDs.ID_AA_SIGNING_CERTIFICATE_V2)); Asn1EncodableVector aaV2 = new Asn1EncodableVector(); AlgorithmIdentifier algoId = new AlgorithmIdentifier(new DerObjectIdentifier(digestAlgorithmOid), null); aaV2.Add(algoId); byte[] dig = DigestAlgorithms.Digest(GetHashAlgorithm(), signCert.GetEncoded()); aaV2.Add(new DerOctetString(dig)); v.Add(new DerSet(new DerSequence(new DerSequence(new DerSequence(aaV2))))); attribute.Add(new DerSequence(v)); } return new DerSet(attribute); }
public override void WriteByte( byte b) { _buf[_off++] = b; if (_off == _buf.Length) { byte[] encoded = new DerOctetString(_buf).GetEncoded(); _gen.Out.Write(encoded, 0, encoded.Length); _off = 0; } }
/** * generate an enveloped object that contains an CMS Enveloped Data * object using the given provider and the passed in key generator. */ private CmsAuthenticatedData Generate( CmsProcessable content, string macOid, CipherKeyGenerator keyGen) { AlgorithmIdentifier macAlgId; KeyParameter encKey; Asn1OctetString encContent; Asn1OctetString macResult; try { // FIXME Will this work for macs? byte[] encKeyBytes = keyGen.GenerateKey(); encKey = ParameterUtilities.CreateKeyParameter(macOid, encKeyBytes); Asn1Encodable asn1Params = GenerateAsn1Parameters(macOid, encKeyBytes); ICipherParameters cipherParameters; macAlgId = GetAlgorithmIdentifier( macOid, encKey, asn1Params, out cipherParameters); IMac mac = MacUtilities.GetMac(macOid); // TODO Confirm no ParametersWithRandom needed // FIXME Only passing key at the moment // mac.Init(cipherParameters); mac.Init(encKey); MemoryStream bOut = new MemoryStream(); Stream mOut = new TeeOutputStream(bOut, new MacOutputStream(mac)); content.Write(mOut); mOut.Close(); bOut.Close(); encContent = new BerOctetString(bOut.ToArray()); byte[] macOctets = MacUtilities.DoFinal(mac); macResult = new DerOctetString(macOctets); } catch (SecurityUtilityException e) { throw new CmsException("couldn't create cipher.", e); } catch (InvalidKeyException e) { throw new CmsException("key invalid in message.", e); } catch (IOException e) { throw new CmsException("exception decoding algorithm parameters.", e); } Asn1EncodableVector recipientInfos = new Asn1EncodableVector(); foreach (RecipientInfoGenerator rig in recipientInfoGenerators) { try { recipientInfos.Add(rig.Generate(encKey, rand)); } catch (InvalidKeyException e) { throw new CmsException("key inappropriate for algorithm.", e); } catch (GeneralSecurityException e) { throw new CmsException("error making encrypted content.", e); } } ContentInfo eci = new ContentInfo(CmsObjectIdentifiers.Data, encContent); ContentInfo contentInfo = new ContentInfo( CmsObjectIdentifiers.AuthenticatedData, new AuthenticatedData(null, new DerSet(recipientInfos), macAlgId, null, eci, null, macResult, null)); return new CmsAuthenticatedData(contentInfo); }
public static AsymmetricKeyParameter CreateKey( SubjectPublicKeyInfo keyInfo) { AlgorithmIdentifier algID = keyInfo.AlgorithmID; if (algID.ObjectID.Equals(PkcsObjectIdentifiers.RsaEncryption) || algID.ObjectID.Equals(X509ObjectIdentifiers.IdEARsa)) { RsaPublicKeyStructure pubKey = RsaPublicKeyStructure.GetInstance(keyInfo.GetPublicKey()); return new RsaKeyParameters(false, pubKey.Modulus, pubKey.PublicExponent); } else if (algID.ObjectID.Equals(PkcsObjectIdentifiers.DhKeyAgreement) || algID.ObjectID.Equals(X9ObjectIdentifiers.DHPublicNumber)) { DHParameter para = new DHParameter((Asn1Sequence)keyInfo.AlgorithmID.Parameters); DerInteger derY = (DerInteger)keyInfo.GetPublicKey(); return new DHPublicKeyParameters(derY.Value, new DHParameters(para.P, para.G)); } else if (algID.ObjectID.Equals(OiwObjectIdentifiers.ElGamalAlgorithm)) { ElGamalParameter para = new ElGamalParameter((Asn1Sequence)keyInfo.AlgorithmID.Parameters); DerInteger derY = (DerInteger)keyInfo.GetPublicKey(); return new ElGamalPublicKeyParameters(derY.Value, new ElGamalParameters(para.P, para.G)); } else if (algID.ObjectID.Equals(X9ObjectIdentifiers.IdDsa) || algID.ObjectID.Equals(OiwObjectIdentifiers.DsaWithSha1)) { DsaParameter para = DsaParameter.GetInstance(keyInfo.AlgorithmID.Parameters); DerInteger derY = (DerInteger)keyInfo.GetPublicKey(); return new DsaPublicKeyParameters(derY.Value, new DsaParameters(para.P, para.Q, para.G)); } else if (algID.ObjectID.Equals(X9ObjectIdentifiers.IdECPublicKey)) { X962Parameters para = new X962Parameters((Asn1Object)keyInfo.AlgorithmID.Parameters); ECDomainParameters dParams = null; if (para.IsNamedCurve) { DerObjectIdentifier oid = (DerObjectIdentifier)para.Parameters; X9ECParameters ecP = X962NamedCurves.GetByOid(oid); if (ecP == null) { ecP = SecNamedCurves.GetByOid(oid); if (ecP == null) { ecP = NistNamedCurves.GetByOid(oid); } } dParams = new ECDomainParameters( ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed()); } else { X9ECParameters ecP = new X9ECParameters((Asn1Sequence)para.Parameters.ToAsn1Object()); dParams = new ECDomainParameters( ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed()); } DerBitString bits = keyInfo.PublicKeyData; byte[] data = bits.GetBytes(); Asn1OctetString key = new DerOctetString(data); X9ECPoint derQ = new X9ECPoint(dParams.Curve, key); return new ECPublicKeyParameters(derQ.Point, dParams); } else if (algID.ObjectID.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; ECCurve curve = ecP.Curve; ECPoint q; if (curve is FpCurve) { FpCurve curveFp = (FpCurve) curve; q = new FpPoint( curveFp, new FpFieldElement(curveFp.Q, new BigInteger(1, x)), new FpFieldElement(curveFp.Q, new BigInteger(1, y))); } else { F2mCurve curveF2m = (F2mCurve) curve; q = new F2mPoint( curveF2m, new F2mFieldElement(curveF2m.M, curveF2m.K1, curveF2m.K2, curveF2m.K3, new BigInteger(1, x)), new F2mFieldElement(curveF2m.M, curveF2m.K1, curveF2m.K2, curveF2m.K3, new BigInteger(1, y)), false); } return new ECPublicKeyParameters(q, gostParams.PublicKeyParamSet); } else if (algID.ObjectID.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: " + algID.ObjectID); } }
private KeyTransRecipientInfo ComputeRecipientInfo(X509Certificate x509certificate, byte[] abyte0) { Asn1InputStream asn1inputstream = new Asn1InputStream(new MemoryStream(x509certificate.GetTbsCertificate())); TbsCertificateStructure tbscertificatestructure = TbsCertificateStructure.GetInstance(asn1inputstream.ReadObject()); AlgorithmIdentifier algorithmidentifier = tbscertificatestructure.SubjectPublicKeyInfo.AlgorithmID; Org.BouncyCastle.Asn1.Cms.IssuerAndSerialNumber issuerandserialnumber = new Org.BouncyCastle.Asn1.Cms.IssuerAndSerialNumber( tbscertificatestructure.Issuer, tbscertificatestructure.SerialNumber.Value); IBufferedCipher cipher = CipherUtilities.GetCipher(algorithmidentifier.ObjectID); cipher.Init(true, x509certificate.GetPublicKey()); byte[] outp = new byte[10000]; int len = cipher.DoFinal(abyte0, outp, 0); byte[] abyte1 = new byte[len]; System.Array.Copy(outp, 0, abyte1, 0, len); DerOctetString deroctetstring = new DerOctetString(abyte1); RecipientIdentifier recipId = new RecipientIdentifier(issuerandserialnumber); return new KeyTransRecipientInfo( recipId, algorithmidentifier, deroctetstring); }
/** * This method provides that encoding and the parameters must be * exactly the same as in {@link #getEncodedPKCS7(byte[],Calendar)}. * * @param secondDigest the content digest * @return the byte array representation of the authenticatedAttributes ready to be signed */ private DerSet GetAuthenticatedAttributeSet(byte[] secondDigest, byte[] ocsp, ICollection<byte[]> crlBytes, CryptoStandard sigtype) { Asn1EncodableVector attribute = new Asn1EncodableVector(); Asn1EncodableVector v = new Asn1EncodableVector(); v.Add(new DerObjectIdentifier(SecurityIDs.ID_CONTENT_TYPE)); v.Add(new DerSet(new DerObjectIdentifier(SecurityIDs.ID_PKCS7_DATA))); attribute.Add(new DerSequence(v)); v = new Asn1EncodableVector(); v.Add(new DerObjectIdentifier(SecurityIDs.ID_MESSAGE_DIGEST)); v.Add(new DerSet(new DerOctetString(secondDigest))); attribute.Add(new DerSequence(v)); bool haveCrl = false; if (crlBytes != null) { foreach (byte[] bCrl in crlBytes) { if (bCrl != null) { haveCrl = true; break; } } } if (ocsp != null || haveCrl) { v = new Asn1EncodableVector(); v.Add(new DerObjectIdentifier(SecurityIDs.ID_ADBE_REVOCATION)); Asn1EncodableVector revocationV = new Asn1EncodableVector(); if (haveCrl) { Asn1EncodableVector v2 = new Asn1EncodableVector(); foreach (byte[] bCrl in crlBytes) { if (bCrl == null) continue; Asn1InputStream t = new Asn1InputStream(bCrl); v2.Add(t.ReadObject()); } revocationV.Add(new DerTaggedObject(true, 0, new DerSequence(v2))); } if (ocsp != null) { DerOctetString doctet = new DerOctetString(ocsp); Asn1EncodableVector vo1 = new Asn1EncodableVector(); Asn1EncodableVector v2 = new Asn1EncodableVector(); v2.Add(OcspObjectIdentifiers.PkixOcspBasic); v2.Add(doctet); DerEnumerated den = new DerEnumerated(0); Asn1EncodableVector v3 = new Asn1EncodableVector(); v3.Add(den); v3.Add(new DerTaggedObject(true, 0, new DerSequence(v2))); vo1.Add(new DerSequence(v3)); revocationV.Add(new DerTaggedObject(true, 1, new DerSequence(vo1))); } v.Add(new DerSet(new DerSequence(revocationV))); attribute.Add(new DerSequence(v)); } if (sigtype == CryptoStandard.CADES) { v = new Asn1EncodableVector(); v.Add(new DerObjectIdentifier(SecurityIDs.ID_AA_SIGNING_CERTIFICATE_V2)); Asn1EncodableVector aaV2 = new Asn1EncodableVector(); String sha256Oid = DigestAlgorithms.GetAllowedDigests(DigestAlgorithms.SHA256); // If we look into X.690-0207, clause 11.5, we can see that using DER all the components of a sequence having // default values shall not be included. According to RFC 5035, 5.4.1.1, definition of ESSCertIDv2, default // AlgorithmIdentifier is sha256. if (!sha256Oid.Equals(digestAlgorithmOid)) { AlgorithmIdentifier algoId = new AlgorithmIdentifier(new DerObjectIdentifier(digestAlgorithmOid)); aaV2.Add(algoId); } byte[] dig = DigestAlgorithms.Digest(GetHashAlgorithm(), signCert.GetEncoded()); aaV2.Add(new DerOctetString(dig)); v.Add(new DerSet(new DerSequence(new DerSequence(new DerSequence(aaV2))))); attribute.Add(new DerSequence(v)); } return new DerSet(attribute); }
internal SignerInfo ToSignerInfo( DerObjectIdentifier contentType) { AlgorithmIdentifier digAlgId = new AlgorithmIdentifier( new DerObjectIdentifier(this._digestOID), DerNull.Instance); AlgorithmIdentifier encAlgId = CmsSignedGenerator.GetEncAlgorithmIdentifier(this.EncryptionAlgOid); byte[] hash = (byte[])outer._messageHashes[Helper.GetDigestAlgName(this._digestOID)]; outer._digests[_digestOID] = hash.Clone(); IDictionary parameters = outer.GetBaseParameters(contentType, digAlgId, hash); Asn1.Cms.AttributeTable signed = (_sAttr != null) // ? _sAttr.GetAttributes(Collections.unmodifiableMap(parameters)) ? _sAttr.GetAttributes(parameters) : null; Asn1Set signedAttr = outer.GetAttributeSet(signed); // // sig must be composed from the DER encoding. // byte[] tmp; if (signedAttr != null) { tmp = signedAttr.GetEncoded(Asn1Encodable.Der); } else { throw new Exception("signatures without signed attributes not implemented."); } _signature.BlockUpdate(tmp, 0, tmp.Length); Asn1OctetString encDigest = new DerOctetString(_signature.GenerateSignature()); parameters = outer.GetBaseParameters(contentType, digAlgId, hash); parameters[CmsAttributeTableParameter.Signature] = encDigest.GetOctets().Clone(); Asn1.Cms.AttributeTable unsigned = (_unsAttr != null) // ? _unsAttr.getAttributes(Collections.unmodifiableMap(parameters)) ? _unsAttr.GetAttributes(parameters) : null; Asn1Set unsignedAttr = outer.GetAttributeSet(unsigned); X509Certificate cert = this.Certificate; SignerIdentifier signerIdentifier; if (cert != null) { TbsCertificateStructure tbs = TbsCertificateStructure.GetInstance( Asn1Object.FromByteArray(cert.GetTbsCertificate())); IssuerAndSerialNumber encSid = new IssuerAndSerialNumber( tbs.Issuer, tbs.SerialNumber.Value); signerIdentifier = new SignerIdentifier(encSid); } else { signerIdentifier = new SignerIdentifier(new DerOctetString(_subjectKeyID)); } return new SignerInfo(signerIdentifier, digAlgId, signedAttr, encAlgId, encDigest, unsignedAttr); }
// internal Asn1.Cms.AttributeTable SignedAttributes // { // get { return _sAttr; } // } // // internal Asn1.Cms.AttributeTable UnsignedAttributes // { // get { return _unsAttr; } // } internal SignerInfo ToSignerInfo( DerObjectIdentifier contentType) { AlgorithmIdentifier digAlgId = new AlgorithmIdentifier( new DerObjectIdentifier(this.DigestAlgOid), DerNull.Instance); AlgorithmIdentifier encAlgId = CmsSignedGenerator.GetEncAlgorithmIdentifier(this.EncryptionAlgOid); byte[] hash = DigestUtilities.DoFinal(_digest); outer._digests.Add(_digestOID, hash.Clone()); IDictionary parameters = outer.GetBaseParameters(contentType, digAlgId, hash); Asn1.Cms.AttributeTable signed = (_sAttr != null) // ? _sAttr.GetAttributes(Collections.unmodifiableMap(parameters)) ? _sAttr.GetAttributes(parameters) : null; Asn1Set signedAttr = outer.GetAttributeSet(signed); // // sig must be composed from the DER encoding. // byte[] bOutBytes; if (signedAttr != null) { bOutBytes = signedAttr.GetDerEncoded(); } else { throw new Exception("signatures without signed attributes not implemented."); } _signature.BlockUpdate(bOutBytes, 0, bOutBytes.Length); Asn1OctetString encDigest = new DerOctetString(_signature.GenerateSignature()); parameters = outer.GetBaseParameters(contentType, digAlgId, hash); parameters[CmsAttributeTableParameter.Signature] = encDigest.GetOctets().Clone(); Asn1.Cms.AttributeTable unsigned = (_unsAttr != null) // ? _unsAttr.getAttributes(Collections.unmodifiableMap(parameters)) ? _unsAttr.GetAttributes(parameters) : null; Asn1Set unsignedAttr = outer.GetAttributeSet(unsigned); X509Certificate cert = this.Certificate; TbsCertificateStructure tbs = TbsCertificateStructure.GetInstance( Asn1Object.FromByteArray(cert.GetTbsCertificate())); IssuerAndSerialNumber encSid = new IssuerAndSerialNumber( tbs.Issuer, tbs.SerialNumber.Value); return new SignerInfo(new SignerIdentifier(encSid), digAlgId, signedAttr, encAlgId, encDigest, unsignedAttr); }
private static byte[] BuildOCSPResponse(byte[] BasicOCSPResponse) { DerOctetString doctet = new DerOctetString(BasicOCSPResponse); Asn1EncodableVector v2 = new Asn1EncodableVector(); v2.Add(OcspObjectIdentifiers.PkixOcspBasic); v2.Add(doctet); DerEnumerated den = new DerEnumerated(0); Asn1EncodableVector v3 = new Asn1EncodableVector(); v3.Add(den); v3.Add(new DerTaggedObject(true, 0, new DerSequence(v2))); DerSequence seq = new DerSequence(v3); return seq.GetEncoded(); }
public static AsymmetricKeyParameter CreateKey( SubjectPublicKeyInfo 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)) { 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); } }