static public ASN1 AlgorithmIdentifier (string oid) { ASN1 ai = new ASN1 (0x30); ai.Add (ASN1Convert.FromOid (oid)); ai.Add (new ASN1 (0x05)); // NULL return ai; }
// Class(60) { // OID(spnego), // Class(A0) { // Class(30) { // Class(A0) { // Class(30) { OID,OID,OID} }, // Class(A2) { OctetStream } } } } public byte [] ProcessSpnegoInitialContextTokenRequest () { Type1Message type1 = new Type1Message (NtlmVersion.Version3); type1.Flags = unchecked ((NtlmFlags) 0xE21882B7); type1.Domain = "WORKGROUP"; // FIXME: remove it ASN1 asn = new ASN1 (0x60); ASN1 asn2 = new ASN1 (0xA0); ASN1 asn21 = new ASN1 (0x30); ASN1 asn211 = new ASN1 (0xA0); ASN1 asn2111 = new ASN1 (0x30); asn211.Add (asn2111); asn2111.Add (ASN1Convert.FromOid (Constants.OidNtlmSsp)); asn2111.Add (ASN1Convert.FromOid (Constants.OidKerberos5)); asn2111.Add (ASN1Convert.FromOid (Constants.OidMIT)); ASN1 asn212 = new ASN1 (0xA2); ASN1 asn2121 = new ASN1 (0x4); asn2121.Value = type1.GetBytes (); asn212.Add (asn2121); asn21.Add (asn211); asn21.Add (asn212); asn2.Add (asn21); asn.Add (ASN1Convert.FromOid (Constants.OidSpnego)); asn.Add (asn2); return asn.GetBytes (); }
static public ASN1 Attribute (string oid, ASN1 value) { ASN1 attr = new ASN1 (0x30); attr.Add (ASN1Convert.FromOid (oid)); ASN1 aset = attr.Add (new ASN1 (0x31)); aset.Add (value); return attr; }
protected override void Encode () { if (extnValue == null) { extnValue = new ASN1 (0x30); foreach (string oid in keyPurpose) { extnValue.Add (ASN1Convert.FromOid (oid)); } } }
internal ASN1 GetASN1() { if (this.key == null || this.hashAlgorithm == null) { return(null); } byte[] data = new byte[] { this.version }; ASN1 asn = new ASN1(48); asn.Add(new ASN1(2, data)); asn.Add(PKCS7.IssuerAndSerialNumber(this.x509)); string oid = CryptoConfig.MapNameToOID(this.hashAlgorithm); asn.Add(PKCS7.AlgorithmIdentifier(oid)); ASN1 asn2 = null; if (this.authenticatedAttributes.Count > 0) { asn2 = asn.Add(new ASN1(160)); foreach (object obj in this.authenticatedAttributes) { ASN1 asn3 = (ASN1)obj; asn2.Add(asn3); } } if (this.key is RSA) { asn.Add(PKCS7.AlgorithmIdentifier("1.2.840.113549.1.1.1")); if (asn2 != null) { RSAPKCS1SignatureFormatter rsapkcs1SignatureFormatter = new RSAPKCS1SignatureFormatter(this.key); rsapkcs1SignatureFormatter.SetHashAlgorithm(this.hashAlgorithm); byte[] bytes = asn2.GetBytes(); bytes[0] = 49; HashAlgorithm hashAlgorithm = HashAlgorithm.Create(this.hashAlgorithm); byte[] rgbHash = hashAlgorithm.ComputeHash(bytes); this.signature = rsapkcs1SignatureFormatter.CreateSignature(rgbHash); } asn.Add(new ASN1(4, this.signature)); if (this.unauthenticatedAttributes.Count > 0) { ASN1 asn4 = asn.Add(new ASN1(161)); foreach (object obj2 in this.unauthenticatedAttributes) { ASN1 asn5 = (ASN1)obj2; asn4.Add(asn5); } } return(asn); } if (this.key is DSA) { throw new NotImplementedException("not yet"); } throw new CryptographicException("Unknown assymetric algorithm"); }
protected override void Encode () { ASN1 seq = new ASN1 (0x30); foreach (string oid in keyPurpose) { seq.Add (ASN1Convert.FromOid (oid)); } extnValue = new ASN1 (0x04); extnValue.Add (seq); }
static public ASN1 Attribute(string oid, ASN1 value) { ASN1 attr = new ASN1(0x30); attr.Add(ASN1Convert.FromOid(oid)); ASN1 aset = attr.Add(new ASN1(0x31)); aset.Add(value); return(attr); }
public static ASN1 Attribute(string oid, ASN1 value) { ASN1 asn = new ASN1(48); asn.Add(ASN1Convert.FromOid(oid)); ASN1 asn2 = asn.Add(new ASN1(49)); asn2.Add(value); return(asn); }
public static ASN1 Attribute(string oid, ASN1 value) { ASN1 aSN = new ASN1(48); aSN.Add(ASN1Convert.FromOid(oid)); ASN1 aSN2 = aSN.Add(new ASN1(49)); aSN2.Add(value); return(aSN); }
protected override void Encode () { if (ski == null) { throw new InvalidOperationException ("Invalid SubjectKeyIdentifier extension"); } var seq = new ASN1 (0x04, ski); extnValue = new ASN1 (0x04); extnValue.Add (seq); }
/// /// SEQUENCE (a) /// +- INTEGER (V) // Version - 0 (v1998) /// +- SEQUENCE (b) /// | +- OID (oid) // 1.2.840.113549.1.1.1 /// | +- Nil (c) /// +- OCTETSTRING(PRVKY) (os) // Private Key Parameter /// /// However, OCTETSTRING(PRVKY) wraps /// SEQUENCE( /// INTEGER(0) // Version - 0 (v1998) /// INTEGER(N) /// INTEGER(E) /// INTEGER(D) /// INTEGER(P) /// INTEGER(Q) /// INTEGER(DP) /// INTEGER(DQ) /// INTEGER(InvQ) /// ) public static byte[] RSAKeyToASN1(RSAParameters PrivateKey) { ASN1 v = ASN1Convert.FromUnsignedBigInteger(new byte[] {0}); ASN1 b = PKCS7.AlgorithmIdentifier ("1.2.840.113549.1.1.1"); ASN1 os = new ASN1(0x30); os.Add(ASN1Convert.FromUnsignedBigInteger(new byte[] {0})); os.Add(ASN1Convert.FromUnsignedBigInteger(PrivateKey.Modulus)); os.Add(ASN1Convert.FromUnsignedBigInteger(PrivateKey.Exponent)); os.Add(ASN1Convert.FromUnsignedBigInteger(PrivateKey.D)); os.Add(ASN1Convert.FromUnsignedBigInteger(PrivateKey.P)); os.Add(ASN1Convert.FromUnsignedBigInteger(PrivateKey.Q)); os.Add(ASN1Convert.FromUnsignedBigInteger(PrivateKey.DP)); os.Add(ASN1Convert.FromUnsignedBigInteger(PrivateKey.DQ)); os.Add(ASN1Convert.FromUnsignedBigInteger(PrivateKey.InverseQ)); ASN1 pem = new ASN1(0x30); pem.Add(v); pem.Add(b); // Make this into an OCTET string pem.Add(new ASN1(0x04, os.GetBytes())); return pem.GetBytes(); }
public static ASN1 ToAsn1(RSA rsa) { EnsureNotNull(rsa, "rsa"); ASN1 asn = new ASN1(0x30); ASN1 asnOid = new ASN1(0x30); // {iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs-1(1) rsaEncryption(1)} // http://www.oid-info.com/get/1.2.840.113549.1.1.1 asnOid.Add(ASN1Convert.FromOid("1.2.840.113549.1.1.1")); asnOid.Add(new ASN1(0x05)); asn.Add(asnOid); ASN1 asnBits = new ASN1(0x03, new byte[1]); byte[] intermediate = ToAsn1Key(rsa).GetBytes(); byte[] key = new byte[intermediate.Length + 1]; intermediate.CopyTo(key, 1); asnBits.Value = key; asn.Add(asnBits); return asn; }
public X509Extension (ASN1 asn1) { if ((asn1.Tag != 0x30) || (asn1.Count < 2)) throw new ArgumentException (Locale.GetText ("Invalid X.509 extension.")); if (asn1[0].Tag != 0x06) throw new ArgumentException (Locale.GetText ("Invalid X.509 extension.")); extnOid = ASN1Convert.ToOid (asn1[0]); extnCritical = ((asn1[1].Tag == 0x01) && (asn1[1].Value[0] == 0xFF)); // last element is an octet string which may need to be decoded extnValue = asn1 [asn1.Count - 1]; if ((extnValue.Tag == 0x04) && (extnValue.Length > 0) && (extnValue.Count == 0)) { try { ASN1 encapsulated = new ASN1 (extnValue.Value); extnValue.Value = null; extnValue.Add (encapsulated); } catch { // data isn't ASN.1 } } Decode (); }
public bool VerifySignature(AsymmetricAlgorithm aa) { if (aa == null) { return(false); } RSAPKCS1SignatureDeformatter r = new RSAPKCS1SignatureDeformatter(aa); r.SetHashAlgorithm(hashAlgorithm); HashAlgorithm ha = HashAlgorithm.Create(hashAlgorithm); byte[] signature = signerInfo.Signature; byte[] hash = null; if (mda) { ASN1 asn = new ASN1(0x31); foreach (ASN1 attr in signerInfo.AuthenticatedAttributes) { asn.Add(attr); } hash = ha.ComputeHash(asn.GetBytes()); } else { hash = ha.ComputeHash(contentInfo.Content[0].Value); } if (hash != null && signature != null) { return(r.VerifySignature(hash, signature)); } return(false); }
private ASN1 KeyBagSafeBag (AsymmetricAlgorithm aa, IDictionary attributes) { PKCS8.PrivateKeyInfo pki = new PKCS8.PrivateKeyInfo (); if (aa is RSA) { pki.Algorithm = "1.2.840.113549.1.1.1"; pki.PrivateKey = PKCS8.PrivateKeyInfo.Encode ((RSA)aa); } else if (aa is DSA) { pki.Algorithm = null; pki.PrivateKey = PKCS8.PrivateKeyInfo.Encode ((DSA)aa); } else throw new CryptographicException ("Unknown asymmetric algorithm {0}", aa.ToString ()); ASN1 safeBag = new ASN1 (0x30); safeBag.Add (ASN1Convert.FromOid (keyBag)); ASN1 bagValue = new ASN1 (0xA0); bagValue.Add (new ASN1 (pki.GetBytes ())); safeBag.Add (bagValue); if (attributes != null) { ASN1 bagAttributes = new ASN1 (0x31); IDictionaryEnumerator de = attributes.GetEnumerator (); while (de.MoveNext ()) { string oid = (string)de.Key; switch (oid) { case PKCS9.friendlyName: ArrayList names = (ArrayList)de.Value; if (names.Count > 0) { ASN1 pkcs12Attribute = new ASN1 (0x30); pkcs12Attribute.Add (ASN1Convert.FromOid (PKCS9.friendlyName)); ASN1 attrValues = new ASN1 (0x31); foreach (byte[] name in names) { ASN1 attrValue = new ASN1 (0x1e); attrValue.Value = name; attrValues.Add (attrValue); } pkcs12Attribute.Add (attrValues); bagAttributes.Add (pkcs12Attribute); } break; case PKCS9.localKeyId: ArrayList keys = (ArrayList)de.Value; if (keys.Count > 0) { ASN1 pkcs12Attribute = new ASN1 (0x30); pkcs12Attribute.Add (ASN1Convert.FromOid (PKCS9.localKeyId)); ASN1 attrValues = new ASN1 (0x31); foreach (byte[] key in keys) { ASN1 attrValue = new ASN1 (0x04); attrValue.Value = key; attrValues.Add (attrValue); } pkcs12Attribute.Add (attrValues); bagAttributes.Add (pkcs12Attribute); } break; default: break; } } if (bagAttributes.Count > 0) { safeBag.Add (bagAttributes); } } return safeBag; }
internal ASN1 GetASN1() { ASN1 aSN = new ASN1(48); byte[] data = new byte[1] { version }; aSN.Add(new ASN1(2, data)); ASN1 aSN2 = aSN.Add(new ASN1(49)); if (this.hashAlgorithm != null) { string oid = CryptoConfig.MapNameToOID(this.hashAlgorithm); aSN2.Add(AlgorithmIdentifier(oid)); } ASN1 aSN3 = contentInfo.ASN1; aSN.Add(aSN3); if (!signed && this.hashAlgorithm != null) { if (mda) { ASN1 value = Attribute("1.2.840.113549.1.9.3", aSN3[0]); signerInfo.AuthenticatedAttributes.Add(value); HashAlgorithm hashAlgorithm = HashAlgorithm.Create(this.hashAlgorithm); byte[] data2 = hashAlgorithm.ComputeHash(aSN3[1][0].Value); ASN1 aSN4 = new ASN1(48); ASN1 value2 = Attribute("1.2.840.113549.1.9.4", aSN4.Add(new ASN1(4, data2))); signerInfo.AuthenticatedAttributes.Add(value2); } else { RSAPKCS1SignatureFormatter rSAPKCS1SignatureFormatter = new RSAPKCS1SignatureFormatter(signerInfo.Key); rSAPKCS1SignatureFormatter.SetHashAlgorithm(this.hashAlgorithm); HashAlgorithm hashAlgorithm2 = HashAlgorithm.Create(this.hashAlgorithm); byte[] rgbHash = hashAlgorithm2.ComputeHash(aSN3[1][0].Value); signerInfo.Signature = rSAPKCS1SignatureFormatter.CreateSignature(rgbHash); } signed = true; } if (certs.Count > 0) { ASN1 aSN5 = aSN.Add(new ASN1(160)); foreach (X509Certificate cert in certs) { aSN5.Add(new ASN1(cert.RawData)); } } if (crls.Count > 0) { ASN1 aSN6 = aSN.Add(new ASN1(161)); foreach (byte[] crl in crls) { aSN6.Add(new ASN1(crl)); } } ASN1 aSN7 = aSN.Add(new ASN1(49)); if (signerInfo.Key != null) { aSN7.Add(signerInfo.ASN1); } return(aSN); }
private byte[] Header (byte[] fileHash, string hashAlgorithm) { string hashOid = CryptoConfig.MapNameToOID (hashAlgorithm); ASN1 content = new ASN1 (0x30); ASN1 c1 = content.Add (new ASN1 (0x30)); c1.Add (ASN1Convert.FromOid (spcPelmageData)); c1.Add (new ASN1 (0x30, obsolete)); ASN1 c2 = content.Add (new ASN1 (0x30)); c2.Add (AlgorithmIdentifier (hashOid)); c2.Add (new ASN1 (0x04, fileHash)); pkcs7.HashName = hashAlgorithm; pkcs7.Certificates.AddRange (certs); pkcs7.ContentInfo.ContentType = spcIndirectDataContext; pkcs7.ContentInfo.Content.Add (content); pkcs7.SignerInfo.Certificate = certs [0]; pkcs7.SignerInfo.Key = rsa; ASN1 opus = null; if (url == null) opus = Attribute (spcSpOpusInfo, Opus (description, null)); else opus = Attribute (spcSpOpusInfo, Opus (description, url.ToString ())); pkcs7.SignerInfo.AuthenticatedAttributes.Add (opus); // When using the MS Root Agency (test) we can't include this attribute in the signature or it won't validate! // pkcs7.SignerInfo.AuthenticatedAttributes.Add (Attribute (spcStatementType, new ASN1 (0x30, ASN1Convert.FromOid (commercialCodeSigning).GetBytes ()))); pkcs7.GetASN1 (); // sign return pkcs7.SignerInfo.Signature; }
static public ASN1 AlgorithmIdentifier (string oid, ASN1 parameters) { ASN1 ai = new ASN1 (0x30); ai.Add (ASN1Convert.FromOid (oid)); ai.Add (parameters); return ai; }
internal ASN1 GetASN1() { if ((key == null) || (hashAlgorithm == null)) { return(null); } byte[] ver = { version }; ASN1 signerInfo = new ASN1(0x30); // version Version -> Version ::= INTEGER signerInfo.Add(new ASN1(0x02, ver)); // issuerAndSerialNumber IssuerAndSerialNumber, signerInfo.Add(PKCS7.IssuerAndSerialNumber(x509)); // digestAlgorithm DigestAlgorithmIdentifier, string hashOid = CryptoConfig.MapNameToOID(hashAlgorithm); signerInfo.Add(AlgorithmIdentifier(hashOid)); // authenticatedAttributes [0] IMPLICIT Attributes OPTIONAL, ASN1 aa = null; if (authenticatedAttributes.Count > 0) { aa = signerInfo.Add(new ASN1(0xA0)); authenticatedAttributes.Sort(new SortedSet()); foreach (ASN1 attr in authenticatedAttributes) { aa.Add(attr); } } // digestEncryptionAlgorithm DigestEncryptionAlgorithmIdentifier, if (key is RSA) { signerInfo.Add(AlgorithmIdentifier(PKCS7.Oid.rsaEncryption)); if (aa != null) { // Calculate the signature here; otherwise it must be set from SignedData RSAPKCS1SignatureFormatter r = new RSAPKCS1SignatureFormatter(key); r.SetHashAlgorithm(hashAlgorithm); byte[] tbs = aa.GetBytes(); tbs [0] = 0x31; // not 0xA0 for signature HashAlgorithm ha = HashAlgorithm.Create(hashAlgorithm); byte[] tbsHash = ha.ComputeHash(tbs); signature = r.CreateSignature(tbsHash); } } else if (key is DSA) { throw new NotImplementedException("not yet"); } else { throw new CryptographicException("Unknown assymetric algorithm"); } // encryptedDigest EncryptedDigest, signerInfo.Add(new ASN1(0x04, signature)); // unauthenticatedAttributes [1] IMPLICIT Attributes OPTIONAL if (unauthenticatedAttributes.Count > 0) { ASN1 ua = signerInfo.Add(new ASN1(0xA1)); unauthenticatedAttributes.Sort(new SortedSet()); foreach (ASN1 attr in unauthenticatedAttributes) { ua.Add(attr); } } return(signerInfo); }
internal ASN1 GetASN1() { ASN1 asn = new ASN1(48); byte[] data = new byte[] { this.version }; asn.Add(new ASN1(2, data)); ASN1 asn2 = asn.Add(new ASN1(49)); if (this.hashAlgorithm != null) { string oid = CryptoConfig.MapNameToOID(this.hashAlgorithm); asn2.Add(PKCS7.AlgorithmIdentifier(oid)); } ASN1 asn3 = this.contentInfo.ASN1; asn.Add(asn3); if (!this.signed && this.hashAlgorithm != null) { if (this.mda) { ASN1 value = PKCS7.Attribute("1.2.840.113549.1.9.3", asn3[0]); this.signerInfo.AuthenticatedAttributes.Add(value); HashAlgorithm hashAlgorithm = HashAlgorithm.Create(this.hashAlgorithm); byte[] data2 = hashAlgorithm.ComputeHash(asn3[1][0].Value); ASN1 asn4 = new ASN1(48); ASN1 value2 = PKCS7.Attribute("1.2.840.113549.1.9.4", asn4.Add(new ASN1(4, data2))); this.signerInfo.AuthenticatedAttributes.Add(value2); } else { RSAPKCS1SignatureFormatter rsapkcs1SignatureFormatter = new RSAPKCS1SignatureFormatter(this.signerInfo.Key); rsapkcs1SignatureFormatter.SetHashAlgorithm(this.hashAlgorithm); HashAlgorithm hashAlgorithm2 = HashAlgorithm.Create(this.hashAlgorithm); byte[] rgbHash = hashAlgorithm2.ComputeHash(asn3[1][0].Value); this.signerInfo.Signature = rsapkcs1SignatureFormatter.CreateSignature(rgbHash); } this.signed = true; } if (this.certs.Count > 0) { ASN1 asn5 = asn.Add(new ASN1(160)); foreach (X509Certificate x509Certificate in this.certs) { asn5.Add(new ASN1(x509Certificate.RawData)); } } if (this.crls.Count > 0) { ASN1 asn6 = asn.Add(new ASN1(161)); foreach (object obj in this.crls) { byte[] data3 = (byte[])obj; asn6.Add(new ASN1(data3)); } } ASN1 asn7 = asn.Add(new ASN1(49)); if (this.signerInfo.Key != null) { asn7.Add(this.signerInfo.ASN1); } return(asn); }
internal ASN1 GetASN1 () { if ((key == null) || (hashAlgorithm == null)) return null; byte[] ver = { version }; ASN1 signerInfo = new ASN1 (0x30); // version Version -> Version ::= INTEGER signerInfo.Add (new ASN1 (0x02, ver)); // issuerAndSerialNumber IssuerAndSerialNumber, signerInfo.Add (PKCS7.IssuerAndSerialNumber (x509)); // digestAlgorithm DigestAlgorithmIdentifier, string hashOid = CryptoConfig.MapNameToOID (hashAlgorithm); signerInfo.Add (AlgorithmIdentifier (hashOid)); // authenticatedAttributes [0] IMPLICIT Attributes OPTIONAL, ASN1 aa = null; if (authenticatedAttributes.Count > 0) { aa = signerInfo.Add (new ASN1 (0xA0)); authenticatedAttributes.Sort(new SortedSet ()); foreach (ASN1 attr in authenticatedAttributes) aa.Add (attr); } // digestEncryptionAlgorithm DigestEncryptionAlgorithmIdentifier, if (key is RSA) { signerInfo.Add (AlgorithmIdentifier (PKCS7.Oid.rsaEncryption)); if (aa != null) { // Calculate the signature here; otherwise it must be set from SignedData RSAPKCS1SignatureFormatter r = new RSAPKCS1SignatureFormatter (key); r.SetHashAlgorithm (hashAlgorithm); byte[] tbs = aa.GetBytes (); tbs [0] = 0x31; // not 0xA0 for signature HashAlgorithm ha = HashAlgorithm.Create (hashAlgorithm); byte[] tbsHash = ha.ComputeHash (tbs); signature = r.CreateSignature (tbsHash); } } else if (key is DSA) { throw new NotImplementedException ("not yet"); } else throw new CryptographicException ("Unknown assymetric algorithm"); // encryptedDigest EncryptedDigest, signerInfo.Add (new ASN1 (0x04, signature)); // unauthenticatedAttributes [1] IMPLICIT Attributes OPTIONAL if (unauthenticatedAttributes.Count > 0) { ASN1 ua = signerInfo.Add (new ASN1 (0xA1)); unauthenticatedAttributes.Sort(new SortedSet ()); foreach (ASN1 attr in unauthenticatedAttributes) ua.Add (attr); } return signerInfo; }
private ASN1 CertificateSafeBag (X509Certificate x509, IDictionary attributes) { ASN1 encapsulatedCertificate = new ASN1 (0x04, x509.RawData); PKCS7.ContentInfo ci = new PKCS7.ContentInfo (); ci.ContentType = x509Certificate; ci.Content.Add (encapsulatedCertificate); ASN1 bagValue = new ASN1 (0xA0); bagValue.Add (ci.ASN1); ASN1 safeBag = new ASN1 (0x30); safeBag.Add (ASN1Convert.FromOid (certBag)); safeBag.Add (bagValue); if (attributes != null) { ASN1 bagAttributes = new ASN1 (0x31); IDictionaryEnumerator de = attributes.GetEnumerator (); while (de.MoveNext ()) { string oid = (string)de.Key; switch (oid) { case PKCS9.friendlyName: ArrayList names = (ArrayList)de.Value; if (names.Count > 0) { ASN1 pkcs12Attribute = new ASN1 (0x30); pkcs12Attribute.Add (ASN1Convert.FromOid (PKCS9.friendlyName)); ASN1 attrValues = new ASN1 (0x31); foreach (byte[] name in names) { ASN1 attrValue = new ASN1 (0x1e); attrValue.Value = name; attrValues.Add (attrValue); } pkcs12Attribute.Add (attrValues); bagAttributes.Add (pkcs12Attribute); } break; case PKCS9.localKeyId: ArrayList keys = (ArrayList)de.Value; if (keys.Count > 0) { ASN1 pkcs12Attribute = new ASN1 (0x30); pkcs12Attribute.Add (ASN1Convert.FromOid (PKCS9.localKeyId)); ASN1 attrValues = new ASN1 (0x31); foreach (byte[] key in keys) { ASN1 attrValue = new ASN1 (0x04); attrValue.Value = key; attrValues.Add (attrValue); } pkcs12Attribute.Add (attrValues); bagAttributes.Add (pkcs12Attribute); } break; default: break; } } if (bagAttributes.Count > 0) { safeBag.Add (bagAttributes); } } return safeBag; }
/* * SafeContents ::= SEQUENCE OF SafeBag * * SafeBag ::= SEQUENCE { * bagId BAG-TYPE.&id ({PKCS12BagSet}), * bagValue [0] EXPLICIT BAG-TYPE.&Type({PKCS12BagSet}{@bagId}), * bagAttributes SET OF PKCS12Attribute OPTIONAL * } */ public byte[] GetBytes () { // TODO (incomplete) ASN1 safeBagSequence = new ASN1 (0x30); // Sync Safe Bag list since X509CertificateCollection may be updated ArrayList scs = new ArrayList (); foreach (SafeBag sb in _safeBags) { if (sb.BagOID.Equals (certBag)) { ASN1 safeBag = sb.ASN1; ASN1 bagValue = safeBag [1]; PKCS7.ContentInfo cert = new PKCS7.ContentInfo (bagValue.Value); scs.Add (new X509Certificate (cert.Content [0].Value)); } } ArrayList addcerts = new ArrayList (); ArrayList removecerts = new ArrayList (); foreach (X509Certificate c in Certificates) { bool found = false; foreach (X509Certificate lc in scs) { if (Compare (c.RawData, lc.RawData)) { found = true; } } if (!found) { addcerts.Add (c); } } foreach (X509Certificate c in scs) { bool found = false; foreach (X509Certificate lc in Certificates) { if (Compare (c.RawData, lc.RawData)) { found = true; } } if (!found) { removecerts.Add (c); } } foreach (X509Certificate c in removecerts) { RemoveCertificate (c); } foreach (X509Certificate c in addcerts) { AddCertificate (c); } // Sync done if (_safeBags.Count > 0) { ASN1 certsSafeBag = new ASN1 (0x30); foreach (SafeBag sb in _safeBags) { if (sb.BagOID.Equals (certBag)) { certsSafeBag.Add (sb.ASN1); } } if (certsSafeBag.Count > 0) { byte[] certsSalt = new byte [8]; RNG.GetBytes (certsSalt); ASN1 seqParams = new ASN1 (0x30); seqParams.Add (new ASN1 (0x04, certsSalt)); seqParams.Add (ASN1Convert.FromInt32 (_iterations)); ASN1 seqPbe = new ASN1 (0x30); seqPbe.Add (ASN1Convert.FromOid (pbeWithSHAAnd3KeyTripleDESCBC)); seqPbe.Add (seqParams); byte[] encrypted = Encrypt (pbeWithSHAAnd3KeyTripleDESCBC, certsSalt, _iterations, certsSafeBag.GetBytes ()); ASN1 encryptedCerts = new ASN1 (0x80, encrypted); ASN1 seq = new ASN1 (0x30); seq.Add (ASN1Convert.FromOid (PKCS7.Oid.data)); seq.Add (seqPbe); seq.Add (encryptedCerts); ASN1 certsVersion = new ASN1 (0x02, new byte [1] { 0x00 }); ASN1 encData = new ASN1 (0x30); encData.Add (certsVersion); encData.Add (seq); ASN1 certsContent = new ASN1 (0xA0); certsContent.Add (encData); PKCS7.ContentInfo bag = new PKCS7.ContentInfo (PKCS7.Oid.encryptedData); bag.Content = certsContent; safeBagSequence.Add (bag.ASN1); } } if (_safeBags.Count > 0) { ASN1 safeContents = new ASN1 (0x30); foreach (SafeBag sb in _safeBags) { if (sb.BagOID.Equals (keyBag) || sb.BagOID.Equals (pkcs8ShroudedKeyBag)) { safeContents.Add (sb.ASN1); } } if (safeContents.Count > 0) { ASN1 content = new ASN1 (0xA0); content.Add (new ASN1 (0x04, safeContents.GetBytes ())); PKCS7.ContentInfo keyBag = new PKCS7.ContentInfo (PKCS7.Oid.data); keyBag.Content = content; safeBagSequence.Add (keyBag.ASN1); } } ASN1 encapsulates = new ASN1 (0x04, safeBagSequence.GetBytes ()); ASN1 ci = new ASN1 (0xA0); ci.Add (encapsulates); PKCS7.ContentInfo authSafe = new PKCS7.ContentInfo (PKCS7.Oid.data); authSafe.Content = ci; ASN1 macData = new ASN1 (0x30); if (_password != null) { // only for password based encryption byte[] salt = new byte [20]; RNG.GetBytes (salt); byte[] macValue = MAC (_password, salt, _iterations, authSafe.Content [0].Value); ASN1 oidSeq = new ASN1 (0x30); oidSeq.Add (ASN1Convert.FromOid ("1.3.14.3.2.26")); // SHA1 oidSeq.Add (new ASN1 (0x05)); ASN1 mac = new ASN1 (0x30); mac.Add (oidSeq); mac.Add (new ASN1 (0x04, macValue)); macData.Add (mac); macData.Add (new ASN1 (0x04, salt)); macData.Add (ASN1Convert.FromInt32 (_iterations)); } ASN1 version = new ASN1 (0x02, new byte [1] { 0x03 }); ASN1 pfx = new ASN1 (0x30); pfx.Add (version); pfx.Add (authSafe.ASN1); if (macData.Count > 0) { // only for password based encryption pfx.Add (macData); } return pfx.GetBytes (); }
public X509SubjectKeyIdentifierExtension (PublicKey key, X509SubjectKeyIdentifierHashAlgorithm algorithm, bool critical) { if (key == null) throw new ArgumentNullException ("key"); byte[] pkraw = key.EncodedKeyValue.RawData; // compute SKI switch (algorithm) { // hash of the public key, excluding Tag, Length and unused bits values case X509SubjectKeyIdentifierHashAlgorithm.Sha1: _subjectKeyIdentifier = SHA1.Create ().ComputeHash (pkraw); break; // 0100 bit pattern followed by the 60 last bit of the hash case X509SubjectKeyIdentifierHashAlgorithm.ShortSha1: byte[] hash = SHA1.Create ().ComputeHash (pkraw); _subjectKeyIdentifier = new byte [8]; Buffer.BlockCopy (hash, 12, _subjectKeyIdentifier, 0, 8); _subjectKeyIdentifier [0] = (byte) (0x40 | (_subjectKeyIdentifier [0] & 0x0F)); break; // hash of the public key, including Tag, Length and unused bits values case X509SubjectKeyIdentifierHashAlgorithm.CapiSha1: // CryptoAPI does that hash on the complete subjectPublicKeyInfo (unlike PKIX) // http://groups.google.ca/groups?selm=e7RqM%24plCHA.1488%40tkmsftngp02&oe=UTF-8&output=gplain ASN1 subjectPublicKeyInfo = new ASN1 (0x30); ASN1 algo = subjectPublicKeyInfo.Add (new ASN1 (0x30)); algo.Add (new ASN1 (CryptoConfig.EncodeOID (key.Oid.Value))); algo.Add (new ASN1 (key.EncodedParameters.RawData)); // add an extra byte for the unused bits (none) byte[] full = new byte [pkraw.Length + 1]; Buffer.BlockCopy (pkraw, 0, full, 1, pkraw.Length); subjectPublicKeyInfo.Add (new ASN1 (0x03, full)); _subjectKeyIdentifier = SHA1.Create ().ComputeHash (subjectPublicKeyInfo.GetBytes ()); break; default: throw new ArgumentException ("algorithm"); } _oid = new Oid (oid, friendlyName); base.Critical = critical; RawData = Encode (); }
internal byte[] Encode () { ASN1 ex = new ASN1 (0x30); foreach (Oid o in _enhKeyUsage) { ex.Add (ASN1Convert.FromOid (o.Value)); } return ex.GetBytes (); }
internal ASN1 GetASN1 () { // SignedData ::= SEQUENCE { ASN1 signedData = new ASN1 (0x30); // version Version -> Version ::= INTEGER byte[] ver = { version }; signedData.Add (new ASN1 (0x02, ver)); // digestAlgorithms DigestAlgorithmIdentifiers -> DigestAlgorithmIdentifiers ::= SET OF DigestAlgorithmIdentifier ASN1 digestAlgorithms = signedData.Add (new ASN1 (0x31)); if (hashAlgorithm != null) { string hashOid = CryptoConfig.MapNameToOID (hashAlgorithm); digestAlgorithms.Add (AlgorithmIdentifier (hashOid)); } // contentInfo ContentInfo, ASN1 ci = contentInfo.ASN1; signedData.Add (ci); if (!signed && (hashAlgorithm != null)) { if (mda) { // Use authenticated attributes for signature // Automatically add the contentType authenticated attribute ASN1 ctattr = Attribute (Oid.contentType, ci[0]); signerInfo.AuthenticatedAttributes.Add (ctattr); // Automatically add the messageDigest authenticated attribute HashAlgorithm ha = HashAlgorithm.Create (hashAlgorithm); byte[] idcHash = ha.ComputeHash (ci[1][0].Value); ASN1 md = new ASN1 (0x30); ASN1 mdattr = Attribute (Oid.messageDigest, md.Add (new ASN1 (0x04, idcHash))); signerInfo.AuthenticatedAttributes.Add (mdattr); } else { // Don't use authenticated attributes for signature -- signature is content RSAPKCS1SignatureFormatter r = new RSAPKCS1SignatureFormatter (signerInfo.Key); r.SetHashAlgorithm (hashAlgorithm); HashAlgorithm ha = HashAlgorithm.Create (hashAlgorithm); byte[] sig = ha.ComputeHash (ci[1][0].Value); signerInfo.Signature = r.CreateSignature (sig); } signed = true; } // certificates [0] IMPLICIT ExtendedCertificatesAndCertificates OPTIONAL, if (certs.Count > 0) { ASN1 a0 = signedData.Add (new ASN1 (0xA0)); foreach (X509Certificate x in certs) a0.Add (new ASN1 (x.RawData)); } // crls [1] IMPLICIT CertificateRevocationLists OPTIONAL, if (crls.Count > 0) { ASN1 a1 = signedData.Add (new ASN1 (0xA1)); foreach (byte[] crl in crls) a1.Add (new ASN1 (crl)); } // signerInfos SignerInfos -> SignerInfos ::= SET OF SignerInfo ASN1 signerInfos = signedData.Add (new ASN1 (0x31)); if (signerInfo.Key != null) signerInfos.Add (signerInfo.ASN1); return signedData; }
internal ASN1 GetASN1() { // SignedData ::= SEQUENCE { ASN1 signedData = new ASN1(0x30); // version Version -> Version ::= INTEGER byte[] ver = { version }; signedData.Add(new ASN1(0x02, ver)); // digestAlgorithms DigestAlgorithmIdentifiers -> DigestAlgorithmIdentifiers ::= SET OF DigestAlgorithmIdentifier ASN1 digestAlgorithms = signedData.Add(new ASN1(0x31)); if (hashAlgorithm != null) { string hashOid = CryptoConfig.MapNameToOID(hashAlgorithm); digestAlgorithms.Add(AlgorithmIdentifier(hashOid)); } // contentInfo ContentInfo, ASN1 ci = contentInfo.ASN1; signedData.Add(ci); if (!signed && (hashAlgorithm != null)) { if (mda) { // Use authenticated attributes for signature // Automatically add the contentType authenticated attribute ASN1 ctattr = Attribute(Oid.contentType, ci[0]); signerInfo.AuthenticatedAttributes.Add(ctattr); // Automatically add the messageDigest authenticated attribute HashAlgorithm ha = HashAlgorithm.Create(hashAlgorithm); byte[] idcHash = ha.ComputeHash(ci[1][0].Value); ASN1 md = new ASN1(0x30); ASN1 mdattr = Attribute(Oid.messageDigest, md.Add(new ASN1(0x04, idcHash))); signerInfo.AuthenticatedAttributes.Add(mdattr); } else { // Don't use authenticated attributes for signature -- signature is content RSAPKCS1SignatureFormatter r = new RSAPKCS1SignatureFormatter(signerInfo.Key); r.SetHashAlgorithm(hashAlgorithm); HashAlgorithm ha = HashAlgorithm.Create(hashAlgorithm); byte[] sig = ha.ComputeHash(ci[1][0].Value); signerInfo.Signature = r.CreateSignature(sig); } signed = true; } // certificates [0] IMPLICIT ExtendedCertificatesAndCertificates OPTIONAL, if (certs.Count > 0) { ASN1 a0 = signedData.Add(new ASN1(0xA0)); foreach (X509Certificate x in certs) { a0.Add(new ASN1(x.RawData)); } } // crls [1] IMPLICIT CertificateRevocationLists OPTIONAL, if (crls.Count > 0) { ASN1 a1 = signedData.Add(new ASN1(0xA1)); foreach (byte[] crl in crls) { a1.Add(new ASN1(crl)); } } // signerInfos SignerInfos -> SignerInfos ::= SET OF SignerInfo ASN1 signerInfos = signedData.Add(new ASN1(0x31)); if (signerInfo.Key != null) { signerInfos.Add(signerInfo.ASN1); } return(signedData); }
// Creates an encrypted PKCS#7 ContentInfo with safeBags as its SafeContents. Used in GetBytes(), above. private PKCS7.ContentInfo EncryptedContentInfo(ASN1 safeBags, string algorithmOid) { byte[] salt = new byte [8]; RNG.GetBytes (salt); ASN1 seqParams = new ASN1 (0x30); seqParams.Add (new ASN1 (0x04, salt)); seqParams.Add (ASN1Convert.FromInt32 (_iterations)); ASN1 seqPbe = new ASN1 (0x30); seqPbe.Add (ASN1Convert.FromOid (algorithmOid)); seqPbe.Add (seqParams); byte[] encrypted = Encrypt (algorithmOid, salt, _iterations, safeBags.GetBytes ()); ASN1 encryptedContent = new ASN1 (0x80, encrypted); ASN1 seq = new ASN1 (0x30); seq.Add (ASN1Convert.FromOid (PKCS7.Oid.data)); seq.Add (seqPbe); seq.Add (encryptedContent); ASN1 version = new ASN1 (0x02, new byte [1] { 0x00 }); ASN1 encData = new ASN1 (0x30); encData.Add (version); encData.Add (seq); ASN1 finalContent = new ASN1 (0xA0); finalContent.Add (encData); PKCS7.ContentInfo bag = new PKCS7.ContentInfo (PKCS7.Oid.encryptedData); bag.Content = finalContent; return bag; }
public byte[] GetBytes () { if (InnerList.Count < 1) return null; ASN1 sequence = new ASN1 (0x30); for (int i=0; i < InnerList.Count; i++) { X509Extension x = (X509Extension) InnerList [i]; sequence.Add (x.ASN1); } return sequence.GetBytes (); }
private ASN1 SecretBagSafeBag (byte[] secret, IDictionary attributes) { ASN1 safeBag = new ASN1 (0x30); safeBag.Add (ASN1Convert.FromOid (secretBag)); ASN1 bagValue = new ASN1 (0x80, secret); safeBag.Add (bagValue); if (attributes != null) { ASN1 bagAttributes = new ASN1 (0x31); IDictionaryEnumerator de = attributes.GetEnumerator (); while (de.MoveNext ()) { string oid = (string)de.Key; switch (oid) { case PKCS9.friendlyName: ArrayList names = (ArrayList)de.Value; if (names.Count > 0) { ASN1 pkcs12Attribute = new ASN1 (0x30); pkcs12Attribute.Add (ASN1Convert.FromOid (PKCS9.friendlyName)); ASN1 attrValues = new ASN1 (0x31); foreach (byte[] name in names) { ASN1 attrValue = new ASN1 (0x1e); attrValue.Value = name; attrValues.Add (attrValue); } pkcs12Attribute.Add (attrValues); bagAttributes.Add (pkcs12Attribute); } break; case PKCS9.localKeyId: ArrayList keys = (ArrayList)de.Value; if (keys.Count > 0) { ASN1 pkcs12Attribute = new ASN1 (0x30); pkcs12Attribute.Add (ASN1Convert.FromOid (PKCS9.localKeyId)); ASN1 attrValues = new ASN1 (0x31); foreach (byte[] key in keys) { ASN1 attrValue = new ASN1 (0x04); attrValue.Value = key; attrValues.Add (attrValue); } pkcs12Attribute.Add (attrValues); bagAttributes.Add (pkcs12Attribute); } break; default: break; } } if (bagAttributes.Count > 0) { safeBag.Add (bagAttributes); } } return safeBag; }
internal byte[] Encode () { ASN1 ex = new ASN1 (0x30); if (_certificateAuthority) ex.Add (new ASN1 (0x01, new byte[] { 0xFF })); if (_hasPathLengthConstraint) { // MS encodes the 0 (pathLengthConstraint is OPTIONAL) // and in a long form (02 00 versus 02 01 00) if (_pathLengthConstraint == 0) ex.Add (new ASN1 (0x02, new byte[] { 0x00 })); else ex.Add (ASN1Convert.FromInt32 (_pathLengthConstraint)); } return ex.GetBytes (); }
private byte[] GetKeyIdentifier (Mono.Security.X509.X509Certificate x509) { // if present in certificate return value of the SubjectKeyIdentifier Mono.Security.X509.X509Extension extn = x509.Extensions ["2.5.29.14"]; if (extn != null) { ASN1 bs = new ASN1 (extn.Value.Value); return bs.Value; } // strangely DEPRECATED keyAttributes isn't used here (like KeyUsage) // if not then we must calculate the SubjectKeyIdentifier ourselve // Note: MS does that hash on the complete subjectPublicKeyInfo (unlike PKIX) // http://groups.google.ca/groups?selm=e7RqM%24plCHA.1488%40tkmsftngp02&oe=UTF-8&output=gplain ASN1 subjectPublicKeyInfo = new ASN1 (0x30); ASN1 algo = subjectPublicKeyInfo.Add (new ASN1 (0x30)); algo.Add (new ASN1 (CryptoConfig.EncodeOID (x509.KeyAlgorithm))); // FIXME: does it work for DSA certs (without an 2.5.29.14 extension ?) algo.Add (new ASN1 (x509.KeyAlgorithmParameters)); byte[] pubkey = x509.PublicKey; byte[] bsvalue = new byte [pubkey.Length + 1]; // add unused bits (0) before the public key Array.Copy (pubkey, 0, bsvalue, 1, pubkey.Length); subjectPublicKeyInfo.Add (new ASN1 (0x03, bsvalue)); SHA1 sha = SHA1.Create (); return sha.ComputeHash (subjectPublicKeyInfo.GetBytes ()); }
private ASN1 Opus (string description, string url) { ASN1 opus = new ASN1 (0x30); if (description != null) { ASN1 part1 = opus.Add (new ASN1 (0xA0)); part1.Add (new ASN1 (0x80, Encoding.BigEndianUnicode.GetBytes (description))); } if (url != null) { ASN1 part2 = opus.Add (new ASN1 (0xA1)); part2.Add (new ASN1 (0x80, Encoding.ASCII.GetBytes (url))); } return opus; }
private byte[] Build (ASN1 tbs, string hashoid, byte[] signature) { ASN1 builder = new ASN1 (0x30); builder.Add (tbs); builder.Add (PKCS7.AlgorithmIdentifier (hashoid)); // first byte of BITSTRING is the number of unused bits in the first byte byte[] bitstring = new byte [signature.Length + 1]; Buffer.BlockCopy (signature, 0, bitstring, 1, signature.Length); builder.Add (new ASN1 (0x03, bitstring)); return builder.GetBytes (); }
static public ASN1 FromString (string rdn) { if (rdn == null) throw new ArgumentNullException ("rdn"); // get string from here to ',' or end of string int start = 0; int end = 0; ASN1 asn1 = new ASN1 (0x30); while (start < rdn.Length) { end = rdn.IndexOf (',', end) + 1; if (end == 0) end = rdn.Length + 1; string av = rdn.Substring (start, end - start - 1); // get '=' position in substring int equal = av.IndexOf ('='); // get AttributeType string attributeType = av.Substring (0, equal); // get value string attributeValue = av.Substring (equal + 1); X520.AttributeTypeAndValue atv = GetAttributeFromOid (attributeType); atv.Value = attributeValue; asn1.Add (new ASN1 (0x31, atv.GetBytes ())); // next part start = end; if (start != - 1) { if (end > rdn.Length) break; } } return asn1; }
public virtual byte[] Sign (DSA key) { string oid = "1.2.840.10040.4.3"; ASN1 tbs = ToBeSigned (oid); HashAlgorithm ha = HashAlgorithm.Create (hashName); if (!(ha is SHA1)) throw new NotSupportedException ("Only SHA-1 is supported for DSA"); byte[] hash = ha.ComputeHash (tbs.GetBytes ()); DSASignatureFormatter dsa = new DSASignatureFormatter (key); dsa.SetHashAlgorithm (hashName); byte[] rs = dsa.CreateSignature (hash); // split R and S byte[] r = new byte [20]; Buffer.BlockCopy (rs, 0, r, 0, 20); byte[] s = new byte [20]; Buffer.BlockCopy (rs, 20, s, 0, 20); ASN1 signature = new ASN1 (0x30); signature.Add (new ASN1 (0x02, r)); signature.Add (new ASN1 (0x02, s)); // dsaWithSha1 (1 2 840 10040 4 3) return Build (tbs, oid, signature.GetBytes ()); }
internal ASN1 GetASN1() { if (key == null || this.hashAlgorithm == null) { return(null); } byte[] data = new byte[1] { version }; ASN1 aSN = new ASN1(48); aSN.Add(new ASN1(2, data)); aSN.Add(IssuerAndSerialNumber(x509)); string oid = CryptoConfig.MapNameToOID(this.hashAlgorithm); aSN.Add(AlgorithmIdentifier(oid)); ASN1 aSN2 = null; if (authenticatedAttributes.Count > 0) { aSN2 = aSN.Add(new ASN1(160)); authenticatedAttributes.Sort(new SortedSet()); foreach (ASN1 authenticatedAttribute in authenticatedAttributes) { aSN2.Add(authenticatedAttribute); } } if (key is RSA) { aSN.Add(AlgorithmIdentifier("1.2.840.113549.1.1.1")); if (aSN2 != null) { RSAPKCS1SignatureFormatter rSAPKCS1SignatureFormatter = new RSAPKCS1SignatureFormatter(key); rSAPKCS1SignatureFormatter.SetHashAlgorithm(this.hashAlgorithm); byte[] bytes = aSN2.GetBytes(); bytes[0] = 49; HashAlgorithm hashAlgorithm = HashAlgorithm.Create(this.hashAlgorithm); byte[] rgbHash = hashAlgorithm.ComputeHash(bytes); signature = rSAPKCS1SignatureFormatter.CreateSignature(rgbHash); } aSN.Add(new ASN1(4, signature)); if (unauthenticatedAttributes.Count > 0) { ASN1 aSN3 = aSN.Add(new ASN1(161)); unauthenticatedAttributes.Sort(new SortedSet()); { foreach (ASN1 unauthenticatedAttribute in unauthenticatedAttributes) { aSN3.Add(unauthenticatedAttribute); } return(aSN); } } return(aSN); } if (key is DSA) { throw new NotImplementedException("not yet"); } throw new CryptographicException("Unknown assymetric algorithm"); }
protected override void Encode () { ASN1 seq = new ASN1 (0x30); if (aki == null) { throw new InvalidOperationException ("Invalid AuthorityKeyIdentifier extension"); } seq.Add (new ASN1 (0x80, aki)); extnValue = new ASN1 (0x04); extnValue.Add (seq); }
public X500DistinguishedName (string distinguishedName, X500DistinguishedNameFlags flag) { if (distinguishedName == null) throw new ArgumentNullException ("distinguishedName"); if ((flag != 0) && ((flag & AllFlags) == 0)) throw new ArgumentException ("flag"); Oid = new Oid (); if (distinguishedName.Length == 0) { // empty (0x00) ASN.1 sequence (0x30) RawData = new byte [2] { 0x30, 0x00 }; DecodeRawData (); } else { var dn = MX.X501.FromString (distinguishedName); if ((flag & X500DistinguishedNameFlags.Reversed) != 0) { ASN1 rdn = new ASN1 (0x30); for (int i = dn.Count - 1; i >= 0; i--) rdn.Add (dn [i]); dn = rdn; } RawData = dn.GetBytes (); if (flag == X500DistinguishedNameFlags.None) name = distinguishedName; else name = Decode (flag); } }
protected override void Encode () { if (extnValue == null) { extnValue = new ASN1 (0x30); if (cA) extnValue.Add (new ASN1 (0x01, new byte[] { 0xFF })); if (pathLenConstraint > 0) extnValue.Add (ASN1Convert.FromInt32 (pathLenConstraint)); } }