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);
        }
Exemple #2
0
        /* SubjectPublicKeyInfo  ::=  SEQUENCE  {
         *      algorithm            AlgorithmIdentifier,
         *      subjectPublicKey     BIT STRING  }
         */
        private ASN1 SubjectPublicKeyInfo()
        {
            ASN1 keyInfo = new ASN1(0x30);

            if (aa is RSA)
            {
                keyInfo.Add(PKCS7.AlgorithmIdentifier("1.2.840.113549.1.1.1"));
                RSAParameters p = (aa as RSA).ExportParameters(false);

                /* RSAPublicKey ::= SEQUENCE {
                 *       modulus            INTEGER,    -- n
                 *       publicExponent     INTEGER  }  -- e
                 */
                ASN1 key = new ASN1(0x30);
                key.Add(ASN1Convert.FromUnsignedBigInteger(p.Modulus));
                key.Add(ASN1Convert.FromUnsignedBigInteger(p.Exponent));
                keyInfo.Add(new ASN1(UniqueIdentifier(key.GetBytes())));
            }
            else if (aa is DSA)
            {
                DSAParameters p = (aa as DSA).ExportParameters(false);

                /* Dss-Parms  ::=  SEQUENCE  {
                 *       p             INTEGER,
                 *       q             INTEGER,
                 *       g             INTEGER  }
                 */
                ASN1 param = new ASN1(0x30);
                param.Add(ASN1Convert.FromUnsignedBigInteger(p.P));
                param.Add(ASN1Convert.FromUnsignedBigInteger(p.Q));
                param.Add(ASN1Convert.FromUnsignedBigInteger(p.G));
                keyInfo.Add(PKCS7.AlgorithmIdentifier("1.2.840.10040.4.1", param));
                ASN1 key = keyInfo.Add(new ASN1(0x03));
                // DSAPublicKey ::= INTEGER  -- public key, y
                key.Add(ASN1Convert.FromUnsignedBigInteger(p.Y));
            }
            else
            {
                throw new NotSupportedException("Unknown Asymmetric Algorithm " + aa.ToString());
            }
            return(keyInfo);
        }
            /*
             * RSAPrivateKey ::= SEQUENCE {
             *	version           Version,
             *	modulus           INTEGER,  -- n
             *	publicExponent    INTEGER,  -- e
             *	privateExponent   INTEGER,  -- d
             *	prime1            INTEGER,  -- p
             *	prime2            INTEGER,  -- q
             *	exponent1         INTEGER,  -- d mod (p-1)
             *	exponent2         INTEGER,  -- d mod (q-1)
             *	coefficient       INTEGER,  -- (inverse of q) mod p
             *	otherPrimeInfos   OtherPrimeInfos OPTIONAL
             * }
             */
            static public byte[] Encode(RSA rsa)
            {
                RSAParameters param = rsa.ExportParameters(true);

                ASN1 rsaPrivateKey = new ASN1(0x30);

                rsaPrivateKey.Add(new ASN1(0x02, new byte [1] {
                    0x00
                }));
                rsaPrivateKey.Add(ASN1Convert.FromUnsignedBigInteger(param.Modulus));
                rsaPrivateKey.Add(ASN1Convert.FromUnsignedBigInteger(param.Exponent));
                rsaPrivateKey.Add(ASN1Convert.FromUnsignedBigInteger(param.D));
                rsaPrivateKey.Add(ASN1Convert.FromUnsignedBigInteger(param.P));
                rsaPrivateKey.Add(ASN1Convert.FromUnsignedBigInteger(param.Q));
                rsaPrivateKey.Add(ASN1Convert.FromUnsignedBigInteger(param.DP));
                rsaPrivateKey.Add(ASN1Convert.FromUnsignedBigInteger(param.DQ));
                rsaPrivateKey.Add(ASN1Convert.FromUnsignedBigInteger(param.InverseQ));

                return(rsaPrivateKey.GetBytes());
            }
Exemple #4
0
        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());
        }
Exemple #5
0
        static public ASN1 FromString(string rdn)
        {
            if (rdn == null)
            {
                throw new ArgumentNullException("rdn");
            }

            int  pos  = 0;
            ASN1 asn1 = new ASN1(0x30);

            while (pos < rdn.Length)
            {
                X520.AttributeTypeAndValue atv = ReadAttribute(rdn, ref pos);
                atv.Value = ReadValue(rdn, ref pos);

                ASN1 sequence = new ASN1(0x31);
                sequence.Add(atv.GetASN1());
                asn1.Add(sequence);
            }
            return(asn1);
        }
            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);
            }
Exemple #7
0
		static public ASN1 FromString (string rdn) 
		{
			if (rdn == null)
				throw new ArgumentNullException ("rdn");

			int pos = 0;
			ASN1 asn1 = new ASN1 (0x30);
			while (pos < rdn.Length) {
				X520.AttributeTypeAndValue atv = ReadAttribute (rdn, ref pos);
				atv.Value = ReadValue (rdn, ref pos);

				ASN1 sequence = new ASN1 (0x31);
				sequence.Add (atv.GetASN1 ());
				asn1.Add (sequence); 
			}
			return asn1;
		}
Exemple #8
0
		// PKCS #1 v.2.1, Section 9.2
		// EMSA-PKCS1-v1_5-Encode
		public static byte[] Encode_v15 (HashAlgorithm hash, byte[] hashValue, int emLength) 
		{
			if (hashValue.Length != (hash.HashSize >> 3))
				throw new CryptographicException ("bad hash length for " + hash.ToString ());

			// DigestInfo ::= SEQUENCE {
			//	digestAlgorithm AlgorithmIdentifier,
			//	digest OCTET STRING
			// }
		
			byte[] t = null;

			string oid = CryptoConfig.MapNameToOID (hash.ToString ());
			if (oid != null)
			{
				ASN1 digestAlgorithm = new ASN1 (0x30);
				digestAlgorithm.Add (new ASN1 (CryptoConfig.EncodeOID (oid)));
				digestAlgorithm.Add (new ASN1 (0x05));		// NULL
				ASN1 digest = new ASN1 (0x04, hashValue);
				ASN1 digestInfo = new ASN1 (0x30);
				digestInfo.Add (digestAlgorithm);
				digestInfo.Add (digest);

				t = digestInfo.GetBytes ();
			}
			else
			{
				// There are no valid OID, in this case t = hashValue
				// This is the case of the MD5SHA hash algorithm
				t = hashValue;
			}

			Buffer.BlockCopy (hashValue, 0, t, t.Length - hashValue.Length, hashValue.Length);
	
			int PSLength = System.Math.Max (8, emLength - t.Length - 3);
			// PS = PSLength of 0xff
	
			// EM = 0x00 | 0x01 | PS | 0x00 | T
			byte[] EM = new byte [PSLength + t.Length + 3];
			EM [1] = 0x01;
			for (int i=2; i < PSLength + 2; i++)
				EM[i] = 0xff;
			Buffer.BlockCopy (t, 0, EM, PSLength + 3, t.Length);
	
			return EM;
		}
Exemple #9
0
		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 ();
		}
Exemple #10
0
			internal ASN1 GetASN1 (byte encoding) 
			{
				byte encode = encoding;
				if (encode == 0xFF)
					encode = SelectBestEncoding ();
					
				ASN1 asn1 = new ASN1 (0x30);
				asn1.Add (ASN1Convert.FromOid (oid));
				switch (encode) {
					case 0x13:
						// PRINTABLESTRING
						asn1.Add (new ASN1 (0x13, Encoding.ASCII.GetBytes (attrValue)));
						break;
					case 0x16:
						// IA5STRING
						asn1.Add (new ASN1 (0x16, Encoding.ASCII.GetBytes (attrValue)));
						break;
					case 0x1E:
						// BMPSTRING
						asn1.Add (new ASN1 (0x1E, Encoding.BigEndianUnicode.GetBytes (attrValue)));
						break;
				}
				return asn1;
			}
Exemple #11
0
		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 ();
		}
            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);
            }
Exemple #13
0
			// Note: PKCS#8 doesn't define how to generate the key required for encryption
			// so you're on your own. Just don't try to copy the big guys too much ;)
			// Netscape:	http://www.cs.auckland.ac.nz/~pgut001/pubs/netscape.txt
			// Microsoft:	http://www.cs.auckland.ac.nz/~pgut001/pubs/breakms.txt
			public byte[] GetBytes ()
			{
				if (_algorithm == null)
					throw new CryptographicException ("No algorithm OID specified");

				ASN1 encryptionAlgorithm = new ASN1 (0x30);
				encryptionAlgorithm.Add (ASN1Convert.FromOid (_algorithm));

				// parameters ANY DEFINED BY algorithm OPTIONAL
				if ((_iterations > 0) || (_salt != null)) {
					ASN1 salt = new ASN1 (0x04, _salt);
					ASN1 iterations = ASN1Convert.FromInt32 (_iterations);

					ASN1 parameters = new ASN1 (0x30);
					parameters.Add (salt);
					parameters.Add (iterations);
					encryptionAlgorithm.Add (parameters);
				}

				// encapsulates EncryptedData into an OCTET STRING
				ASN1 encryptedData = new ASN1 (0x04, _data);

				ASN1 encryptedPrivateKeyInfo = new ASN1 (0x30);
				encryptedPrivateKeyInfo.Add (encryptionAlgorithm);
				encryptedPrivateKeyInfo.Add (encryptedData);

				return encryptedPrivateKeyInfo.GetBytes ();
			}
Exemple #14
0
		/*
		 * 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) {
					PKCS7.ContentInfo contentInfo = EncryptedContentInfo (certsSafeBag, pbeWithSHAAnd3KeyTripleDESCBC);
					safeBagSequence.Add (contentInfo.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);
				}
			}

			// Doing SecretBags separately in case we want to change their encryption independently.
			if (_safeBags.Count > 0) {
				ASN1 secretsSafeBag = new ASN1 (0x30);
				foreach (SafeBag sb in _safeBags) {
					if (sb.BagOID.Equals (secretBag)) {
						secretsSafeBag.Add (sb.ASN1);
					}
				}

				if (secretsSafeBag.Count > 0) {
					PKCS7.ContentInfo contentInfo = EncryptedContentInfo (secretsSafeBag, pbeWithSHAAnd3KeyTripleDESCBC);
					safeBagSequence.Add (contentInfo.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 ();
		}
Exemple #15
0
		// 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;
		}
		protected override ASN1 ToBeSigned (string oid) 
		{
			// TBSCertificate
			ASN1 tbsCert = new ASN1 (0x30);

			if (version > 1) {
				// TBSCertificate / [0] Version DEFAULT v1,
				byte[] ver = { (byte)(version - 1) };
				ASN1 v = tbsCert.Add (new ASN1 (0xA0));
				v.Add (new ASN1 (0x02, ver));
			}

			// TBSCertificate / CertificateSerialNumber,
			tbsCert.Add (new ASN1 (0x02, sn));

			// TBSCertificate / AlgorithmIdentifier,
                        tbsCert.Add (PKCS7.AlgorithmIdentifier (oid));

			// TBSCertificate / Name
			tbsCert.Add (X501.FromString (issuer));

			// TBSCertificate / Validity
			ASN1 validity = tbsCert.Add (new ASN1 (0x30));
			// TBSCertificate / Validity / Time
			validity.Add (ASN1Convert.FromDateTime (notBefore));
			// TBSCertificate / Validity / Time
			validity.Add (ASN1Convert.FromDateTime (notAfter));

			// TBSCertificate / Name
			tbsCert.Add (X501.FromString (subject));

			// TBSCertificate / SubjectPublicKeyInfo
			tbsCert.Add (SubjectPublicKeyInfo ());
                        
			if (version > 1) {
				// TBSCertificate / [1]  IMPLICIT UniqueIdentifier OPTIONAL
				if (issuerUniqueID != null)
					tbsCert.Add (new ASN1 (0xA1, UniqueIdentifier (issuerUniqueID)));

				// TBSCertificate / [2]  IMPLICIT UniqueIdentifier OPTIONAL
				if (subjectUniqueID != null)
					tbsCert.Add (new ASN1 (0xA1, UniqueIdentifier (subjectUniqueID)));

				// TBSCertificate / [3]  Extensions OPTIONAL
				if ((version > 2) &&  (extensions.Count > 0))
					tbsCert.Add (new ASN1 (0xA3, extensions.GetBytes ()));
			}

			return tbsCert;
		}
		/* SubjectPublicKeyInfo  ::=  SEQUENCE  {
		 *      algorithm            AlgorithmIdentifier,
		 *      subjectPublicKey     BIT STRING  }
		 */
		private ASN1 SubjectPublicKeyInfo () 
		{
			ASN1 keyInfo = new ASN1 (0x30);
			if (aa is RSA) {
				keyInfo.Add (PKCS7.AlgorithmIdentifier ("1.2.840.113549.1.1.1"));
				RSAParameters p = (aa as RSA).ExportParameters (false);
				/* RSAPublicKey ::= SEQUENCE {
				 *       modulus            INTEGER,    -- n
				 *       publicExponent     INTEGER  }  -- e
				 */
				ASN1 key = new ASN1 (0x30);
				key.Add (ASN1Convert.FromUnsignedBigInteger (p.Modulus));
				key.Add (ASN1Convert.FromUnsignedBigInteger (p.Exponent));
				keyInfo.Add (new ASN1 (UniqueIdentifier (key.GetBytes ())));
			}
			else if (aa is DSA) {
				DSAParameters p = (aa as DSA).ExportParameters (false);
				/* Dss-Parms  ::=  SEQUENCE  {
				 *       p             INTEGER,
				 *       q             INTEGER,
				 *       g             INTEGER  }
				 */
				ASN1 param = new ASN1 (0x30);
				param.Add (ASN1Convert.FromUnsignedBigInteger (p.P));
				param.Add (ASN1Convert.FromUnsignedBigInteger (p.Q));
				param.Add (ASN1Convert.FromUnsignedBigInteger (p.G));
				keyInfo.Add (PKCS7.AlgorithmIdentifier ("1.2.840.10040.4.1", param));
				ASN1 key = keyInfo.Add (new ASN1 (0x03));
				// DSAPublicKey ::= INTEGER  -- public key, y
				key.Add (ASN1Convert.FromUnsignedBigInteger (p.Y));
			}
			else
				throw new NotSupportedException ("Unknown Asymmetric Algorithm " + aa.ToString ());
			return keyInfo;
		}
            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);
            }
Exemple #19
0
		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;
		}
Exemple #20
0
			public byte[] GetBytes () 
			{
				ASN1 privateKeyAlgorithm = new ASN1 (0x30);
				privateKeyAlgorithm.Add (ASN1Convert.FromOid (_algorithm));
				privateKeyAlgorithm.Add (new ASN1 (0x05)); // ASN.1 NULL

				ASN1 pki = new ASN1 (0x30);
				pki.Add (new ASN1 (0x02, new byte [1] { (byte) _version }));
				pki.Add (privateKeyAlgorithm);
				pki.Add (new ASN1 (0x04, _key));

				if (_list.Count > 0) {
					ASN1 attributes = new ASN1 (0xA0);
					foreach (ASN1 attribute in _list) {
						attributes.Add (attribute);
					}
					pki.Add (attributes);
				}

				return pki.GetBytes ();
			}
Exemple #21
0
			/*
			 * RSAPrivateKey ::= SEQUENCE {
			 *	version           Version, 
			 *	modulus           INTEGER,  -- n
			 *	publicExponent    INTEGER,  -- e
			 *	privateExponent   INTEGER,  -- d
			 *	prime1            INTEGER,  -- p
			 *	prime2            INTEGER,  -- q
			 *	exponent1         INTEGER,  -- d mod (p-1)
			 *	exponent2         INTEGER,  -- d mod (q-1) 
			 *	coefficient       INTEGER,  -- (inverse of q) mod p
			 *	otherPrimeInfos   OtherPrimeInfos OPTIONAL 
			 * }
			 */
			static public byte[] Encode (RSA rsa) 
			{
				RSAParameters param = rsa.ExportParameters (true);

				ASN1 rsaPrivateKey = new ASN1 (0x30);
				rsaPrivateKey.Add (new ASN1 (0x02, new byte [1] { 0x00 }));
				rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.Modulus));
				rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.Exponent));
				rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.D));
				rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.P));
				rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.Q));
				rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.DP));
				rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.DQ));
				rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.InverseQ));

				return rsaPrivateKey.GetBytes ();
			}
Exemple #22
0
		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 ());
		}
Exemple #23
0
		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;
		}
Exemple #24
0
		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;
		}