public OriginatorInfo( Asn1Set certs, Asn1Set crls) { this.certs = certs; this.crls = crls; }
public AttributeX509( DerObjectIdentifier attrType, Asn1Set attrValues) { this.attrType = attrType; this.attrValues = attrValues; }
public AuthenticatedData( OriginatorInfo originatorInfo, Asn1Set recipientInfos, AlgorithmIdentifier macAlgorithm, AlgorithmIdentifier digestAlgorithm, ContentInfo encapsulatedContent, Asn1Set authAttrs, Asn1OctetString mac, Asn1Set unauthAttrs) { if (digestAlgorithm != null || authAttrs != null) { if (digestAlgorithm == null || authAttrs == null) { throw new ArgumentException("digestAlgorithm and authAttrs must be set together"); } } version = new DerInteger(CalculateVersion(originatorInfo)); this.originatorInfo = originatorInfo; this.macAlgorithm = macAlgorithm; this.digestAlgorithm = digestAlgorithm; this.recipientInfos = recipientInfos; this.encapsulatedContentInfo = encapsulatedContent; this.authAttrs = authAttrs; this.mac = mac; this.unauthAttrs = unauthAttrs; }
private PrivateKeyInfo( Asn1Sequence seq) { IEnumerator e = seq.GetEnumerator(); e.MoveNext(); IBigInteger version = ((DerInteger) e.Current).Value; if (version.IntValue != 0) { throw new ArgumentException("wrong version for private key info"); } e.MoveNext(); algID = AlgorithmIdentifier.GetInstance(e.Current); try { e.MoveNext(); Asn1OctetString data = (Asn1OctetString) e.Current; privKey = Asn1Object.FromByteArray(data.GetOctets()); } catch (IOException) { throw new ArgumentException("Error recoverying private key from sequence"); } if (e.MoveNext()) { attributes = Asn1Set.GetInstance((Asn1TaggedObject) e.Current, false); } }
public OriginatorInfo( Asn1Sequence seq) { switch (seq.Count) { case 0: // empty break; case 1: Asn1TaggedObject o = (Asn1TaggedObject) seq[0]; switch (o.TagNo) { case 0 : certs = Asn1Set.GetInstance(o, false); break; case 1 : crls = Asn1Set.GetInstance(o, false); break; default: throw new ArgumentException("Bad tag in OriginatorInfo: " + o.TagNo); } break; case 2: certs = Asn1Set.GetInstance((Asn1TaggedObject) seq[0], false); crls = Asn1Set.GetInstance((Asn1TaggedObject) seq[1], false); break; default: throw new ArgumentException("OriginatorInfo too big"); } }
public AuthEnvelopedData( OriginatorInfo originatorInfo, Asn1Set recipientInfos, EncryptedContentInfo authEncryptedContentInfo, Asn1Set authAttrs, Asn1OctetString mac, Asn1Set unauthAttrs) { // "It MUST be set to 0." this.version = new DerInteger(0); this.originatorInfo = originatorInfo; // TODO // "There MUST be at least one element in the collection." this.recipientInfos = recipientInfos; this.authEncryptedContentInfo = authEncryptedContentInfo; // TODO // "The authAttrs MUST be present if the content type carried in // EncryptedContentInfo is not id-data." this.authAttrs = authAttrs; this.mac = mac; this.unauthAttrs = unauthAttrs; }
public SafeBag( DerObjectIdentifier oid, Asn1Object obj) { this.bagID = oid; this.bagValue = obj; this.bagAttributes = null; }
private AttributeX509( Asn1Sequence seq) { if (seq.Count != 2) throw new ArgumentException("Bad sequence size: " + seq.Count); attrType = DerObjectIdentifier.GetInstance(seq[0]); attrValues = Asn1Set.GetInstance(seq[1]); }
public SafeBag( DerObjectIdentifier oid, Asn1Object obj, Asn1Set bagAttributes) { this.bagID = oid; this.bagValue = obj; this.bagAttributes = bagAttributes; }
private AttributePkcs( Asn1Sequence seq) { if (seq.Count != 2) throw new ArgumentException("Wrong number of elements in sequence", "seq"); attrType = DerObjectIdentifier.GetInstance(seq[0]); attrValues = Asn1Set.GetInstance(seq[1]); }
public PrivateKeyInfo( AlgorithmIdentifier algID, Asn1Object privateKey, Asn1Set attributes) { this.privKey = privateKey; this.algID = algID; this.attributes = attributes; }
public PrivateKeyInfo( AlgorithmIdentifier algID, Asn1Object privateKey, Asn1Set attributes) { this.algID = algID; this.privKey = new DerOctetString(privateKey.GetEncoded(Asn1Encodable.Der)); this.attributes = attributes; }
public SafeBag( Asn1Sequence seq) { this.bagID = (DerObjectIdentifier) seq[0]; this.bagValue = ((DerTaggedObject) seq[1]).GetObject(); if (seq.Count == 3) { this.bagAttributes = (Asn1Set) seq[2]; } }
public AttributeTable(Asn1Set s) { _attributes = Platform.CreateHashtable(s.Count); for (int i = 0; i != s.Count; i++) { AttributeX509 a = AttributeX509.GetInstance(s[i]); _attributes.Add(a.AttrType, a); } }
public EncryptedData( EncryptedContentInfo encInfo, Asn1Set unprotectedAttrs) { if (encInfo == null) throw new ArgumentNullException("encInfo"); this.version = new DerInteger((unprotectedAttrs == null) ? 0 : 2); this.encryptedContentInfo = encInfo; this.unprotectedAttrs = unprotectedAttrs; }
public AttributeTable(Asn1Set s) { _attributes = Platform.CreateHashtable(s.Count); for (int i = 0; i != s.Count; i++) { Attribute a = Attribute.GetInstance(s[i]); AddAttribute(a); } }
public EnvelopedData( OriginatorInfo originatorInfo, Asn1Set recipientInfos, EncryptedContentInfo encryptedContentInfo, Attributes unprotectedAttrs) { this.version = new DerInteger(CalculateVersion(originatorInfo, recipientInfos, Asn1Set.GetInstance(unprotectedAttrs))); this.originatorInfo = originatorInfo; this.recipientInfos = recipientInfos; this.encryptedContentInfo = encryptedContentInfo; this.unprotectedAttrs = Asn1Set.GetInstance(unprotectedAttrs); }
private void checkSortedSet( int attempt, Asn1Set s) { if (s[0] is DerBoolean && s[1] is DerInteger && s[2] is DerBitString && s[3] is DerOctetString) { return; } Fail("sorting failed on attempt: " + attempt); }
public SignedData( DerInteger _version, Asn1Set _digestAlgorithms, ContentInfo _contentInfo, Asn1Set _certificates, Asn1Set _crls, Asn1Set _signerInfos) { version = _version; digestAlgorithms = _digestAlgorithms; contentInfo = _contentInfo; certificates = _certificates; crls = _crls; signerInfos = _signerInfos; }
public CertificationRequestInfo( X509Name subject, SubjectPublicKeyInfo pkInfo, Asn1Set attributes) { this.subject = subject; this.subjectPKInfo = pkInfo; this.attributes = attributes; if (subject == null || version == null || subjectPKInfo == null) { throw new ArgumentException( "Not all mandatory fields set in CertificationRequestInfo generator."); } }
public SignedData( Asn1Set digestAlgorithms, ContentInfo contentInfo, Asn1Set certificates, Asn1Set crls, Asn1Set signerInfos) { this.version = CalculateVersion(contentInfo.ContentType, certificates, crls, signerInfos); this.digestAlgorithms = digestAlgorithms; this.contentInfo = contentInfo; this.certificates = certificates; this.crls = crls; this.signerInfos = signerInfos; this.crlsBer = crls is BerSet; this.certsBer = certificates is BerSet; }
private EncryptedData( Asn1Sequence seq) { if (seq == null) throw new ArgumentNullException("seq"); if (seq.Count < 2 || seq.Count > 3) throw new ArgumentException("Bad sequence size: " + seq.Count, "seq"); this.version = DerInteger.GetInstance(seq[0]); this.encryptedContentInfo = EncryptedContentInfo.GetInstance(seq[1]); if (seq.Count > 2) { this.unprotectedAttrs = Asn1Set.GetInstance(seq[2]); } }
public SignerInfo( SignerIdentifier sid, AlgorithmIdentifier digAlgorithm, Attributes authenticatedAttributes, AlgorithmIdentifier digEncryptionAlgorithm, Asn1OctetString encryptedDigest, Attributes unauthenticatedAttributes) { this.version = new DerInteger(sid.IsTagged ? 3 : 1); this.sid = sid; this.digAlgorithm = digAlgorithm; this.authenticatedAttributes = Asn1Set.GetInstance(authenticatedAttributes); this.digEncryptionAlgorithm = digEncryptionAlgorithm; this.encryptedDigest = encryptedDigest; this.unauthenticatedAttributes = Asn1Set.GetInstance(unauthenticatedAttributes); }
private SignedData( Asn1Sequence seq) { IEnumerator e = seq.GetEnumerator(); e.MoveNext(); version = (DerInteger)e.Current; e.MoveNext(); digestAlgorithms = ((Asn1Set)e.Current); e.MoveNext(); contentInfo = ContentInfo.GetInstance(e.Current); while (e.MoveNext()) { Asn1Object o = (Asn1Object)e.Current; // // an interesting feature of SignedData is that there appear // to be varying implementations... // for the moment we ignore anything which doesn't fit. // if (o is Asn1TaggedObject) { Asn1TaggedObject tagged = (Asn1TaggedObject)o; switch (tagged.TagNo) { case 0: certsBer = tagged is BerTaggedObject; certificates = Asn1Set.GetInstance(tagged, false); break; case 1: crlsBer = tagged is BerTaggedObject; crls = Asn1Set.GetInstance(tagged, false); break; default: throw new ArgumentException("unknown tag value " + tagged.TagNo); } } else { signerInfos = (Asn1Set) o; } } }
public SignerInfo( DerInteger version, IssuerAndSerialNumber issuerAndSerialNumber, AlgorithmIdentifier digAlgorithm, Asn1Set authenticatedAttributes, AlgorithmIdentifier digEncryptionAlgorithm, Asn1OctetString encryptedDigest, Asn1Set unauthenticatedAttributes) { this.version = version; this.issuerAndSerialNumber = issuerAndSerialNumber; this.digAlgorithm = digAlgorithm; this.authenticatedAttributes = authenticatedAttributes; this.digEncryptionAlgorithm = digEncryptionAlgorithm; this.encryptedDigest = encryptedDigest; this.unauthenticatedAttributes = unauthenticatedAttributes; }
private AuthEnvelopedData( Asn1Sequence seq) { int index = 0; // TODO // "It MUST be set to 0." Asn1Object tmp = seq[index++].ToAsn1Object(); version = (DerInteger)tmp; tmp = seq[index++].ToAsn1Object(); if (tmp is Asn1TaggedObject) { originatorInfo = OriginatorInfo.GetInstance((Asn1TaggedObject)tmp, false); tmp = seq[index++].ToAsn1Object(); } // TODO // "There MUST be at least one element in the collection." recipientInfos = Asn1Set.GetInstance(tmp); tmp = seq[index++].ToAsn1Object(); authEncryptedContentInfo = EncryptedContentInfo.GetInstance(tmp); tmp = seq[index++].ToAsn1Object(); if (tmp is Asn1TaggedObject) { authAttrs = Asn1Set.GetInstance((Asn1TaggedObject)tmp, false); tmp = seq[index++].ToAsn1Object(); } else { // TODO // "The authAttrs MUST be present if the content type carried in // EncryptedContentInfo is not id-data." } mac = Asn1OctetString.GetInstance(tmp); if (seq.Count > index) { tmp = seq[index++].ToAsn1Object(); unauthAttrs = Asn1Set.GetInstance((Asn1TaggedObject)tmp, false); } }
private AuthenticatedData( Asn1Sequence seq) { int index = 0; version = (DerInteger)seq[index++]; Asn1Encodable tmp = seq[index++]; if (tmp is Asn1TaggedObject) { originatorInfo = OriginatorInfo.GetInstance((Asn1TaggedObject)tmp, false); tmp = seq[index++]; } recipientInfos = Asn1Set.GetInstance(tmp); macAlgorithm = AlgorithmIdentifier.GetInstance(seq[index++]); tmp = seq[index++]; if (tmp is Asn1TaggedObject) { digestAlgorithm = AlgorithmIdentifier.GetInstance((Asn1TaggedObject)tmp, false); tmp = seq[index++]; } encapsulatedContentInfo = ContentInfo.GetInstance(tmp); tmp = seq[index++]; if (tmp is Asn1TaggedObject) { authAttrs = Asn1Set.GetInstance((Asn1TaggedObject)tmp, false); tmp = seq[index++]; } mac = Asn1OctetString.GetInstance(tmp); if (seq.Count > index) { unauthAttrs = Asn1Set.GetInstance((Asn1TaggedObject)seq[index], false); } }
public SignerInfo( Asn1Sequence seq) { IEnumerator e = seq.GetEnumerator(); e.MoveNext(); version = (DerInteger) e.Current; e.MoveNext(); issuerAndSerialNumber = IssuerAndSerialNumber.GetInstance(e.Current); e.MoveNext(); digAlgorithm = AlgorithmIdentifier.GetInstance(e.Current); e.MoveNext(); object obj = e.Current; if (obj is Asn1TaggedObject) { authenticatedAttributes = Asn1Set.GetInstance((Asn1TaggedObject) obj, false); e.MoveNext(); digEncryptionAlgorithm = AlgorithmIdentifier.GetInstance(e.Current); } else { authenticatedAttributes = null; digEncryptionAlgorithm = AlgorithmIdentifier.GetInstance(obj); } e.MoveNext(); encryptedDigest = DerOctetString.GetInstance(e.Current); if (e.MoveNext()) { unauthenticatedAttributes = Asn1Set.GetInstance((Asn1TaggedObject)e.Current, false); } else { unauthenticatedAttributes = null; } }
private PrivateKeyInfo(Asn1Sequence seq) { IEnumerator e = seq.GetEnumerator(); e.MoveNext(); BigInteger version = ((DerInteger)e.Current).Value; if (version.IntValue != 0) { throw new ArgumentException("wrong version for private key info: " + version.IntValue); } e.MoveNext(); algID = AlgorithmIdentifier.GetInstance(e.Current); e.MoveNext(); privKey = Asn1OctetString.GetInstance(e.Current); if (e.MoveNext()) { attributes = Asn1Set.GetInstance((Asn1TaggedObject)e.Current, false); } }
public EnvelopedData( Asn1Sequence seq) { int index = 0; version = (DerInteger) seq[index++]; object tmp = seq[index++]; if (tmp is Asn1TaggedObject) { originatorInfo = OriginatorInfo.GetInstance((Asn1TaggedObject) tmp, false); tmp = seq[index++]; } recipientInfos = Asn1Set.GetInstance(tmp); encryptedContentInfo = EncryptedContentInfo.GetInstance(seq[index++]); if (seq.Count > index) { unprotectedAttrs = Asn1Set.GetInstance((Asn1TaggedObject) seq[index], false); } }
public Attributes(Asn1EncodableVector v) { attributes = new BerSet(v); }
public void Load( Stream input, char[] password) { if (input == null) { throw new ArgumentNullException("input"); } Asn1Sequence obj = (Asn1Sequence)Asn1Object.FromStream(input); Pfx bag = new Pfx(obj); ContentInfo info = bag.AuthSafe; bool wrongPkcs12Zero = false; if (password != null && bag.MacData != null) // check the mac code { MacData mData = bag.MacData; DigestInfo dInfo = mData.Mac; AlgorithmIdentifier algId = dInfo.AlgorithmID; byte[] salt = mData.GetSalt(); int itCount = mData.IterationCount.IntValue; byte[] data = ((Asn1OctetString)info.Content).GetOctets(); byte[] mac = CalculatePbeMac(algId.Algorithm, salt, itCount, password, false, data); byte[] dig = dInfo.GetDigest(); if (!Arrays.ConstantTimeAreEqual(mac, dig)) { if (password.Length > 0) { throw new IOException("PKCS12 key store MAC invalid - wrong password or corrupted file."); } // Try with incorrect zero length password mac = CalculatePbeMac(algId.Algorithm, salt, itCount, password, true, data); if (!Arrays.ConstantTimeAreEqual(mac, dig)) { throw new IOException("PKCS12 key store MAC invalid - wrong password or corrupted file."); } wrongPkcs12Zero = true; } } keys.Clear(); localIds.Clear(); unmarkedKeyEntry = null; IList certBags = Platform.CreateArrayList(); if (info.ContentType.Equals(PkcsObjectIdentifiers.Data)) { byte[] octs = ((Asn1OctetString)info.Content).GetOctets(); AuthenticatedSafe authSafe = new AuthenticatedSafe( (Asn1Sequence)Asn1OctetString.FromByteArray(octs)); ContentInfo[] cis = authSafe.GetContentInfo(); foreach (ContentInfo ci in cis) { DerObjectIdentifier oid = ci.ContentType; byte[] octets = null; if (oid.Equals(PkcsObjectIdentifiers.Data)) { octets = ((Asn1OctetString)ci.Content).GetOctets(); } else if (oid.Equals(PkcsObjectIdentifiers.EncryptedData)) { if (password != null) { EncryptedData d = EncryptedData.GetInstance(ci.Content); octets = CryptPbeData(false, d.EncryptionAlgorithm, password, wrongPkcs12Zero, d.Content.GetOctets()); } } else { // TODO Other data types } if (octets != null) { Asn1Sequence seq = (Asn1Sequence)Asn1Object.FromByteArray(octets); foreach (Asn1Sequence subSeq in seq) { SafeBag b = new SafeBag(subSeq); if (b.BagID.Equals(PkcsObjectIdentifiers.CertBag)) { certBags.Add(b); } else if (b.BagID.Equals(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag)) { LoadPkcs8ShroudedKeyBag(EncryptedPrivateKeyInfo.GetInstance(b.BagValue), b.BagAttributes, password, wrongPkcs12Zero); } else if (b.BagID.Equals(PkcsObjectIdentifiers.KeyBag)) { LoadKeyBag(PrivateKeyInfo.GetInstance(b.BagValue), b.BagAttributes); } else { // TODO Other bag types } } } } } certs.Clear(); chainCerts.Clear(); keyCerts.Clear(); foreach (SafeBag b in certBags) { CertBag certBag = new CertBag((Asn1Sequence)b.BagValue); byte[] octets = ((Asn1OctetString)certBag.CertValue).GetOctets(); X509Certificate cert = new X509CertificateParser().ReadCertificate(octets); // // set the attributes // IDictionary attributes = Platform.CreateHashtable(); Asn1OctetString localId = null; string alias = null; if (b.BagAttributes != null) { foreach (Asn1Sequence sq in b.BagAttributes) { DerObjectIdentifier aOid = DerObjectIdentifier.GetInstance(sq[0]); Asn1Set attrSet = Asn1Set.GetInstance(sq[1]); if (attrSet.Count > 0) { // TODO We should be adding all attributes in the set Asn1Encodable attr = attrSet[0]; // TODO We might want to "merge" attribute sets with // the same OID - currently, differing values give an error if (attributes.Contains(aOid.Id)) { // OK, but the value has to be the same if (!attributes[aOid.Id].Equals(attr)) { throw new IOException("attempt to add existing attribute with different value"); } } else { attributes.Add(aOid.Id, attr); } if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName)) { alias = ((DerBmpString)attr).GetString(); } else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID)) { localId = (Asn1OctetString)attr; } } } } CertId certId = new CertId(cert.GetPublicKey()); X509CertificateEntry certEntry = new X509CertificateEntry(cert, attributes); chainCerts[certId] = certEntry; if (unmarkedKeyEntry != null) { if (keyCerts.Count == 0) { string name = Hex.ToHexString(certId.Id); keyCerts[name] = certEntry; keys[name] = unmarkedKeyEntry; } } else { if (localId != null) { string name = Hex.ToHexString(localId.GetOctets()); keyCerts[name] = certEntry; } if (alias != null) { // TODO There may have been more than one alias certs[alias] = certEntry; } } } }
public SignedData(Asn1Set digestAlgorithms, ContentInfo contentInfo, Asn1Set certificates, Asn1Set crls, Asn1Set signerInfos) { version = CalculateVersion(contentInfo.ContentType, certificates, crls, signerInfos); this.digestAlgorithms = digestAlgorithms; this.contentInfo = contentInfo; this.certificates = certificates; this.crls = crls; this.signerInfos = signerInfos; crlsBer = crls is BerSet; certsBer = certificates is BerSet; }
internal SignerInfo ToSignerInfo( DerObjectIdentifier contentType, CmsProcessable content, SecureRandom random, bool isCounterSignature) { AlgorithmIdentifier digAlgId = DigestAlgorithmID; string digestName = Helper.GetDigestAlgName(digestOID); IDigest dig = Helper.GetDigestInstance(digestName); string signatureName = digestName + "with" + Helper.GetEncryptionAlgName(encOID); ISigner sig = Helper.GetSignatureInstance(signatureName); // TODO Optimise the case where more than one signer with same digest if (content != null) { content.Write(new DigOutputStream(dig)); } byte[] hash = DigestUtilities.DoFinal(dig); outer._digests.Add(digestOID, hash.Clone()); sig.Init(true, new ParametersWithRandom(key, random)); Stream sigStr = new BufferedStream(new SigOutputStream(sig)); Asn1Set signedAttr = null; if (sAttr != null) { IDictionary parameters = outer.GetBaseParameters(contentType, digAlgId, hash); // Asn1.Cms.AttributeTable signed = sAttr.GetAttributes(Collections.unmodifiableMap(parameters)); Asn1.Cms.AttributeTable signed = sAttr.GetAttributes(parameters); if (isCounterSignature) { Hashtable tmpSigned = signed.ToHashtable(); tmpSigned.Remove(CmsAttributes.ContentType); signed = new Asn1.Cms.AttributeTable(tmpSigned); } // TODO Validate proposed signed attributes signedAttr = outer.GetAttributeSet(signed); // sig must be composed from the DER encoding. new DerOutputStream(sigStr).WriteObject(signedAttr); } else if (content != null) { // TODO Use raw signature of the hash value instead content.Write(sigStr); } sigStr.Close(); byte[] sigBytes = sig.GenerateSignature(); Asn1Set unsignedAttr = null; if (unsAttr != null) { IDictionary baseParameters = outer.GetBaseParameters(contentType, digAlgId, hash); baseParameters[CmsAttributeTableParameter.Signature] = sigBytes.Clone(); // Asn1.Cms.AttributeTable unsigned = unsAttr.GetAttributes(Collections.unmodifiableMap(baseParameters)); Asn1.Cms.AttributeTable unsigned = unsAttr.GetAttributes(baseParameters); // TODO Validate proposed unsigned attributes unsignedAttr = outer.GetAttributeSet(unsigned); } // TODO[RSAPSS] Need the ability to specify non-default parameters Asn1Encodable sigX509Parameters = SignerUtilities.GetDefaultX509Parameters(signatureName); AlgorithmIdentifier encAlgId = CmsSignedGenerator.GetEncAlgorithmIdentifier( new DerObjectIdentifier(encOID), sigX509Parameters); return(new SignerInfo(signerIdentifier, digAlgId, signedAttr, encAlgId, new DerOctetString(sigBytes), unsignedAttr)); }
static string BuildPartitionedCrlDistributionPoint(string partitionedCrlDistributionPoint, Asn1Set dset) { foreach (DerSequence relativeDn in dset) { var relativeDnOid = ((DerObjectIdentifier)relativeDn[0]).Id; var relativeDnName = (string)X509Name.RFC2253Symbols[new DerObjectIdentifier(relativeDnOid)]; var relativeDnValue = ((DerStringBase)relativeDn[1]).GetString(); var comma = partitionedCrlDistributionPoint.Length > 0 ? "," : ""; partitionedCrlDistributionPoint = relativeDnName + "=" + relativeDnValue + comma + partitionedCrlDistributionPoint; } return partitionedCrlDistributionPoint; }
public SignerInfo Generate(DerObjectIdentifier contentType, AlgorithmIdentifier digestAlgorithm, byte[] calculatedDigest) { try { string digestName = Helper.GetDigestAlgName(_digestOID); string signatureName = digestName + "with" + _encName; // AlgorithmIdentifier digAlgId = DigestAlgorithmID; // // byte[] hash = (byte[])outer._messageHashes[Helper.GetDigestAlgName(this._digestOID)]; // outer._digests[_digestOID] = hash.Clone(); byte[] bytesToSign = calculatedDigest; /* RFC 3852 5.4 * The result of the message digest calculation process depends on * whether the signedAttrs field is present. When the field is absent, * the result is just the message digest of the content as described * * above. When the field is present, however, the result is the message * digest of the complete DER encoding of the SignedAttrs value * contained in the signedAttrs field. */ Asn1Set signedAttr = null; if (_sAttr != null) { IDictionary parameters = outer.GetBaseParameters(contentType, digestAlgorithm, calculatedDigest); // Asn1.Cms.AttributeTable signed = _sAttr.GetAttributes(Collections.unmodifiableMap(parameters)); Asn1.Cms.AttributeTable signed = _sAttr.GetAttributes(parameters); if (contentType == null) //counter signature { if (signed != null && signed[CmsAttributes.ContentType] != null) { IDictionary tmpSigned = signed.ToDictionary(); tmpSigned.Remove(CmsAttributes.ContentType); signed = new Asn1.Cms.AttributeTable(tmpSigned); } } signedAttr = outer.GetAttributeSet(signed); // sig must be composed from the DER encoding. bytesToSign = signedAttr.GetEncoded(Asn1Encodable.Der); } else { // Note: Need to use raw signatures here since we have already calculated the digest if (_encName.Equals("RSA")) { DigestInfo dInfo = new DigestInfo(digestAlgorithm, calculatedDigest); bytesToSign = dInfo.GetEncoded(Asn1Encodable.Der); } } _sig.BlockUpdate(bytesToSign, 0, bytesToSign.Length); byte[] sigBytes = _sig.GenerateSignature(); Asn1Set unsignedAttr = null; if (_unsAttr != null) { IDictionary parameters = outer.GetBaseParameters( contentType, digestAlgorithm, calculatedDigest); parameters[CmsAttributeTableParameter.Signature] = sigBytes.Clone(); // Asn1.Cms.AttributeTable unsigned = _unsAttr.getAttributes(Collections.unmodifiableMap(parameters)); Asn1.Cms.AttributeTable unsigned = _unsAttr.GetAttributes(parameters); unsignedAttr = outer.GetAttributeSet(unsigned); } // TODO[RSAPSS] Need the ability to specify non-default parameters Asn1Encodable sigX509Parameters = SignerUtilities.GetDefaultX509Parameters(signatureName); AlgorithmIdentifier digestEncryptionAlgorithm = Helper.GetEncAlgorithmIdentifier( new DerObjectIdentifier(_encOID), sigX509Parameters); return(new SignerInfo(_signerIdentifier, digestAlgorithm, signedAttr, digestEncryptionAlgorithm, new DerOctetString(sigBytes), unsignedAttr)); } catch (IOException e) { throw new CmsStreamException("encoding error.", e); } catch (SignatureException e) { throw new CmsStreamException("error creating signature.", e); } }
public AttributeTable(Attributes attrs) : this(Asn1Set.GetInstance(attrs.ToAsn1Object())) { }
/** * Replace the certificate and CRL information associated with this * CmsSignedData object with the new one passed in. * * @param signedData the signed data object to be used as a base. * @param x509Certs the new certificates to be used. * @param x509Crls the new CRLs to be used. * @return a new signed data object. * @exception CmsException if there is an error processing the stores */ public static CmsSignedData ReplaceCertificatesAndCrls( CmsSignedData signedData, IX509Store x509Certs, IX509Store x509Crls, IX509Store x509AttrCerts) { if (x509AttrCerts != null) { throw Platform.CreateNotImplementedException("Currently can't replace attribute certificates"); } // // copy // CmsSignedData cms = new CmsSignedData(signedData); // // replace the certs and crls in the SignedData object // Asn1Set certs = null; try { Asn1Set asn1Set = CmsUtilities.CreateBerSetFromList( CmsUtilities.GetCertificatesFromStore(x509Certs)); if (asn1Set.Count != 0) { certs = asn1Set; } } catch (X509StoreException e) { throw new CmsException("error getting certificates from store", e); } Asn1Set crls = null; try { Asn1Set asn1Set = CmsUtilities.CreateBerSetFromList( CmsUtilities.GetCrlsFromStore(x509Crls)); if (asn1Set.Count != 0) { crls = asn1Set; } } catch (X509StoreException e) { throw new CmsException("error getting CRLs from store", e); } // // replace the CMS structure. // SignedData old = signedData.signedData; cms.signedData = new SignedData( old.DigestAlgorithms, old.EncapContentInfo, certs, crls, old.SignerInfos); // // replace the contentInfo with the new one // cms.contentInfo = new ContentInfo(cms.contentInfo.ContentType, cms.signedData); return(cms); }
/** * generate a signed object that for a CMS Signed Data * object - if encapsulate is true a copy * of the message will be included in the signature. The content type * is set according to the OID represented by the string signedContentType. */ public CmsSignedData Generate( string signedContentType, // FIXME Avoid accessing more than once to support CmsProcessableInputStream CmsProcessable content, bool encapsulate) { Asn1EncodableVector digestAlgs = new Asn1EncodableVector(); Asn1EncodableVector signerInfos = new Asn1EncodableVector(); _digests.Clear(); // clear the current preserved digest state // // add the precalculated SignerInfo objects. // foreach (SignerInformation signer in _signers) { digestAlgs.Add(Helper.FixAlgID(signer.DigestAlgorithmID)); // TODO Verify the content type and calculated digest match the precalculated SignerInfo signerInfos.Add(signer.ToSignerInfo()); } // // add the SignerInfo objects // bool isCounterSignature = (signedContentType == null); DerObjectIdentifier contentTypeOid = isCounterSignature ? null : new DerObjectIdentifier(signedContentType); foreach (SignerInf signer in signerInfs) { try { digestAlgs.Add(signer.DigestAlgorithmID); signerInfos.Add(signer.ToSignerInfo(contentTypeOid, content, rand)); } catch (IOException e) { throw new CmsException("encoding error.", e); } catch (InvalidKeyException e) { throw new CmsException("key inappropriate for signature.", e); } catch (SignatureException e) { throw new CmsException("error creating signature.", e); } catch (CertificateEncodingException e) { throw new CmsException("error creating sid.", e); } } Asn1Set certificates = null; if (_certs.Count != 0) { certificates = CmsUtilities.CreateBerSetFromList(_certs); } Asn1Set certrevlist = null; if (_crls.Count != 0) { certrevlist = CmsUtilities.CreateBerSetFromList(_crls); } Asn1OctetString octs = null; if (encapsulate) { MemoryStream bOut = new MemoryStream(); if (content != null) { try { content.Write(bOut); } catch (IOException e) { throw new CmsException("encapsulation error.", e); } } octs = new BerOctetString(bOut.ToArray()); } ContentInfo encInfo = new ContentInfo(contentTypeOid, octs); SignedData sd = new SignedData( new DerSet(digestAlgs), encInfo, certificates, certrevlist, new DerSet(signerInfos)); ContentInfo contentInfo = new ContentInfo(CmsObjectIdentifiers.SignedData, sd); return(new CmsSignedData(content, contentInfo)); }
public static int CalculateVersion(OriginatorInfo originatorInfo, Asn1Set recipientInfos, Asn1Set unprotectedAttrs) { if (originatorInfo != null || unprotectedAttrs != null) { return(2); } foreach (object o in recipientInfos) { RecipientInfo ri = RecipientInfo.GetInstance(o); if (ri.Version.Value.IntValue != 0) { return(2); } } return(0); }
public Org.BouncyCastle.X509.X509Certificate ReadCertificate( Stream inStream) { if (inStream == null) { throw new ArgumentNullException("inStream"); } if (!inStream.CanRead) { throw new ArgumentException("inStream must be read-able", "inStream"); } if (currentStream == null) { currentStream = inStream; sData = null; sDataObjectCount = 0; } else if (currentStream != inStream) // reset if input stream has changed { currentStream = inStream; sData = null; sDataObjectCount = 0; } try { if (sData != null) { if (sDataObjectCount != sData.Count) { return(GetCertificate()); } sData = null; sDataObjectCount = 0; return(null); } var pis = new PushbackStream(inStream); int tag = pis.ReadByte(); if (tag < 0) { return(null); } pis.Unread(tag); if (tag != 0x30) // assume ascii PEM encoded. { return(ReadPemCertificate(pis)); } return(ReadDerCertificate(new Asn1InputStream(pis))); } catch (Exception e) { throw new CertificateException("Failed to read certificate", e); } }
/** * 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 X509Certificate ReadCertificate(Stream inStream) { if (inStream == null) { throw new ArgumentNullException("inStream"); } if (!inStream.CanRead) { throw new ArgumentException("inStream must be read-able", "inStream"); } if (this.currentStream == null) { this.currentStream = inStream; this.sData = null; this.sDataObjectCount = 0; } else if (this.currentStream != inStream) { this.currentStream = inStream; this.sData = null; this.sDataObjectCount = 0; } X509Certificate result; try { if (this.sData != null) { if (this.sDataObjectCount != this.sData.Count) { result = this.GetCertificate(); } else { this.sData = null; this.sDataObjectCount = 0; result = null; } } else { PushbackStream pushbackStream = new PushbackStream(inStream); int num = pushbackStream.ReadByte(); if (num < 0) { result = null; } else { pushbackStream.Unread(num); if (num != 48) { result = this.ReadPemCertificate(pushbackStream); } else { result = this.ReadDerCertificate(new Asn1InputStream(pushbackStream)); } } } } catch (Exception exception) { throw new CertificateException("Failed to read certificate", exception); } return(result); }
public Attribute(DerObjectIdentifier attrType, Asn1Set attrValues) { this.attrType = attrType; this.attrValues = attrValues; }
/// <summary> /// Generate an enveloped object that contains a CMS Enveloped Data /// object using the passed in key generator. /// </summary> private CmsEnvelopedData Generate( CmsProcessable content, string encryptionOid, CipherKeyGenerator keyGen) { AlgorithmIdentifier encAlgId = null; KeyParameter encKey; Asn1OctetString encContent; try { byte[] encKeyBytes = keyGen.GenerateKey(); encKey = ParameterUtilities.CreateKeyParameter(encryptionOid, encKeyBytes); Asn1Encodable asn1Params = GenerateAsn1Parameters(encryptionOid, encKeyBytes); ICipherParameters cipherParameters; encAlgId = GetAlgorithmIdentifier( encryptionOid, encKey, asn1Params, out cipherParameters); IBufferedCipher cipher = CipherUtilities.GetCipher(encryptionOid); cipher.Init(true, new ParametersWithRandom(cipherParameters, rand)); MemoryStream bOut = new MemoryStream(); CipherStream cOut = new CipherStream(bOut, null, cipher); content.Write(cOut); BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(cOut); encContent = new BerOctetString(bOut.ToArray()); } 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); } } EncryptedContentInfo eci = new EncryptedContentInfo( CmsObjectIdentifiers.Data, encAlgId, encContent); Asn1Set unprotectedAttrSet = null; if (unprotectedAttributeGenerator != null) { Asn1.Cms.AttributeTable attrTable = unprotectedAttributeGenerator.GetAttributes(BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable()); unprotectedAttrSet = new BerSet(attrTable.ToAsn1EncodableVector()); } ContentInfo contentInfo = new ContentInfo( CmsObjectIdentifiers.EnvelopedData, new EnvelopedData(null, new DerSet(recipientInfos), eci, unprotectedAttrSet)); return(new CmsEnvelopedData(contentInfo)); }
private void DoClose() { Platform.Dispose(_out); // TODO Parent context(s) should really be be closed explicitly _eiGen.Close(); outer._digests.Clear(); // clear the current preserved digest state if (outer._certs.Count > 0) { Asn1Set certs = CmsUtilities.CreateBerSetFromList(outer._certs); WriteToGenerator(_sigGen, new BerTaggedObject(false, 0, certs)); } if (outer._crls.Count > 0) { Asn1Set crls = CmsUtilities.CreateBerSetFromList(outer._crls); WriteToGenerator(_sigGen, new BerTaggedObject(false, 1, crls)); } // // Calculate the digest hashes // foreach (DictionaryEntry de in outer._messageDigests) { outer._messageHashes.Add(de.Key, DigestUtilities.DoFinal((IDigest)de.Value)); } // TODO If the digest OIDs for precalculated signers weren't mixed in with // the others, we could fill in outer._digests here, instead of SignerInfoGenerator.Generate // // collect all the SignerInfo objects // Asn1EncodableVector signerInfos = new Asn1EncodableVector(); // // add the generated SignerInfo objects // { foreach (DigestAndSignerInfoGeneratorHolder holder in outer._signerInfs) { AlgorithmIdentifier digestAlgorithm = holder.DigestAlgorithm; byte[] calculatedDigest = (byte[])outer._messageHashes[ Helper.GetDigestAlgName(holder.digestOID)]; outer._digests[holder.digestOID] = calculatedDigest.Clone(); signerInfos.Add(holder.signerInf.Generate(_contentOID, digestAlgorithm, calculatedDigest)); } } // // add the precalculated SignerInfo objects. // { foreach (SignerInformation signer in outer._signers) { // TODO Verify the content type and calculated digest match the precalculated SignerInfo // if (!signer.ContentType.Equals(_contentOID)) // { // // TODO The precalculated content type did not match - error? // } // // byte[] calculatedDigest = (byte[])outer._digests[signer.DigestAlgOid]; // if (calculatedDigest == null) // { // // TODO We can't confirm this digest because we didn't calculate it - error? // } // else // { // if (!Arrays.AreEqual(signer.GetContentDigest(), calculatedDigest)) // { // // TODO The precalculated digest did not match - error? // } // } signerInfos.Add(signer.ToSignerInfo()); } } WriteToGenerator(_sigGen, new DerSet(signerInfos)); _sigGen.Close(); _sGen.Close(); }
public Pkcs10CertificationRequestDelaySigned(string signatureAlgorithm, X509Name subject, AsymmetricKeyParameter publicKey, Asn1Set attributes) { if (signatureAlgorithm == null) { throw new ArgumentNullException("signatureAlgorithm"); } if (subject == null) { throw new ArgumentNullException("subject"); } if (publicKey == null) { throw new ArgumentNullException("publicKey"); } if (publicKey.IsPrivate) { throw new ArgumentException("expected public key", "publicKey"); } string text = Platform.ToUpperInvariant(signatureAlgorithm); DerObjectIdentifier derObjectIdentifier = (DerObjectIdentifier)Pkcs10CertificationRequest.algorithms[text]; if (derObjectIdentifier == null) { try { derObjectIdentifier = new DerObjectIdentifier(text); } catch (Exception innerException) { throw new ArgumentException("Unknown signature type requested", innerException); } } if (Pkcs10CertificationRequest.noParams.Contains(derObjectIdentifier)) { sigAlgId = new AlgorithmIdentifier(derObjectIdentifier); } else if (Pkcs10CertificationRequest.exParams.Contains(text)) { sigAlgId = new AlgorithmIdentifier(derObjectIdentifier, (Asn1Encodable)Pkcs10CertificationRequest.exParams[text]); } else { sigAlgId = new AlgorithmIdentifier(derObjectIdentifier, DerNull.Instance); } SubjectPublicKeyInfo pkInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey); reqInfo = new CertificationRequestInfo(subject, pkInfo, attributes); }
// RFC3852, section 5.1: // IF ((certificates is present) AND // (any certificates with a type of other are present)) OR // ((crls is present) AND // (any crls with a type of other are present)) // THEN version MUST be 5 // ELSE // IF (certificates is present) AND // (any version 2 attribute certificates are present) // THEN version MUST be 4 // ELSE // IF ((certificates is present) AND // (any version 1 attribute certificates are present)) OR // (any SignerInfo structures are version 3) OR // (encapContentInfo eContentType is other than id-data) // THEN version MUST be 3 // ELSE version MUST be 1 // private DerInteger CalculateVersion( DerObjectIdentifier contentOid, Asn1Set certs, Asn1Set crls, Asn1Set signerInfs) { bool otherCert = false; bool otherCrl = false; bool attrCertV1Found = false; bool attrCertV2Found = false; if (certs != null) { foreach (object obj in certs) { if (obj is Asn1TaggedObject) { Asn1TaggedObject tagged = (Asn1TaggedObject)obj; if (tagged.TagNo == 1) { attrCertV1Found = true; } else if (tagged.TagNo == 2) { attrCertV2Found = true; } else if (tagged.TagNo == 3) { otherCert = true; break; } } } } if (otherCert) { return(new DerInteger(5)); } if (crls != null) { foreach (object obj in crls) { if (obj is Asn1TaggedObject) { otherCrl = true; break; } } } if (otherCrl) { return(new DerInteger(5)); } if (attrCertV2Found) { return(new DerInteger(4)); } if (attrCertV1Found) { return(new DerInteger(3)); } if (contentOid.Equals(CmsObjectIdentifiers.Data) && !CheckForVersion3(signerInfs)) { return(new DerInteger(1)); } return(new DerInteger(3)); }
protected virtual void LoadPkcs8ShroudedKeyBag(EncryptedPrivateKeyInfo encPrivKeyInfo, Asn1Set bagAttributes, char[] password, bool wrongPkcs12Zero) { if (password != null) { PrivateKeyInfo privInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo( password, wrongPkcs12Zero, encPrivKeyInfo); LoadKeyBag(privInfo, bagAttributes); } }
public CmsEnvelopedData Generate(CmsProcessable content, ICipherBuilderWithKey cipherBuilder) { //AlgorithmIdentifier encAlgId = null; KeyParameter encKey; Asn1OctetString encContent; try { encKey = (KeyParameter)cipherBuilder.Key; MemoryStream collector = new MemoryStream(); Stream bOut = cipherBuilder.BuildCipher(collector).Stream; content.Write(bOut); BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(bOut); encContent = new BerOctetString(collector.ToArray()); } 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); } } EncryptedContentInfo eci = new EncryptedContentInfo( CmsObjectIdentifiers.Data, (AlgorithmIdentifier)cipherBuilder.AlgorithmDetails, encContent); Asn1Set unprotectedAttrSet = null; if (unprotectedAttributeGenerator != null) { Asn1.Cms.AttributeTable attrTable = unprotectedAttributeGenerator.GetAttributes(BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable()); unprotectedAttrSet = new BerSet(attrTable.ToAsn1EncodableVector()); } ContentInfo contentInfo = new ContentInfo( CmsObjectIdentifiers.EnvelopedData, new EnvelopedData(null, new DerSet(recipientInfos), eci, unprotectedAttrSet)); return(new CmsEnvelopedData(contentInfo)); }
internal SignerInfo ToSignerInfo( DerObjectIdentifier contentType, CmsProcessable content, SecureRandom random) { AlgorithmIdentifier digAlgId = DigestAlgorithmID; string digestName = Helper.GetDigestAlgName(digestOID); string signatureName = digestName + "with" + Helper.GetEncryptionAlgName(encOID); byte[] hash; if (outer._digests.Contains(digestOID)) { hash = (byte[])outer._digests[digestOID]; } else { IDigest dig = Helper.GetDigestInstance(digestName); if (content != null) { content.Write(new DigOutputStream(dig)); } hash = DigestUtilities.DoFinal(dig); outer._digests.Add(digestOID, hash.Clone()); } IStreamCalculator calculator = sigCalc.CreateCalculator(); #if NETCF_1_0 || NETCF_2_0 || SILVERLIGHT Stream sigStr = new SigOutputStream(calculator.Stream); #else Stream sigStr = new BufferedStream(calculator.Stream); #endif Asn1Set signedAttr = null; if (sAttr != null) { IDictionary parameters = outer.GetBaseParameters(contentType, digAlgId, hash); // Asn1.Cms.AttributeTable signed = sAttr.GetAttributes(Collections.unmodifiableMap(parameters)); Asn1.Cms.AttributeTable signed = sAttr.GetAttributes(parameters); if (contentType == null) //counter signature { if (signed != null && signed[CmsAttributes.ContentType] != null) { IDictionary tmpSigned = signed.ToDictionary(); tmpSigned.Remove(CmsAttributes.ContentType); signed = new Asn1.Cms.AttributeTable(tmpSigned); } } // TODO Validate proposed signed attributes signedAttr = outer.GetAttributeSet(signed); // sig must be composed from the DER encoding. new DerOutputStream(sigStr).WriteObject(signedAttr); } else if (content != null) { // TODO Use raw signature of the hash value instead content.Write(sigStr); } sigStr.Close(); byte[] sigBytes = ((IBlockResult)calculator.GetResult()).DoFinal(); Asn1Set unsignedAttr = null; if (unsAttr != null) { IDictionary baseParameters = outer.GetBaseParameters(contentType, digAlgId, hash); baseParameters[CmsAttributeTableParameter.Signature] = sigBytes.Clone(); // Asn1.Cms.AttributeTable unsigned = unsAttr.GetAttributes(Collections.unmodifiableMap(baseParameters)); Asn1.Cms.AttributeTable unsigned = unsAttr.GetAttributes(baseParameters); // TODO Validate proposed unsigned attributes unsignedAttr = outer.GetAttributeSet(unsigned); } // TODO[RSAPSS] Need the ability to specify non-default parameters Asn1Encodable sigX509Parameters = SignerUtilities.GetDefaultX509Parameters(signatureName); AlgorithmIdentifier encAlgId = Helper.GetEncAlgorithmIdentifier( new DerObjectIdentifier(encOID), sigX509Parameters); return(new SignerInfo(signerIdentifier, digAlgId, signedAttr, encAlgId, new DerOctetString(sigBytes), unsignedAttr)); }
public Pkcs10CertificationRequestDelaySigned(string signatureAlgorithm, X509Name subject, AsymmetricKeyParameter publicKey, Asn1Set attributes, AsymmetricKeyParameter signingKey) : base(signatureAlgorithm, subject, publicKey, attributes, signingKey) { }
/// <summary> /// Instantiate a Pkcs10CertificationRequest object with the necessary credentials. /// </summary> ///<param name="signatureAlgorithm">Name of Sig Alg.</param> /// <param name="subject">X509Name of subject eg OU="My unit." O="My Organisatioin" C="au" </param> /// <param name="publicKey">Public Key to be included in cert reqest.</param> /// <param name="attributes">ASN1Set of Attributes.</param> /// <param name="signingKey">Matching Private key for nominated (above) public key to be used to sign the request.</param> public Pkcs10CertificationRequest( string signatureAlgorithm, X509Name subject, AsymmetricKeyParameter publicKey, Asn1Set attributes, AsymmetricKeyParameter signingKey) { if (signatureAlgorithm == null) { throw new ArgumentNullException("signatureAlgorithm"); } if (subject == null) { throw new ArgumentNullException("subject"); } if (publicKey == null) { throw new ArgumentNullException("publicKey"); } if (publicKey.IsPrivate) { throw new ArgumentException("expected public key", "publicKey"); } if (!signingKey.IsPrivate) { throw new ArgumentException("key for signing must be private", "signingKey"); } // DerObjectIdentifier sigOid = SignerUtilities.GetObjectIdentifier(signatureAlgorithm); string algorithmName = signatureAlgorithm.ToUpper(CultureInfo.InvariantCulture); DerObjectIdentifier sigOid = (DerObjectIdentifier)algorithms[algorithmName]; if (sigOid == null) { try { sigOid = new DerObjectIdentifier(algorithmName); } catch (Exception e) { throw new ArgumentException("Unknown signature type requested", e); } } if (noParams.Contains(sigOid)) { this.sigAlgId = new AlgorithmIdentifier(sigOid); } else if (exParams.Contains(algorithmName)) { this.sigAlgId = new AlgorithmIdentifier(sigOid, (Asn1Encodable)exParams[algorithmName]); } else { this.sigAlgId = new AlgorithmIdentifier(sigOid, DerNull.Instance); } SubjectPublicKeyInfo pubInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey); this.reqInfo = new CertificationRequestInfo(subject, pubInfo, attributes); ISigner sig = SignerUtilities.GetSigner(signatureAlgorithm); sig.Init(true, signingKey); try { // Encode. byte[] b = reqInfo.GetDerEncoded(); sig.BlockUpdate(b, 0, b.Length); } catch (Exception e) { throw new ArgumentException("exception encoding TBS cert request", e); } // Generate Signature. sigBits = new DerBitString(sig.GenerateSignature()); }
/** * Generates a certificate revocation list (CRL) object and initializes * it with the data read from the input stream inStream. */ public X509Crl ReadCrl( Stream inStream) { if (inStream == null) { throw new ArgumentNullException("inStream"); } if (!inStream.CanRead) { throw new ArgumentException("inStream must be read-able", "inStream"); } if (currentCrlStream == null) { currentCrlStream = inStream; sCrlData = null; sCrlDataObjectCount = 0; } else if (currentCrlStream != inStream) // reset if input stream has changed { currentCrlStream = inStream; sCrlData = null; sCrlDataObjectCount = 0; } try { if (sCrlData != null) { if (sCrlDataObjectCount != sCrlData.Count) { return(GetCrl()); } sCrlData = null; sCrlDataObjectCount = 0; return(null); } PushbackStream pis = new PushbackStream(inStream); int tag = pis.ReadByte(); if (tag < 0) { return(null); } pis.Unread(tag); if (tag != 0x30) // assume ascii PEM encoded. { return(ReadPemCrl(pis)); } Asn1InputStream asn1 = lazyAsn1 ? new LazyAsn1InputStream(pis) : new Asn1InputStream(pis); return(ReadDerCrl(asn1)); } catch (CrlException e) { throw e; } catch (Exception e) { throw new CrlException(e.ToString()); } }
public CmsSignedData Generate(string signedContentType, CmsProcessable content, bool encapsulate) { Asn1EncodableVector asn1EncodableVector = new Asn1EncodableVector(new Asn1Encodable[0]); Asn1EncodableVector asn1EncodableVector2 = new Asn1EncodableVector(new Asn1Encodable[0]); this._digests.Clear(); foreach (SignerInformation signerInformation in this._signers) { asn1EncodableVector.Add(new Asn1Encodable[] { CmsSignedDataGenerator.Helper.FixAlgID(signerInformation.DigestAlgorithmID) }); asn1EncodableVector2.Add(new Asn1Encodable[] { signerInformation.ToSignerInfo() }); } DerObjectIdentifier contentType = (signedContentType == null) ? null : new DerObjectIdentifier(signedContentType); foreach (CmsSignedDataGenerator.SignerInf signerInf in this.signerInfs) { try { asn1EncodableVector.Add(new Asn1Encodable[] { signerInf.DigestAlgorithmID }); asn1EncodableVector2.Add(new Asn1Encodable[] { signerInf.ToSignerInfo(contentType, content, this.rand) }); } catch (IOException e) { throw new CmsException("encoding error.", e); } catch (InvalidKeyException e2) { throw new CmsException("key inappropriate for signature.", e2); } catch (SignatureException e3) { throw new CmsException("error creating signature.", e3); } catch (CertificateEncodingException e4) { throw new CmsException("error creating sid.", e4); } } Asn1Set certificates = null; if (this._certs.Count != 0) { certificates = CmsUtilities.CreateBerSetFromList(this._certs); } Asn1Set crls = null; if (this._crls.Count != 0) { crls = CmsUtilities.CreateBerSetFromList(this._crls); } Asn1OctetString content2 = null; if (encapsulate) { MemoryStream memoryStream = new MemoryStream(); if (content != null) { try { content.Write(memoryStream); } catch (IOException e5) { throw new CmsException("encapsulation error.", e5); } } content2 = new BerOctetString(memoryStream.ToArray()); } ContentInfo contentInfo = new ContentInfo(contentType, content2); SignedData content3 = new SignedData(new DerSet(asn1EncodableVector), contentInfo, certificates, crls, new DerSet(asn1EncodableVector2)); ContentInfo sigData = new ContentInfo(CmsObjectIdentifiers.SignedData, content3); return(new CmsSignedData(content, sigData)); }
/** * Generates a certificate revocation list (CRL) object and initializes * it with the data read from the input stream inStream. */ public X509Crl ReadCrl( Stream inStream) { if (inStream == null) { throw new ArgumentNullException("inStream"); } if (!inStream.CanRead) { throw new ArgumentException("inStream must be read-able", "inStream"); } // TODO Remove this restriction? if (!inStream.CanSeek) { throw new ArgumentException("inStream must be seek-able", "inStream"); } if (currentCrlStream == null) { currentCrlStream = inStream; sCrlData = null; sCrlDataObjectCount = 0; } else if (currentCrlStream != inStream) // reset if input stream has changed { currentCrlStream = inStream; sCrlData = null; sCrlDataObjectCount = 0; } try { if (sCrlData != null) { if (sCrlDataObjectCount != sCrlData.Count) { return(GetCrl()); } sCrlData = null; sCrlDataObjectCount = 0; return(null); } // if (!inStream.markSupported()) // { // inStream = new BufferedInputStream(inStream); // } // // inStream.mark(10); long pos = inStream.Position; int tag; if ((tag = inStream.ReadByte()) < 0) { return(null); } if (tag != 0x30) // assume ascii PEM encoded. { inStream.Seek(pos, SeekOrigin.Begin); return(ReadPemCrl(inStream)); } if ((tag = inStream.ReadByte()) < 0) { return(null); } inStream.Seek(pos, SeekOrigin.Begin); return(ReadDerCrl(new Asn1InputStream(inStream))); } catch (CrlException e) { throw e; } catch (Exception e) { throw new CrlException(e.ToString()); } }
private Attributes(Asn1Set attributes) { this.attributes = attributes; }
private DerInteger CalculateVersion(DerObjectIdentifier contentOid, Asn1Set certs, Asn1Set crls, Asn1Set signerInfs) { bool flag = false; bool flag2 = false; bool flag3 = false; bool flag4 = false; if (certs != null) { { global::System.Collections.IEnumerator enumerator = certs.GetEnumerator(); try { while (enumerator.MoveNext()) { object current = enumerator.get_Current(); if (current is Asn1TaggedObject) { Asn1TaggedObject asn1TaggedObject = (Asn1TaggedObject)current; if (asn1TaggedObject.TagNo == 1) { flag3 = true; } else if (asn1TaggedObject.TagNo == 2) { flag4 = true; } else if (asn1TaggedObject.TagNo == 3) { flag = true; break; } } } } finally { global::System.IDisposable disposable = enumerator as global::System.IDisposable; if (disposable != null) { disposable.Dispose(); } } } } if (flag) { return(Version5); } if (crls != null) { { global::System.Collections.IEnumerator enumerator = crls.GetEnumerator(); try { while (enumerator.MoveNext()) { object current2 = enumerator.get_Current(); if (current2 is Asn1TaggedObject) { flag2 = true; break; } } } finally { global::System.IDisposable disposable2 = enumerator as global::System.IDisposable; if (disposable2 != null) { disposable2.Dispose(); } } } } if (flag2) { return(Version5); } if (flag4) { return(Version4); } if (flag3 || !CmsObjectIdentifiers.Data.Equals(contentOid) || CheckForVersion3(signerInfs)) { return(Version3); } return(Version1); }
public Attribute( Asn1Sequence seq) { attrType = (DerObjectIdentifier)seq[0]; attrValues = (Asn1Set)seq[1]; }