internal static string GetCertificatePolicyId(X509Certificate cert, int certificatePolicyPos = 0, int policyIdentifierPos = 0) { try { byte[] extPolicyBytes = cert.GetExtensionValue(CERTIFICATE_POLICY_OID).GetOctets(); if (extPolicyBytes == null) { return(null); } DerOctetString oct = (DerOctetString)cert.GetExtensionValue(CERTIFICATE_POLICY_OID); Asn1Sequence seq = (Asn1Sequence) new Asn1InputStream(oct.GetOctets()).ReadObject(); if (seq.Count <= (certificatePolicyPos)) { return(null); } CertificatePolicies certificatePolicies = new CertificatePolicies( PolicyInformation.GetInstance(seq[certificatePolicyPos])); PolicyInformation[] policyInformation = certificatePolicies.GetPolicyInformation(); return(policyInformation[0].PolicyIdentifier.Id); } catch (Exception ex) { Console.WriteLine(ex); return(null); } }
// Time Stamp Authority /** * Gets the URL of the TSA if it's available on the certificate * @param certificate a certificate * @return a TSA URL * @throws IOException */ public static String GetTSAURL(X509Certificate certificate) { Asn1OctetString octetString = certificate.GetExtensionValue(SecurityIDs.ID_TSA); if (octetString == null) { return(null); } byte[] der = octetString.GetOctets(); if (der == null) { return(null); } Asn1Object asn1obj; try { asn1obj = Asn1Object.FromByteArray(der); if (asn1obj is DerOctetString) { DerOctetString octets = (DerOctetString)asn1obj; asn1obj = Asn1Object.FromByteArray(octets.GetOctets()); } Asn1Sequence asn1seq = Asn1Sequence.GetInstance(asn1obj); return(GetStringFromGeneralName(asn1seq[1].ToAsn1Object())); } catch (IOException) { return(null); } }
public virtual bool Check(CertificateAndContext cert) { if (cert is null) { throw new System.ArgumentNullException(nameof(cert)); } Asn1OctetString qcStatement = cert.Certificate.GetExtensionValue(X509Extensions.QCStatements); if (qcStatement != null) { DerOctetString s = (DerOctetString)qcStatement; byte[] content = s.GetOctets(); using (Asn1InputStream input = new Asn1InputStream(content)) { DerSequence seq = (DerSequence)input.ReadObject(); for (int i = 0; i < seq.Count; i++) { QCStatement statement = QCStatement.GetInstance(seq[i]); if (statement.StatementId.Id.Equals(qcStatementId, System.StringComparison.OrdinalIgnoreCase)) { return(true); } } return(false); } } return(false); }
private BigInteger GetCrlNumber(X509Crl crl) { //byte[] crlNumberExtensionValue = crl.GetExtensionValue(X509Extensions.CrlNumber); Asn1OctetString crlNumberExtensionValue = crl.GetExtensionValue(X509Extensions.CrlNumber); if (null == crlNumberExtensionValue) { return(null); } //try //{ //DerOctetString octetString = (DerOctetString)(new ASN1InputStream(new ByteArrayInputStream // (crlNumberExtensionValue)).ReadObject()); DerOctetString octetString = (DerOctetString)crlNumberExtensionValue; byte[] octets = octetString.GetOctets(); DerInteger integer = (DerInteger) new Asn1InputStream(octets).ReadObject(); BigInteger crlNumber = integer.PositiveValue; return(crlNumber); //} //catch (IOException e) //{ // throw new RuntimeException("IO error: " + e.Message, e); //} }
/// <summary> /// Gets the CRL URLs from the CRL Distribution Points extension /// </summary> /// <param name="certificate"><seealso cref="Org.BouncyCastle.X509.X509Certificate"/></param> /// <returns>CRL URLs from the CRL Distribution Points extension</returns> public static List <Uri> GetCrlDistributionPoints(this Org.BouncyCastle.X509.X509Certificate certificate) { List <Uri> crlUrls = new List <Uri>(); if (certificate == null) { return(crlUrls); } var cdpExtention = certificate.GetExtensionValue(X509Extensions.CrlDistributionPoints); if (cdpExtention == null) { return(crlUrls); } byte[] crldpExt = cdpExtention.GetDerEncoded(); if (crldpExt == null) { return(crlUrls); } Asn1InputStream oAsnInStream = new Asn1InputStream(crldpExt); var derObjCrlDP = oAsnInStream.ReadObject(); DerOctetString dosCrlDP = (DerOctetString)derObjCrlDP; byte[] crldpExtOctets = dosCrlDP.GetOctets(); Asn1InputStream oAsnInStream2 = new Asn1InputStream(crldpExtOctets); var derObj2 = oAsnInStream2.ReadObject(); CrlDistPoint distPoint = CrlDistPoint.GetInstance(derObj2); foreach (DistributionPoint dp in distPoint.GetDistributionPoints()) { DistributionPointName dpn = dp.DistributionPointName; // Look for URIs in fullName if (dpn != null) { if (dpn.GetType() == typeof(Org.BouncyCastle.Asn1.X509.DistributionPointName)) { GeneralName[] genNames = GeneralNames.GetInstance(dpn.Name).GetNames(); // Look for an URI for (int j = 0; j < genNames.Length; j++) { if (genNames[j].TagNo == GeneralName.UniformResourceIdentifier) { Uri uri; String url = DerIA5String.GetInstance(genNames[j].Name).GetString(); if (Uri.TryCreate(url, UriKind.Absolute, out uri)) { crlUrls.Add(uri); } } } } } } return(crlUrls); }
public virtual bool Check(CertificateAndContext cert) { if (cert is null) { throw new System.ArgumentNullException(nameof(cert)); } Asn1OctetString certificatePolicies = cert.Certificate.GetExtensionValue(X509Extensions.CertificatePolicies); if (certificatePolicies != null) { DerOctetString s = (DerOctetString)certificatePolicies; byte[] content = s.GetOctets(); using (Asn1InputStream input = new Asn1InputStream(content)) { DerSequence seq = (DerSequence)input.ReadObject(); for (int i = 0; i < seq.Count; i++) { PolicyInformation policyInfo = PolicyInformation.GetInstance(seq[i]); if (policyInfo.PolicyIdentifier.Id.Equals(policyOid, System.StringComparison.OrdinalIgnoreCase)) { return(true); } } } } return(false); }
private string GetOcspUrlFromCertificate(X509Certificate cert) { var derId = new DerObjectIdentifier(X509Extensions.AuthorityInfoAccess.Id); byte[] extensionValue = cert.GetExtensionValue(derId).GetOctets(); Asn1Sequence asn1Seq = (Asn1Sequence)Asn1Object.FromByteArray(extensionValue); // AuthorityInfoAccessSyntax // Enumeration <?> objects = asn1Seq.Objects; string result = null; foreach (Asn1Sequence obj in asn1Seq) { DerObjectIdentifier oid = (DerObjectIdentifier)obj[0]; // accessMethod DerTaggedObject location = (DerTaggedObject)obj[1]; // accessLocation if (location.TagNo == GeneralName.UniformResourceIdentifier) { DerOctetString uri = (DerOctetString)location.GetObject(); String str = Encoding.Default.GetString(uri.GetOctets()); if (oid.Equals(X509ObjectIdentifiers.IdADOcsp)) { result = str; break; } } } //while (objects.hasMoreElements()) //{ // ASN1Sequence obj = (ASN1Sequence)objects.nextElement(); // AccessDescription //} return(result); }
public virtual bool Check(CertificateAndContext cert) { //TODO jbonilla - validar. //byte[] certificatePolicies = cert.GetCertificate().GetExtensionValue(X509Extensions.CertificatePolicies); Asn1OctetString certificatePolicies = cert.GetCertificate().GetExtensionValue(X509Extensions.CertificatePolicies); if (certificatePolicies != null) { try { //Asn1InputStream input = new Asn1InputStream(certificatePolicies); //DerOctetString s = (DerOctetString)input.ReadObject(); DerOctetString s = (DerOctetString)certificatePolicies; byte[] content = s.GetOctets(); Asn1InputStream input = new Asn1InputStream(content); DerSequence seq = (DerSequence)input.ReadObject(); for (int i = 0; i < seq.Count; i++) { PolicyInformation policyInfo = PolicyInformation.GetInstance(seq[i]); if (policyInfo.PolicyIdentifier.Id.Equals(policyOid)) { return(true); } } } catch (IOException e) { throw new RuntimeException(e); } } return(false); }
public virtual bool Check(CertificateAndContext cert) { //TODO jbonilla - Validar //byte[] qcStatement = cert.GetCertificate().GetExtensionValue(X509Extensions.QCStatements); Asn1OctetString qcStatement = cert.GetCertificate().GetExtensionValue(X509Extensions.QCStatements); if (qcStatement != null) { try { //Asn1InputStream input = new Asn1InputStream(qcStatement); //DerOctetString s = (DerOctetString)input.ReadObject(); DerOctetString s = (DerOctetString)qcStatement; byte[] content = s.GetOctets(); Asn1InputStream input = new Asn1InputStream(content); DerSequence seq = (DerSequence)input.ReadObject(); for (int i = 0; i < seq.Count; i++) { QCStatement statement = QCStatement.GetInstance(seq[i]); if (statement.StatementId.Id.Equals(qcStatementId)) { return(true); } } return(false); } catch (IOException e) { throw new RuntimeException(e); } } return(false); }
/// <summary> /// Parses and checks contents of the DICE extension /// </summary> /// <param name="c">Certificate to validate</param> /// <returns>Extension is well formed</returns> bool CheckDICEExtension(X509Certificate c) { var criticalOids = c.GetCriticalExtensionOids(); if (criticalOids.Contains(DICEExtensionOid)) { Error("DICE extension is marked critical and should be non-critical"); return(false); } var nonCriticalOids = c.GetNonCriticalExtensionOids(); if (!nonCriticalOids.Contains(DICEExtensionOid)) { Error("DICE extension not found"); return(false); } var diceExtension = c.GetExtensionValue(new DerObjectIdentifier(DICEExtensionOid)); try { DerOctetString envelope = (DerOctetString)DerOctetString.FromByteArray(diceExtension.GetEncoded()); DerSequence seq = (DerSequence)DerSequence.FromByteArray(envelope.GetOctets()); // first field is version number var versionNumber = (DerInteger)seq[0]; if (versionNumber.PositiveValue.IntValue != 1) { Error($"DICE Extension has Wrong version number. Expecing {DICEExtensionVersionNumber}, cert contains {versionNumber.ToString()}"); return(false); } // second field is DeviceID var devIdPubKey = SubjectPublicKeyInfo.GetInstance(seq[1]); // will check it's good later PubKeyInfoFromDICEExtension = devIdPubKey; // third field contains {hashOid, hashVal} var hashEnvelope = (DerSequence)seq[2]; var hashAlg = (DerObjectIdentifier)hashEnvelope[0]; if (hashAlg.Id != NistObjectIdentifiers.IdSha256.ToString()) { Error("DICE Extension hash alg is wrong. "); return(false); } var hashVal = (DerOctetString)hashEnvelope[1]; if (hashVal.GetOctets().Length != 32) { Error("DICE Extension hash value length is wrong. "); return(false); } } catch (Exception e) { Error($"Failed to parse the DICE extension. Parsing exception was {e.ToString()}"); return(false); } return(true); }
// 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)); }
protected override bool Asn1Equals(Asn1Object asn1Object) { DerOctetString derOctetString = asn1Object as DerOctetString; if (derOctetString == null) { return(false); } return(Arrays.AreEqual(GetOctets(), derOctetString.GetOctets())); }
public static byte[] GetPListBytes(Asn1Object rootObject) { Asn1Object plistObj = Asn1Helper.FindAsn1Value(PListOID, rootObject); if (plistObj is DerTaggedObject) { DerOctetString value = ((DerTaggedObject)plistObj).GetObject() as DerOctetString; if (value != null) { return(value.GetOctets()); } } return(null); }
/// <summary> /// Método que busca en las demás firmas el message-digest que coincida con el algoritmo de huella dado /// </summary> /// <param name="siStore"></param> /// <param name="digestMethod"></param> /// <returns></returns> private byte[] GetDigestValue(SignerInformationStore siStore, DigestMethod digestMethod) { var signers = siStore.GetSigners(); foreach (SignerInformation signerInfo in signers) { if (signerInfo.DigestAlgOid == digestMethod.Oid) { BcCms.Attribute digest = signerInfo.SignedAttributes[PkcsObjectIdentifiers.Pkcs9AtMessageDigest]; DerOctetString derHash = (DerOctetString)digest.AttrValues[0]; return(derHash.GetOctets()); } } return(null); }
/// <exception cref="System.IO.IOException"></exception> private string GetAccessLocation(X509Certificate certificate, DerObjectIdentifier accessMethod) { //byte[] authInfoAccessExtensionValue = certificate.GetExtensionValue(X509Extensions // .AuthorityInfoAccess); Asn1OctetString authInfoAccessExtensionValue = certificate.GetExtensionValue(X509Extensions .AuthorityInfoAccess); if (null == authInfoAccessExtensionValue) { return(null); } AuthorityInformationAccess authorityInformationAccess; //DerOctetString oct = (DerOctetString)(new Asn1InputStream(new MemoryStream // (authInfoAccessExtensionValue)).ReadObject()); DerOctetString oct = (DerOctetString)authInfoAccessExtensionValue; //authorityInformationAccess = new AuthorityInformationAccess((Asn1Sequence)new Asn1InputStream // (oct.GetOctets()).ReadObject()); authorityInformationAccess = AuthorityInformationAccess.GetInstance((Asn1Sequence) new Asn1InputStream (oct.GetOctets()).ReadObject()); AccessDescription[] accessDescriptions = authorityInformationAccess.GetAccessDescriptions (); foreach (AccessDescription accessDescription in accessDescriptions) { LOG.Info("access method: " + accessDescription.AccessMethod); bool correctAccessMethod = accessDescription.AccessMethod.Equals(accessMethod ); if (!correctAccessMethod) { continue; } GeneralName gn = accessDescription.AccessLocation; if (gn.TagNo != GeneralName.UniformResourceIdentifier) { LOG.Info("not a uniform resource identifier"); continue; } DerIA5String str = (DerIA5String)((DerTaggedObject)gn.ToAsn1Object()).GetObject(); string accessLocation = str.GetString(); LOG.Info("access location: " + accessLocation); return(accessLocation); } return(null); }
// Time Stamp Authority /// <summary>Gets the URL of the TSA if it's available on the certificate</summary> /// <param name="certificate">a certificate</param> /// <returns>a TSA URL</returns> public static String GetTSAURL(X509Certificate certificate) { byte[] der = SignUtils.GetExtensionValueByOid(certificate, SecurityIDs.ID_TSA); if (der == null) { return(null); } Asn1Object asn1obj; try { asn1obj = Asn1Object.FromByteArray(der); DerOctetString octets = (DerOctetString)asn1obj; asn1obj = Asn1Object.FromByteArray(octets.GetOctets()); Asn1Sequence asn1seq = Asn1Sequence.GetInstance(asn1obj); return(GetStringFromGeneralName(asn1seq[1].ToAsn1Object())); } catch (System.IO.IOException) { return(null); } }
/// <summary> /// /// </summary> /// <param name="x509_certificate2"></param> /// <param name="plain_data"></param> /// <returns></returns> public byte[] GetEncryptedContent(X509Certificate2 x509_certificate2, byte[] plain_data) { tDESCrypto _cryptoService = new tDESCrypto(); // RecipientInfo 구조체 생성 및 설정 RecipientInfo _recipientInfo = this.GetKeyTransRecipientInfo(x509_certificate2, _cryptoService.Key); // EncryptedContentInfo 구조체 생성 및 설정 DerOctetString _taxInvoce = new DerOctetString(plain_data); byte[] _package = _taxInvoce.GetOctets(); byte[] _encrypt = _cryptoService.Encrypt(_package); // 대칭키로 암호화 EncryptedContentInfo _encryptedContentInfo = this.GetEncryptedContentInfo(_encrypt, _cryptoService.IV); // EnvelopedData 구조체 생성 및 설정 Asn1Set _receipientInfos = new DerSet(_recipientInfo); EnvelopedData _envelopedData = new EnvelopedData((OriginatorInfo)null, _receipientInfos, _encryptedContentInfo, (Asn1Set)null); Org.BouncyCastle.Asn1.Cms.ContentInfo _content = new Org.BouncyCastle.Asn1.Cms.ContentInfo(new DerObjectIdentifier("1.2.840.113549.1.7.3"), _envelopedData); return(_content.GetEncoded()); }
private void EncodePublicKey() { X9ECParameters ecP = X962NamedCurves.GetByOid(X9ObjectIdentifiers.Prime239v3); if (X9IntegerConverter.GetByteLength(ecP.Curve) != 30) { Fail("wrong byte length reported for curve"); } if (ecP.Curve.FieldSize != 239) { Fail("wrong field size reported for curve"); } // // named curve // X962Parameters _params = new X962Parameters(X9ObjectIdentifiers.Prime192v1); ECPoint point = ecP.G.Multiply(BigInteger.ValueOf(100)); DerOctetString p = new DerOctetString(point.GetEncoded(true)); SubjectPublicKeyInfo info = new SubjectPublicKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.IdECPublicKey, _params), p.GetOctets()); if (!Arrays.AreEqual(info.GetEncoded(), namedPub)) { Fail("failed public named generation"); } X9ECPoint x9P = new X9ECPoint(ecP.Curve, p); if (!Arrays.AreEqual(p.GetOctets(), x9P.Point.GetEncoded())) { Fail("point encoding not preserved"); } Asn1Object o = Asn1Object.FromByteArray(namedPub); if (!info.Equals(o)) { Fail("failed public named equality"); } // // explicit curve parameters // _params = new X962Parameters(ecP); info = new SubjectPublicKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.IdECPublicKey, _params), p.GetOctets()); if (!Arrays.AreEqual(info.GetEncoded(), expPub)) { Fail("failed public explicit generation"); } o = Asn1Object.FromByteArray(expPub); if (!info.Equals(o)) { Fail("failed public explicit equality"); } }
private void AddAsn1Object(string name, DataKey root, Asn1Object obj, int level, Logger logger) { Asn1Sequence seq = obj as Asn1Sequence; Asn1Set set = obj as Asn1Set; Asn1TaggedObject tag = obj as Asn1TaggedObject; string currName = name ?? obj.GetType().Name; System.Diagnostics.Trace.WriteLine(String.Format("{0} {1}", currName, obj.GetType())); if (seq != null) { if (!Config.IgnoreSequences) { DataKey key = new Asn1SequenceKey(currName, Config.NoVerify); foreach (Asn1Object o in seq) { AddAsn1Object(null, key, o, level + 1, logger); } root.AddSubNode(key); } else { root.AddValue(currName, obj.GetDerEncoded()); } } else if (set != null) { if (!Config.IgnoreSets) { DataKey key = new Asn1SetKey(currName, Config.NoVerify); foreach (Asn1Object o in set) { AddAsn1Object(null, key, o, level + 1, logger); } root.AddSubNode(key); } else { root.AddValue(currName, obj.GetDerEncoded()); } } else if (tag != null) { if (!Config.IgnoreTaggedObjects) { DataKey key = new Asn1TaggedObjectKey(currName, tag.TagNo, Config.NoVerify); root.AddSubNode(key); Asn1Object o = tag.GetObject(); DerOctetString oct = o as DerOctetString; AddAsn1Object("Object", key, tag.GetObject(), level + 1, logger); //if (oct != null) //{ // Asn1InputStream input = new Asn1InputStream(oct.GetOctetStream()); // try // { // Asn1Object next = input.ReadObject(); // if (next == null) // { // AddAsn1Object("Object", key, o, logger); // } // else // { // Asn1OctetStringObject newRoot = new Asn1OctetStringObject("Object"); // while (next != null) // { // AddAsn1Object(next.GetType().Name, newRoot, next, logger); // next = input.ReadObject(); // } // key.AddSubNode(newRoot); // } // } // catch (IOException) // { // AddAsn1Object("Object", key, o, logger); // } //} //else //{ // AddAsn1Object("Object", key, tag.GetObject(), logger); //} } else { root.AddValue(currName, obj.GetDerEncoded()); } } else { if (!Config.NoDecode) { DerStringBase str = obj as DerStringBase; DerObjectIdentifier oid = obj as DerObjectIdentifier; DerInteger i = obj as DerInteger; DerOctetString oct = obj as DerOctetString; DerBitString bits = obj as DerBitString; DerBoolean boo = obj as DerBoolean; DerNull n = obj as DerNull; DerUtcTime time = obj as DerUtcTime; DerGeneralizedTime gt = obj as DerGeneralizedTime; DerApplicationSpecific app = obj as DerApplicationSpecific; if (oct != null) { root.AddValue(new Asn1OctetStringValue(currName, oct.GetOctets())); } else if (bits != null) { root.AddSubNode(new Asn1BitStringKey(currName, bits.PadBits, bits.GetBytes())); } else if (str != null) { Type stringType = typeof(Asn1StringValue <>).MakeGenericType(str.GetType()); root.AddValue((DataValue)Activator.CreateInstance(stringType, currName, str.GetString())); } else if (oid != null) { root.AddValue(new Asn1ObjectIdentifierValue(currName, oid.Id)); } else if (i != null) { root.AddValue(new Asn1IntegerValue(currName, i.Value.ToByteArray())); } else if (boo != null) { root.AddValue(new Asn1BooleanValue(currName, boo.IsTrue)); } else if (n != null) { root.AddValue(new Asn1NullValue(currName)); } else if (time != null) { root.AddValue(new Asn1DateTimeValue(currName, time.ToDateTime())); } else if (gt != null) { root.AddValue(new Asn1GeneralizedTimeValue(currName, gt.ToDateTime())); } else if (app != null) { root.AddSubNode(new Asn1ApplicationSpecificValue(currName, app.ApplicationTag, app.GetContents())); } else { logger.LogError("Cannot convert type {0} to a class", obj.GetType().Name); root.AddValue(currName, obj.GetDerEncoded()); } } else { root.AddValue(currName, obj.GetDerEncoded()); } } }
public static AsymmetricKeyParameter CreateKey( PrivateKeyInfo keyInfo) { AlgorithmIdentifier algID = keyInfo.AlgorithmID; if (algID.ObjectID.Equals(PkcsObjectIdentifiers.RsaEncryption)) { RsaPrivateKeyStructure keyStructure = new RsaPrivateKeyStructure( (Asn1Sequence)keyInfo.PrivateKey); return(new RsaPrivateCrtKeyParameters( keyStructure.Modulus, keyStructure.PublicExponent, keyStructure.PrivateExponent, keyStructure.Prime1, keyStructure.Prime2, keyStructure.Exponent1, keyStructure.Exponent2, keyStructure.Coefficient)); } else if (algID.ObjectID.Equals(PkcsObjectIdentifiers.DhKeyAgreement)) { DHParameter para = new DHParameter((Asn1Sequence)algID.Parameters); DerInteger derX = (DerInteger)keyInfo.PrivateKey; return(new DHPrivateKeyParameters(derX.Value, new DHParameters(para.P, para.G))); } else if (algID.ObjectID.Equals(OiwObjectIdentifiers.ElGamalAlgorithm)) { ElGamalParameter para = new ElGamalParameter((Asn1Sequence)algID.Parameters); DerInteger derX = (DerInteger)keyInfo.PrivateKey; return(new ElGamalPrivateKeyParameters(derX.Value, new ElGamalParameters(para.P, para.G))); } else if (algID.ObjectID.Equals(X9ObjectIdentifiers.IdDsa)) { DsaParameter para = DsaParameter.GetInstance(algID.Parameters); DerInteger derX = (DerInteger)keyInfo.PrivateKey; return(new DsaPrivateKeyParameters(derX.Value, new DsaParameters(para.P, para.Q, para.G))); } else if (algID.ObjectID.Equals(X9ObjectIdentifiers.IdECPublicKey)) { X962Parameters para = new X962Parameters((Asn1Object)algID.Parameters); ECDomainParameters dParams = null; if (para.IsNamedCurve) { DerObjectIdentifier oid = (DerObjectIdentifier)para.Parameters; X9ECParameters ecP = X962NamedCurves.GetByOid(oid); if (ecP == null) { ecP = SecNamedCurves.GetByOid(oid); if (ecP == null) { ecP = NistNamedCurves.GetByOid(oid); } } dParams = new ECDomainParameters( ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed()); } else { X9ECParameters ecP = new X9ECParameters( (Asn1Sequence)para.Parameters); dParams = new ECDomainParameters( ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed()); } ECPrivateKeyStructure ec = new ECPrivateKeyStructure((Asn1Sequence)keyInfo.PrivateKey); return(new ECPrivateKeyParameters(ec.GetKey(), dParams)); } else if (algID.ObjectID.Equals(CryptoProObjectIdentifiers.GostR3410x2001)) { throw new NotImplementedException(); } else if (algID.ObjectID.Equals(CryptoProObjectIdentifiers.GostR3410x94)) { Gost3410PublicKeyAlgParameters algParams = new Gost3410PublicKeyAlgParameters( (Asn1Sequence)algID.Parameters); DerOctetString derX = (DerOctetString)keyInfo.PrivateKey; byte[] keyEnc = derX.GetOctets(); byte[] keyBytes = new byte[keyEnc.Length]; for (int i = 0; i != keyEnc.Length; i++) { keyBytes[i] = keyEnc[keyEnc.Length - 1 - i]; // was little endian } BigInteger x = new BigInteger(1, keyBytes); return(new Gost3410PrivateKeyParameters(x, algParams.PublicKeyParamSet)); } else { throw new SecurityUtilityException("algorithm identifier in key not recognised"); } }
public static AsymmetricKeyParameter CreateKey(PrivateKeyInfo keyInfo) { //IL_02a2: Unknown result type (might be due to invalid IL or missing references) AlgorithmIdentifier privateKeyAlgorithm = keyInfo.PrivateKeyAlgorithm; DerObjectIdentifier algorithm = privateKeyAlgorithm.Algorithm; if (algorithm.Equals(PkcsObjectIdentifiers.RsaEncryption) || algorithm.Equals(X509ObjectIdentifiers.IdEARsa) || algorithm.Equals(PkcsObjectIdentifiers.IdRsassaPss) || algorithm.Equals(PkcsObjectIdentifiers.IdRsaesOaep)) { RsaPrivateKeyStructure instance = RsaPrivateKeyStructure.GetInstance(keyInfo.ParsePrivateKey()); return(new RsaPrivateCrtKeyParameters(instance.Modulus, instance.PublicExponent, instance.PrivateExponent, instance.Prime1, instance.Prime2, instance.Exponent1, instance.Exponent2, instance.Coefficient)); } if (algorithm.Equals(PkcsObjectIdentifiers.DhKeyAgreement)) { DHParameter dHParameter = new DHParameter(Asn1Sequence.GetInstance(privateKeyAlgorithm.Parameters.ToAsn1Object())); DerInteger derInteger = (DerInteger)keyInfo.ParsePrivateKey(); int l = dHParameter.L?.IntValue ?? 0; DHParameters parameters = new DHParameters(dHParameter.P, dHParameter.G, null, l); return(new DHPrivateKeyParameters(derInteger.Value, parameters, algorithm)); } if (algorithm.Equals(OiwObjectIdentifiers.ElGamalAlgorithm)) { ElGamalParameter elGamalParameter = new ElGamalParameter(Asn1Sequence.GetInstance(privateKeyAlgorithm.Parameters.ToAsn1Object())); DerInteger derInteger2 = (DerInteger)keyInfo.ParsePrivateKey(); return(new ElGamalPrivateKeyParameters(derInteger2.Value, new ElGamalParameters(elGamalParameter.P, elGamalParameter.G))); } if (algorithm.Equals(X9ObjectIdentifiers.IdDsa)) { DerInteger derInteger3 = (DerInteger)keyInfo.ParsePrivateKey(); Asn1Encodable parameters2 = privateKeyAlgorithm.Parameters; DsaParameters parameters3 = null; if (parameters2 != null) { DsaParameter instance2 = DsaParameter.GetInstance(parameters2.ToAsn1Object()); parameters3 = new DsaParameters(instance2.P, instance2.Q, instance2.G); } return(new DsaPrivateKeyParameters(derInteger3.Value, parameters3)); } if (algorithm.Equals(X9ObjectIdentifiers.IdECPublicKey)) { X962Parameters x962Parameters = new X962Parameters(privateKeyAlgorithm.Parameters.ToAsn1Object()); X9ECParameters x9ECParameters = ((!x962Parameters.IsNamedCurve) ? new X9ECParameters((Asn1Sequence)x962Parameters.Parameters) : ECKeyPairGenerator.FindECCurveByOid((DerObjectIdentifier)x962Parameters.Parameters)); ECPrivateKeyStructure instance3 = ECPrivateKeyStructure.GetInstance(keyInfo.ParsePrivateKey()); BigInteger key = instance3.GetKey(); if (x962Parameters.IsNamedCurve) { return(new ECPrivateKeyParameters("EC", key, (DerObjectIdentifier)x962Parameters.Parameters)); } ECDomainParameters parameters4 = new ECDomainParameters(x9ECParameters.Curve, x9ECParameters.G, x9ECParameters.N, x9ECParameters.H, x9ECParameters.GetSeed()); return(new ECPrivateKeyParameters(key, parameters4)); } if (algorithm.Equals(CryptoProObjectIdentifiers.GostR3410x2001)) { Gost3410PublicKeyAlgParameters gost3410PublicKeyAlgParameters = new Gost3410PublicKeyAlgParameters(Asn1Sequence.GetInstance(privateKeyAlgorithm.Parameters.ToAsn1Object())); ECDomainParameters byOid = ECGost3410NamedCurves.GetByOid(gost3410PublicKeyAlgParameters.PublicKeyParamSet); if (byOid == null) { throw new ArgumentException("Unrecognized curve OID for GostR3410x2001 private key"); } Asn1Object asn1Object = keyInfo.ParsePrivateKey(); ECPrivateKeyStructure eCPrivateKeyStructure = ((!(asn1Object is DerInteger)) ? ECPrivateKeyStructure.GetInstance(asn1Object) : new ECPrivateKeyStructure(byOid.N.BitLength, ((DerInteger)asn1Object).Value)); return(new ECPrivateKeyParameters("ECGOST3410", eCPrivateKeyStructure.GetKey(), gost3410PublicKeyAlgParameters.PublicKeyParamSet)); } if (algorithm.Equals(CryptoProObjectIdentifiers.GostR3410x94)) { Gost3410PublicKeyAlgParameters gost3410PublicKeyAlgParameters2 = new Gost3410PublicKeyAlgParameters(Asn1Sequence.GetInstance(privateKeyAlgorithm.Parameters.ToAsn1Object())); DerOctetString derOctetString = (DerOctetString)keyInfo.ParsePrivateKey(); BigInteger x = new BigInteger(1, Arrays.Reverse(derOctetString.GetOctets())); return(new Gost3410PrivateKeyParameters(x, gost3410PublicKeyAlgParameters2.PublicKeyParamSet)); } throw new SecurityUtilityException("algorithm identifier in key not recognised"); }
public static List <CertSimples> ListaCertificado(X509Certificate2Collection Certificados) { List <CertSimples> oLista = new List <CertSimples>(); for (int i = 0; i < Certificados.Count; i++) { X509Certificate2 oCertificado = Certificados[i]; CertSimples oCert = new CertSimples(); oCert.SerialNumber = oCertificado.SerialNumber; oCert.Subject = oCertificado.Subject; try { string[] DadosSubject = oCertificado.Subject.Split(','); if (DadosSubject[0].IndexOf(":") > -1) { oCert.Nome = DadosSubject[0].Substring(3, DadosSubject[0].IndexOf(":") - 3); } else { oCert.Nome = DadosSubject[0].Substring(3); } } catch (Exception ex) { oCert.Nome = oCert.Subject; } foreach (var obj in oCertificado.Extensions) { if (obj.Oid.Value == "2.5.29.17") //otherName { byte[] Dados = obj.RawData; Stream sm = new MemoryStream(Dados); // StreamReader oSr = new StreamReader(sm); //string teste = System.Text.Encoding.ASCII.GetString(Dados); DerSequence otherName = (DerSequence)Asn1Object.FromStream(sm); var objCollection = otherName.GetEnumerator(); while (objCollection.MoveNext()) { Org.BouncyCastle.Asn1.DerTaggedObject iSub = (Org.BouncyCastle.Asn1.DerTaggedObject)objCollection.Current; Asn1Object derObject = iSub.GetObject(); if (derObject.GetType().Name.Contains("DerSequence")) { var objSubCollection = ((DerSequence)derObject).GetEnumerator(); byte count = 0; string strOID = ""; DerOctetString strOctet;// = (DerOctetString)derObject; string strTexto = ""; while (objSubCollection.MoveNext()) { var Conteudo = objSubCollection.Current; if (count == 0) { strOID = Conteudo.ToString(); } else { Org.BouncyCastle.Asn1.DerTaggedObject subCampos = (Org.BouncyCastle.Asn1.DerTaggedObject)Conteudo; Asn1Object derSub = subCampos.GetObject(); try { if (derSub.GetType().Name.Contains("DerOctetString")) { strOctet = (DerOctetString)derSub; byte[] Texto = strOctet.GetOctets(); strTexto = System.Text.Encoding.ASCII.GetString(Texto); } else { DerPrintableString strPtrString = (DerPrintableString)derSub; strTexto = strPtrString.GetString(); } } catch (Exception ex) { strTexto = derSub.ToString(); } } count++; } if (strOID == "2.16.76.1.3.1") //PESSOA FÍSICA { //i· OID = 2.16.76.1.3.1 e conteúdo = nas primeiras 8(oito) posições, a data de nascimento do titular, no formato ddmmaaaa; nas 11(onze) posições subseqüentes, o Cadastro de Pessoa Física(CPF) do titular; nas 11(onze) posições subseqüentes, o Número de Identificação Social – NIS(PIS, PASEP ou CI); nas 15(quinze) posições subseqüentes, o número do Registro Geral(RG) do titular; nas 10(dez) posições subseqüentes, as siglas do órgão expedidor do RG e respectiva unidade da federação; try { oCert.DataNascimento = strTexto.Substring(0, 8); oCert.CPF = strTexto.Substring(8, 11); oCert.NIS = strTexto.Substring(19, 11); oCert.RG = strTexto.Substring(30, 15); oCert.OrgaoExpedidor = strTexto.Substring(45); oCert.Tipo = "F"; } catch (Exception ex) { throw new Exception("Erro na leitura da OID=2.16.76.1.3.1:" + ex.Message, ex); } } else if (strOID == "2.16.76.1.3.6") //PESSOA FÍSICA { //ii· OID = 2.16.76.1.3.6 e conteúdo = nas 12 (doze) posições o número do Cadastro Específico do INSS (CEI) da pessoa física titular do certificado; } else if (strOID == "2.16.76.1.3.6") //PESSOA FÍSICA { try { //iii· OID = 2.16.76.1.3.5 e conteúdo nas primeiras 12(doze) posições, o número de inscrição do Título de Eleitor; nas 3(três) posições subseqüentes, a Zona Eleitoral; nas 4(quatro) posições seguintes, a Seção; nas 22(vinte e duas) posições subseqüentes, o município e a UF do Título de Eleitor. oCert.TituloEleitor = strTexto.Substring(0, 12); oCert.ZonaEleitoral = strTexto.Substring(12, 3); oCert.SecaoEleitoral = strTexto.Substring(15, 4); oCert.MunicipioEleitoral = strTexto.Substring(19, 22); } catch (Exception ex) { throw new Exception("Erro na leitura da OID=2.16.76.1.3.6:" + ex.Message, ex); } } else if (strOID == "2.16.76.1.4.2.1.1") { try { oCert.OAB = strTexto; } catch (Exception ex) { throw new Exception("Erro na leitura da OID=2.16.76.1.4.2.1.1:" + ex.Message, ex); } } else if (strOID == "2.16.76.1.3.4") //PESSOA JURÍDICA { try { oCert.Tipo = "J"; //i· OID = 2.16.76.1.3.4 e conteúdo = nas primeiras 8(oito) posições, a data de nascimento do responsável pelo certificado, no formato ddmmaaaa; nas 11(onze) posições subseqüentes, o Cadastro de Pessoa Física(CPF) do responsável; nas 11(onze) posições subseqüentes, o Número de Identificação Social – NIS(PIS, PASEP ou CI); nas 15(quinze) posições subseqüentes, o número do Registro Geral(RG) do responsável; nas 10(dez) posições subseqüentes, as siglas do órgão expedidor do RG e respectiva Unidade da Federação; oCert.DataNascimento = strTexto.Substring(0, 8); oCert.CPF = strTexto.Substring(8, 11); try { oCert.NIS = strTexto.Substring(19, 11); oCert.RG = strTexto.Substring(30, 15); oCert.OrgaoExpedidor = strTexto.Substring(45, 10); } catch (Exception ex) { } } catch (Exception ex) { throw new Exception("Erro na leitura da OID=2.16.76.1.3.4:" + strTexto + "." + ex.Message, ex); } } else if (strOID == "2.16.76.1.3.2") //PESSOA JURÍDICA { //ii· OID = 2.16.76.1.3.2 e conteúdo = nome do responsável pelo certificado; try { oCert.NomeResponsavel = strTexto; } catch (Exception ex) { throw new Exception("Erro na leitura da OID=2.16.76.1.3.2:" + ex.Message, ex); } } else if (strOID == "2.16.76.1.3.3") //PESSOA JURÍDICA { //iii· OID = 2.16.76.1.3.3 e conteúdo = nas 14(quatorze) posições o número do Cadastro Nacional de Pessoa Jurídica(CNPJ) da pessoa jurídica titular do certificado; try { oCert.CNPJ = strTexto; } catch (Exception ex) { throw new Exception("Erro na leitura da OID=2.16.76.1.3.3:" + ex.Message, ex); } } else if (strOID == "2.16.76.1.3.7") //PESSOA JURÍDICA { //iv. OID = 2.16.76.1.3.7 e conteúdo = nas 12 (doze) posições o número do Cadastro Específico do INSS (CEI) da pessoa jurídica titular do certificado. } count = 0; } else { //i. rfc822Name contendo o endereço e-mail do titular do certificado. if (derObject.GetType().Name == "DerOctetString") { DerOctetString strOctet = (DerOctetString)derObject; byte[] Texto = strOctet.GetOctets(); string strTexto = System.Text.Encoding.ASCII.GetString(Texto); oCert.Email = strTexto; } else { string texto = derObject.GetType().Name; } } } sm.Close(); } } oCert.Certificado = oCertificado; oLista.Add(oCert); } return(oLista); }
public static AsymmetricKeyParameter CreateKey( PrivateKeyInfo keyInfo) { AlgorithmIdentifier algID = keyInfo.AlgorithmID; DerObjectIdentifier algOid = algID.ObjectID; // TODO See RSAUtil.isRsaOid in Java build if (algOid.Equals(PkcsObjectIdentifiers.RsaEncryption) || algOid.Equals(X509ObjectIdentifiers.IdEARsa) || algOid.Equals(PkcsObjectIdentifiers.IdRsassaPss) || algOid.Equals(PkcsObjectIdentifiers.IdRsaesOaep)) { RsaPrivateKeyStructure keyStructure = new RsaPrivateKeyStructure( Asn1Sequence.GetInstance(keyInfo.PrivateKey)); return(new RsaPrivateCrtKeyParameters( keyStructure.Modulus, keyStructure.PublicExponent, keyStructure.PrivateExponent, keyStructure.Prime1, keyStructure.Prime2, keyStructure.Exponent1, keyStructure.Exponent2, keyStructure.Coefficient)); } else if (algOid.Equals(PkcsObjectIdentifiers.DhKeyAgreement)) { DHParameter para = new DHParameter( Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object())); DerInteger derX = (DerInteger)keyInfo.PrivateKey; BigInteger lVal = para.L; int l = lVal == null ? 0 : lVal.IntValue; DHParameters dhParams = new DHParameters(para.P, para.G, null, l); return(new DHPrivateKeyParameters(derX.Value, dhParams)); } else if (algOid.Equals(OiwObjectIdentifiers.ElGamalAlgorithm)) { ElGamalParameter para = new ElGamalParameter( Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object())); DerInteger derX = (DerInteger)keyInfo.PrivateKey; return(new ElGamalPrivateKeyParameters( derX.Value, new ElGamalParameters(para.P, para.G))); } else if (algOid.Equals(X9ObjectIdentifiers.IdDsa)) { DerInteger derX = (DerInteger)keyInfo.PrivateKey; Asn1Encodable ae = algID.Parameters; DsaParameters parameters = null; if (ae != null) { DsaParameter para = DsaParameter.GetInstance(ae.ToAsn1Object()); parameters = new DsaParameters(para.P, para.Q, para.G); } return(new DsaPrivateKeyParameters(derX.Value, parameters)); } else if (algOid.Equals(X9ObjectIdentifiers.IdECPublicKey)) { X962Parameters para = new X962Parameters(algID.Parameters.ToAsn1Object()); X9ECParameters ecP; if (para.IsNamedCurve) { // TODO ECGost3410NamedCurves support (returns ECDomainParameters though) DerObjectIdentifier oid = (DerObjectIdentifier)para.Parameters; ecP = X962NamedCurves.GetByOid(oid); if (ecP == null) { ecP = SecNamedCurves.GetByOid(oid); if (ecP == null) { ecP = NistNamedCurves.GetByOid(oid); if (ecP == null) { ecP = TeleTrusTNamedCurves.GetByOid(oid); } } } } else { ecP = new X9ECParameters((Asn1Sequence)para.Parameters); } ECDomainParameters dParams = new ECDomainParameters( ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed()); ECPrivateKeyStructure ec = new ECPrivateKeyStructure( Asn1Sequence.GetInstance(keyInfo.PrivateKey)); return(new ECPrivateKeyParameters(ec.GetKey(), dParams)); } else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x2001)) { Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters( Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object())); ECPrivateKeyStructure ec = new ECPrivateKeyStructure( Asn1Sequence.GetInstance(keyInfo.PrivateKey)); ECDomainParameters ecP = ECGost3410NamedCurves.GetByOid(gostParams.PublicKeyParamSet); if (ecP == null) { return(null); } return(new ECPrivateKeyParameters(ec.GetKey(), gostParams.PublicKeyParamSet)); } else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x94)) { Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters( Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object())); DerOctetString derX = (DerOctetString)keyInfo.PrivateKey; byte[] keyEnc = derX.GetOctets(); byte[] keyBytes = new byte[keyEnc.Length]; for (int i = 0; i != keyEnc.Length; i++) { keyBytes[i] = keyEnc[keyEnc.Length - 1 - i]; // was little endian } BigInteger x = new BigInteger(1, keyBytes); return(new Gost3410PrivateKeyParameters(x, gostParams.PublicKeyParamSet)); } else { throw new SecurityUtilityException("algorithm identifier in key not recognised"); } }
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)); }
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)); }
public virtual byte[] GetArchiveTimestampData(int index, Document originalDocument) { using (var toTimestamp = new MemoryStream()) { BcCms.ContentInfo contentInfo = _cmsSignedData.ContentInfo; BcCms.SignedData signedData = BcCms.SignedData.GetInstance(contentInfo.Content); // 5.4.1 if (signedData.EncapContentInfo == null || signedData.EncapContentInfo. Content == null) { if (originalDocument != null) { toTimestamp.Write(Streams.ReadAll(originalDocument.OpenStream())); } else { throw new Exception("Signature is detached and no original data provided."); } } else { BcCms.ContentInfo content = signedData.EncapContentInfo; DerOctetString octet = (DerOctetString)content.Content; BcCms.ContentInfo info2 = new BcCms.ContentInfo(new DerObjectIdentifier("1.2.840.113549.1.7.1"), new BerOctetString(octet.GetOctets())); toTimestamp.Write(info2.GetEncoded()); } if (signedData.Certificates != null) { DerOutputStream output = new DerOutputStream(toTimestamp); output.WriteObject(signedData.Certificates); output.Close(); } if (signedData.CRLs != null) { toTimestamp.Write(signedData.CRLs.GetEncoded()); } if (signerInformation.UnsignedAttributes != null) { Asn1EncodableVector original = signerInformation.UnsignedAttributes.ToAsn1EncodableVector(); IList <BcCms.Attribute> timeStampToRemove = GetTimeStampToRemove(index); Asn1EncodableVector filtered = new Asn1EncodableVector(); for (int i = 0; i < original.Count; i++) { Asn1Encodable enc = original[i]; if (!timeStampToRemove.Contains(enc)) { filtered.Add(original[i]); } } SignerInformation filteredInfo = SignerInformation.ReplaceUnsignedAttributes(signerInformation, new BcCms.AttributeTable(filtered)); toTimestamp.Write(filteredInfo.ToSignerInfo().GetEncoded()); } return(toTimestamp.ToArray()); } }
public static AsymmetricKeyParameter CreateKey(PrivateKeyInfo keyInfo) { AlgorithmIdentifier privateKeyAlgorithm = keyInfo.PrivateKeyAlgorithm; DerObjectIdentifier objectID = privateKeyAlgorithm.ObjectID; if (objectID.Equals(PkcsObjectIdentifiers.RsaEncryption) || objectID.Equals(X509ObjectIdentifiers.IdEARsa) || objectID.Equals(PkcsObjectIdentifiers.IdRsassaPss) || objectID.Equals(PkcsObjectIdentifiers.IdRsaesOaep)) { RsaPrivateKeyStructure instance = RsaPrivateKeyStructure.GetInstance(keyInfo.ParsePrivateKey()); return(new RsaPrivateCrtKeyParameters(instance.Modulus, instance.PublicExponent, instance.PrivateExponent, instance.Prime1, instance.Prime2, instance.Exponent1, instance.Exponent2, instance.Coefficient)); } if (objectID.Equals(PkcsObjectIdentifiers.DhKeyAgreement)) { DHParameter dHParameter = new DHParameter(Asn1Sequence.GetInstance(privateKeyAlgorithm.Parameters.ToAsn1Object())); DerInteger derInteger = (DerInteger)keyInfo.ParsePrivateKey(); BigInteger l = dHParameter.L; int l2 = (l == null) ? 0 : l.IntValue; DHParameters parameters = new DHParameters(dHParameter.P, dHParameter.G, null, l2); return(new DHPrivateKeyParameters(derInteger.Value, parameters, objectID)); } if (objectID.Equals(OiwObjectIdentifiers.ElGamalAlgorithm)) { ElGamalParameter elGamalParameter = new ElGamalParameter(Asn1Sequence.GetInstance(privateKeyAlgorithm.Parameters.ToAsn1Object())); DerInteger derInteger2 = (DerInteger)keyInfo.ParsePrivateKey(); return(new ElGamalPrivateKeyParameters(derInteger2.Value, new ElGamalParameters(elGamalParameter.P, elGamalParameter.G))); } if (objectID.Equals(X9ObjectIdentifiers.IdDsa)) { DerInteger derInteger3 = (DerInteger)keyInfo.ParsePrivateKey(); Asn1Encodable parameters2 = privateKeyAlgorithm.Parameters; DsaParameters parameters3 = null; if (parameters2 != null) { DsaParameter instance2 = DsaParameter.GetInstance(parameters2.ToAsn1Object()); parameters3 = new DsaParameters(instance2.P, instance2.Q, instance2.G); } return(new DsaPrivateKeyParameters(derInteger3.Value, parameters3)); } if (objectID.Equals(X9ObjectIdentifiers.IdECPublicKey)) { X962Parameters x962Parameters = new X962Parameters(privateKeyAlgorithm.Parameters.ToAsn1Object()); X9ECParameters x9ECParameters; if (x962Parameters.IsNamedCurve) { x9ECParameters = ECKeyPairGenerator.FindECCurveByOid((DerObjectIdentifier)x962Parameters.Parameters); } else { x9ECParameters = new X9ECParameters((Asn1Sequence)x962Parameters.Parameters); } ECPrivateKeyStructure eCPrivateKeyStructure = new ECPrivateKeyStructure(Asn1Sequence.GetInstance(keyInfo.ParsePrivateKey())); BigInteger key = eCPrivateKeyStructure.GetKey(); if (x962Parameters.IsNamedCurve) { return(new ECPrivateKeyParameters("EC", key, (DerObjectIdentifier)x962Parameters.Parameters)); } ECDomainParameters parameters4 = new ECDomainParameters(x9ECParameters.Curve, x9ECParameters.G, x9ECParameters.N, x9ECParameters.H, x9ECParameters.GetSeed()); return(new ECPrivateKeyParameters(key, parameters4)); } else if (objectID.Equals(CryptoProObjectIdentifiers.GostR3410x2001)) { Gost3410PublicKeyAlgParameters gost3410PublicKeyAlgParameters = new Gost3410PublicKeyAlgParameters(Asn1Sequence.GetInstance(privateKeyAlgorithm.Parameters.ToAsn1Object())); Asn1Object asn1Object = keyInfo.ParsePrivateKey(); ECPrivateKeyStructure eCPrivateKeyStructure2; if (asn1Object is DerInteger) { eCPrivateKeyStructure2 = new ECPrivateKeyStructure(((DerInteger)asn1Object).Value); } else { eCPrivateKeyStructure2 = ECPrivateKeyStructure.GetInstance(asn1Object); } if (ECGost3410NamedCurves.GetByOid(gost3410PublicKeyAlgParameters.PublicKeyParamSet) == null) { throw new ArgumentException("Unrecognized curve OID for GostR3410x2001 private key"); } return(new ECPrivateKeyParameters("ECGOST3410", eCPrivateKeyStructure2.GetKey(), gost3410PublicKeyAlgParameters.PublicKeyParamSet)); } else { if (objectID.Equals(CryptoProObjectIdentifiers.GostR3410x94)) { Gost3410PublicKeyAlgParameters gost3410PublicKeyAlgParameters2 = new Gost3410PublicKeyAlgParameters(Asn1Sequence.GetInstance(privateKeyAlgorithm.Parameters.ToAsn1Object())); DerOctetString derOctetString = (DerOctetString)keyInfo.ParsePrivateKey(); BigInteger x = new BigInteger(1, Arrays.Reverse(derOctetString.GetOctets())); return(new Gost3410PrivateKeyParameters(x, gost3410PublicKeyAlgParameters2.PublicKeyParamSet)); } throw new SecurityUtilityException("algorithm identifier in key not recognised"); } }
public static AsymmetricKeyParameter CreateKey( PrivateKeyInfo keyInfo) { AlgorithmIdentifier algID = keyInfo.PrivateKeyAlgorithm; DerObjectIdentifier algOid = algID.Algorithm; // TODO See RSAUtil.isRsaOid in Java build if (algOid.Equals(PkcsObjectIdentifiers.RsaEncryption) || algOid.Equals(X509ObjectIdentifiers.IdEARsa) || algOid.Equals(PkcsObjectIdentifiers.IdRsassaPss) || algOid.Equals(PkcsObjectIdentifiers.IdRsaesOaep)) { RsaPrivateKeyStructure keyStructure = RsaPrivateKeyStructure.GetInstance(keyInfo.ParsePrivateKey()); return(new RsaPrivateCrtKeyParameters( keyStructure.Modulus, keyStructure.PublicExponent, keyStructure.PrivateExponent, keyStructure.Prime1, keyStructure.Prime2, keyStructure.Exponent1, keyStructure.Exponent2, keyStructure.Coefficient)); } // TODO? // else if (algOid.Equals(X9ObjectIdentifiers.DHPublicNumber)) else if (algOid.Equals(PkcsObjectIdentifiers.DhKeyAgreement)) { DHParameter para = new DHParameter( Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object())); DerInteger derX = (DerInteger)keyInfo.ParsePrivateKey(); BigInteger lVal = para.L; int l = lVal == null ? 0 : lVal.IntValue; DHParameters dhParams = new DHParameters(para.P, para.G, null, l); return(new DHPrivateKeyParameters(derX.Value, dhParams, algOid)); } else if (algOid.Equals(OiwObjectIdentifiers.ElGamalAlgorithm)) { ElGamalParameter para = new ElGamalParameter( Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object())); DerInteger derX = (DerInteger)keyInfo.ParsePrivateKey(); return(new ElGamalPrivateKeyParameters( derX.Value, new ElGamalParameters(para.P, para.G))); } else if (algOid.Equals(X9ObjectIdentifiers.IdDsa)) { DerInteger derX = (DerInteger)keyInfo.ParsePrivateKey(); Asn1Encodable ae = algID.Parameters; DsaParameters parameters = null; if (ae != null) { DsaParameter para = DsaParameter.GetInstance(ae.ToAsn1Object()); parameters = new DsaParameters(para.P, para.Q, para.G); } return(new DsaPrivateKeyParameters(derX.Value, parameters)); } else if (algOid.Equals(X9ObjectIdentifiers.IdECPublicKey)) { X962Parameters para = new X962Parameters(algID.Parameters.ToAsn1Object()); X9ECParameters x9; if (para.IsNamedCurve) { x9 = ECKeyPairGenerator.FindECCurveByOid((DerObjectIdentifier)para.Parameters); } else { x9 = new X9ECParameters((Asn1Sequence)para.Parameters); } ECPrivateKeyStructure ec = ECPrivateKeyStructure.GetInstance(keyInfo.ParsePrivateKey()); BigInteger d = ec.GetKey(); if (para.IsNamedCurve) { return(new ECPrivateKeyParameters("EC", d, (DerObjectIdentifier)para.Parameters)); } ECDomainParameters dParams = new ECDomainParameters(x9.Curve, x9.G, x9.N, x9.H, x9.GetSeed()); return(new ECPrivateKeyParameters(d, dParams)); } else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x2001)) { Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters( Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object())); ECDomainParameters ecP = ECGost3410NamedCurves.GetByOid(gostParams.PublicKeyParamSet); if (ecP == null) { throw new ArgumentException("Unrecognized curve OID for GostR3410x2001 private key"); } Asn1Object privKey = keyInfo.ParsePrivateKey(); ECPrivateKeyStructure ec; if (privKey is DerInteger) { // TODO Do we need to pass any parameters here? ec = new ECPrivateKeyStructure(ecP.N.BitLength, ((DerInteger)privKey).Value); } else { ec = ECPrivateKeyStructure.GetInstance(privKey); } return(new ECPrivateKeyParameters("ECGOST3410", ec.GetKey(), gostParams.PublicKeyParamSet)); } else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x94)) { Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters( Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object())); DerOctetString derX = (DerOctetString)keyInfo.ParsePrivateKey(); BigInteger x = new BigInteger(1, Arrays.Reverse(derX.GetOctets())); return(new Gost3410PrivateKeyParameters(x, gostParams.PublicKeyParamSet)); } else { throw new SecurityUtilityException("algorithm identifier in key not recognised"); } }