Ejemplo n.º 1
0
 public Oid(Oid oid) {
     if (oid == null)
         throw new ArgumentNullException("oid");
     m_value = oid.m_value;
     m_friendlyName = oid.m_friendlyName;
     m_group = oid.m_group;
 }
Ejemplo n.º 2
0
 internal SignaturePayload(int version, string contentIdentifier, Oid digestAlgorithm, byte[] digest)
 {
     Version = version;
     ContentIdentifier = contentIdentifier;
     DigestAlgorithm = digestAlgorithm;
     Digest = digest;
 }
Ejemplo n.º 3
0
		public void ConstructorNonPkcs7Oid ()
		{
			Oid o = new Oid ("1.2.3.4");
			ContentInfo ci = new ContentInfo (o, asnNull);
			Assert.AreEqual (asnNull, ci.Content, "Content");
			Assert.AreEqual ("1.2.3.4", ci.ContentType.Value, "ContentType.Value");
		}
Ejemplo n.º 4
0
 public static bool HasEKU(this X509Certificate2 self, Oid requiredEku)
 {
     return self.Extensions
         .OfType<X509EnhancedKeyUsageExtension>()
         .SelectMany(ext => ext.EnhancedKeyUsages.Cast<Oid>())
         .Any(eku => string.Equals(requiredEku.Value, eku.Value, StringComparison.OrdinalIgnoreCase));
 }
		private void CommonStuff (CryptographicAttributeObjectCollection coll)
		{
			Assert.IsFalse (coll.IsSynchronized, "IsSynchronized");
			Assert.AreSame (coll, coll.SyncRoot, "SyncRoot");
			Assert.IsNotNull (coll.GetEnumerator (), "GetEnumerator");

			int i = coll.Count;
			Oid o1 = new Oid ("1.2.840.113549.1.7.3");
			AsnEncodedData aed = new AsnEncodedData (o1, new byte[] { 0x05, 0x00 });
			Assert.AreEqual (i, coll.Add (aed), "Add(AsnEncodedData)");
			Assert.IsTrue ((coll[i++] is CryptographicAttributeObject), "converted");

			Oid o2 = new Oid ("1.2.840.113549.1.7.2");
			CryptographicAttributeObject cao = new CryptographicAttributeObject (o2);
			Assert.AreEqual (i, coll.Add (cao), "Add(CryptographicAttributeObject)");

			CryptographicAttributeObject[] array = new CryptographicAttributeObject [coll.Count];
			coll.CopyTo (array, 0);

			Array a = (Array) new object [coll.Count];
			ICollection c = (ICollection) coll;
			c.CopyTo (a, 0);

			IEnumerable e = (IEnumerable) coll;
			Assert.IsNotNull (e.GetEnumerator (), "GetEnumerator");

			coll.Remove (cao);
			Assert.AreEqual (i, coll.Count, "Remove(CryptographicAttributeObject)");
		}
		public void One_CryptographicAttributeObject () 
		{
			Oid o = new Oid (defaultOid);
			CryptographicAttributeObject cao = new CryptographicAttributeObject (o);
			coll = new CryptographicAttributeObjectCollection (cao);
			Count (1);
		}
Ejemplo n.º 7
0
        public AsymmetricAlgorithm DecodePublicKey(Oid oid, byte[] encodedKeyValue, byte[] encodedParameters)
        {
            int algId = OidInfo.FindOidInfo(CryptOidInfoKeyType.CRYPT_OID_INFO_OID_KEY, oid.Value, OidGroup.PublicKeyAlgorithm, fallBackToAllGroups: true).AlgId;
            switch (algId)
            {
                case AlgId.CALG_RSA_KEYX:
                case AlgId.CALG_RSA_SIGN:
                    {
                        byte[] keyBlob = DecodeKeyBlob(CryptDecodeObjectStructType.RSA_CSP_PUBLICKEYBLOB, encodedKeyValue);
                        RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                        rsa.ImportCspBlob(keyBlob);
                        return rsa;
                    }

                case AlgId.CALG_DSS_SIGN:
                    {
                        byte[] keyBlob = ConstructDSSPublicKeyCspBlob(encodedKeyValue, encodedParameters);
                        DSACryptoServiceProvider dsa = new DSACryptoServiceProvider();
                        dsa.ImportCspBlob(keyBlob);
                        return dsa;
                    }

                default:
                    throw new NotSupportedException(SR.NotSupported_KeyAlgorithm);
            }
        }
Ejemplo n.º 8
0
 public X509Extension (Oid oid, byte[] rawData, bool critical) : base (oid, rawData) {
     if (base.Oid == null || base.Oid.Value == null)
         throw new ArgumentNullException("oid");
     if (base.Oid.Value.Length == 0)
         throw new ArgumentException(SR.GetString(SR.Arg_EmptyOrNullString), "oid.Value");
     m_critical = critical;
 }
Ejemplo n.º 9
0
        public AsymmetricAlgorithm DecodePublicKey(Oid oid, byte[] encodedKeyValue, byte[] encodedParameters, ICertificatePal certificatePal)
        {
            if (oid.Value == Oids.Ecc)
            {
                return DecodeECDsaPublicKey((CertificatePal)certificatePal);
            }

            int algId = OidInfo.FindOidInfo(CryptOidInfoKeyType.CRYPT_OID_INFO_OID_KEY, oid.Value, OidGroup.PublicKeyAlgorithm, fallBackToAllGroups: true).AlgId;
            switch (algId)
            {
                case AlgId.CALG_RSA_KEYX:
                case AlgId.CALG_RSA_SIGN:
                    {
                        byte[] keyBlob = DecodeKeyBlob(CryptDecodeObjectStructType.CNG_RSA_PUBLIC_KEY_BLOB, encodedKeyValue);
                        CngKey cngKey = CngKey.Import(keyBlob, CngKeyBlobFormat.GenericPublicBlob);
                        return new RSACng(cngKey);
                    }

#if !NETNATIVE
                case AlgId.CALG_DSS_SIGN:
                    {
                        byte[] keyBlob = ConstructDSSPublicKeyCspBlob(encodedKeyValue, encodedParameters);
                        DSACryptoServiceProvider dsa = new DSACryptoServiceProvider();
                        dsa.ImportCspBlob(keyBlob);
                        return dsa;
                    }
#endif

                default:
                    throw new NotSupportedException(SR.NotSupported_KeyAlgorithm);
            }
        }
Ejemplo n.º 10
0
        public static bool IsMatch(this TimeStampToken tst, Stream data)
        {
            //check if we can verify the time-stamp
            if (tst.TimeStampInfo.HashAlgorithm.Parameters != DerNull.Instance)
            {
                trace.TraceEvent(TraceEventType.Error, 0, "The time-stamp {0} contains hash parameters {1} which isn't supported", tst.TimeStampInfo.SerialNumber, tst.TimeStampInfo.HashAlgorithm.Parameters);
                throw new NotSupportedException("Only hash algorithms without parameters are currently supported for timestamps");
            }
            if (tst.TimeStampInfo.Nonce != null)
            {
                trace.TraceEvent(TraceEventType.Error, 0, "The time-stamp {0} contains a Nonce which isn't supported", tst.TimeStampInfo.SerialNumber, tst.TimeStampInfo.HashAlgorithm.Parameters);
                throw new NotSupportedException("Time-stamp with a nonce isn't supported");
            }

            //create the hash according to the specs of the time-stamp
            var hashAlogOid = new Oid(tst.TimeStampInfo.HashAlgorithm.ObjectID.Id);
            var hashAlgo = (HashAlgorithm)CryptoConfig.CreateFromName(hashAlogOid.FriendlyName);
            byte[] signatureValueHashed = hashAlgo.ComputeHash(data);

            //verify the hash value
            byte[] timestampHash = tst.TimeStampInfo.TstInfo.MessageImprint.GetHashedMessage();

            trace.TraceEvent(TraceEventType.Verbose, 0, "Comparing the calculated hash ({3}) {1} with {2} for TST {0}", tst.TimeStampInfo.SerialNumber,
                Convert.ToBase64String(signatureValueHashed), Convert.ToBase64String(timestampHash), hashAlogOid.FriendlyName);
            return ((IStructuralEquatable)signatureValueHashed).Equals(timestampHash, StructuralComparisons.StructuralEqualityComparer);
        }
Ejemplo n.º 11
0
 public AnnotationBase(Oid id, object value)
 {
     if(null == id) { throw new ArgumentNullException(); }
     this.Id = id;
     this.Value = value;
     return;
 }
Ejemplo n.º 12
0
		public void ConstructorOidKeyLength ()
		{
			Oid o = new Oid (validOid);
			AlgorithmIdentifier ai = new AlgorithmIdentifier (o, 128);
			Assert.AreEqual (128, ai.KeyLength, "KeyLength");
			Assert.AreEqual (validOid, ai.Oid.Value, "Oid");
			Assert.AreEqual (0, ai.Parameters.Length, "Parameters");
		}
Ejemplo n.º 13
0
Archivo: Oid.cs Proyecto: nlhepler/mono
		public Oid (Oid oid) 
		{
			if (oid == null)
				throw new ArgumentNullException ("oid");

			_value = oid.Value;
			_name = oid.FriendlyName;
		}
Ejemplo n.º 14
0
		public void ConstructorOidArray () 
		{
			Oid o = new Oid (defaultOid);
			Pkcs9AttributeObject a = new Pkcs9AttributeObject (o, new byte[0]);
			Assert.AreEqual (defaultName, a.Oid.FriendlyName, "Oid.FriendlyName");
			Assert.AreEqual (defaultOid, a.Oid.Value, "Oid.Value");
			Assert.AreEqual (0, a.RawData.Length, "RawData");
		}
Ejemplo n.º 15
0
		// constructors

		public CryptographicAttributeObject (Oid oid) 
		{
			if (oid == null)
				throw new ArgumentNullException ("oid");

			_oid = new Oid (oid);
			_list = new AsnEncodedDataCollection ();
		}
Ejemplo n.º 16
0
		public void ConstructorOidObject () 
		{
			Oid o = new Oid (defaultOid);
			CryptographicAttribute ca = new CryptographicAttribute (o, o);
			Assert.AreEqual (defaultName, ca.Oid.FriendlyName, "Oid.FriendlyName");
			Assert.AreEqual (defaultOid, ca.Oid.Value, "Oid.Value");
			Assert.AreEqual (1, ca.Values.Count, "Values");
		}
Ejemplo n.º 17
0
 public Oid(Oid oid)
 {
     if (oid == null)
         throw new ArgumentNullException(nameof(oid));
     _value = oid._value;
     _friendlyName = oid._friendlyName;
     _group = oid._group;
 }
Ejemplo n.º 18
0
		public AsnEncodedData (AsnEncodedData asnEncodedData)
		{
			if (asnEncodedData == null)
				throw new ArgumentNullException ("asnEncodedData");

			Oid = new Oid (asnEncodedData._oid);
			RawData = asnEncodedData._raw;
		}
Ejemplo n.º 19
0
		public void ConstructorOidContent () 
		{
			Oid o = new Oid (defaultOid);
			ContentInfo ci = new ContentInfo (o, asnNull);
			Assert.AreEqual (asnNull, ci.Content, "Content");
			Assert.AreEqual (defaultName, ci.ContentType.FriendlyName, "ContentType.FriendlyName");
			Assert.AreEqual (defaultOid, ci.ContentType.Value, "ContentType.Value");
		}
Ejemplo n.º 20
0
		public void CopyToOid () 
		{
			OidCollection oc = new OidCollection ();
			oc.Add (new Oid ("1.0"));
			Oid[] array = new Oid [1];
			oc.CopyTo (array, 0);
			Assert.AreEqual ("1.0", array [0].Value, "CopyTo(Oid)");
		}
Ejemplo n.º 21
0
 /// <summary>
 /// The <see cref="M:System.Security.Cryptography.Pkcs.ContentInfo.#ctor(System.Security.Cryptography.Oid,System.Byte[])"/>  constructor  creates an instance of the <see cref="T:System.Security.Cryptography.Pkcs.ContentInfo"/> class by using the specified content type and an array of byte values as the data.
 /// </summary>
 /// <param name="contentType">An <see cref="T:System.Security.Cryptography.Oid"/> object that contains an <paramref name="object identifier"/> (OID) that specifies the content type of the content. This can be data, digestedData, encryptedData, envelopedData, hashedData, signedAndEnvelopedData, or signedData.  For more information, see  Remarks.</param><param name="content">An array of byte values that represents the data from which to create the <see cref="T:System.Security.Cryptography.Pkcs.ContentInfo"/> object.</param><exception cref="T:System.ArgumentNullException">A null reference  was passed to a method that does not accept it as a valid argument. </exception>
 public ContentInfo(Oid contentType, byte[] content)
 {
     if (contentType == null)
         throw new ArgumentNullException("contentType");
     if (content == null)
         throw new ArgumentNullException("content");
     this.m_contentType = contentType;
     this.m_content = content;
 }
Ejemplo n.º 22
0
 private void Decode()
 {
     if (this.RawData.Length < 2 || (int)this.RawData[1] != this.RawData.Length - 2)
         throw new CryptographicException(-2146885630);
     if ((int)this.RawData[0] != 6)
         throw new CryptographicException(-2146881269);
     this.m_contentType = new Oid(PkcsUtils.DecodeObjectIdentifier(this.RawData, 2));
     this.m_decoded = true;
 }
		public void Constructor_CryptographicAttributeObject () 
		{
			Oid o = new Oid (defaultOid);
			CryptographicAttributeObject cao = new CryptographicAttributeObject (o);
			CryptographicAttributeObjectCollection coll = new CryptographicAttributeObjectCollection (cao);
			Assert.AreEqual (1, coll.Count, "Count");
			Assert.AreSame (cao, coll[0], "this[int]");
			CommonStuff (coll);
		}
Ejemplo n.º 24
0
		public void ConstructorOidArrayList () 
		{
			Oid o = new Oid (defaultOid);
			ArrayList al = new ArrayList ();
			CryptographicAttribute ca = new CryptographicAttribute (o, al);
			Assert.AreEqual (defaultName, ca.Oid.FriendlyName, "Oid.FriendlyName");
			Assert.AreEqual (defaultOid, ca.Oid.Value, "Oid.Value");
			Assert.AreEqual (0, ca.Values.Count, "Values");
		}
Ejemplo n.º 25
0
        public static void Pkcs9AttributeAsnEncodedDataCtorEmptyOidValue()
        {
            Oid oid = new Oid(Oids.Aes128);
            oid.Value = string.Empty;

            AsnEncodedData a = new AsnEncodedData(oid, new byte[3]);
            object ign;
            Assert.Throws<ArgumentException>(() => ign = new Pkcs9AttributeObject(a));
        }
 private static string GetOidName(Oid oid)
 {
     string friendlyName = oid.FriendlyName;
     if (string.IsNullOrEmpty(friendlyName))
     {
         friendlyName = oid.Value;
     }
     return friendlyName;
 }
Ejemplo n.º 27
0
		public void Constructor_OidData () 
		{
			Oid o = new Oid ("1.0");
			AsnEncodedData aed = new AsnEncodedData (o, asnNullBytes);
			Assert.AreEqual ("1.0", aed.Oid.Value, "Oid.Value");
			Assert.IsNull (aed.Oid.FriendlyName, "Oid.FriendlyName");
			Assert.AreEqual (BitConverter.ToString (asnNullBytes), BitConverter.ToString (aed.RawData), "RawData");
			Assert.AreEqual (asnNullString, aed.Format (true), "Format");
		}
 private byte[] EncryptedBytes(byte[] bytes)
 {
     var contentInfo = new ContentInfo(bytes);
     var encryptAlgoOid = new Oid("2.16.840.1.101.3.4.1.42"); // AES-256-CBC            
     var envelopedCms = new EnvelopedCms(contentInfo, new AlgorithmIdentifier(encryptAlgoOid));
     var recipient = new CmsRecipient(CryptographicCertificate);
     envelopedCms.Encrypt(recipient);
     return envelopedCms.Encode();
 }
Ejemplo n.º 29
0
		public void ConstructorOidAsnEncodedDataCollectionNull ()
		{
			Oid o = new Oid (defaultOid);
			AsnEncodedDataCollection coll = null;
			CryptographicAttributeObject ca = new CryptographicAttributeObject (o, coll);
			Assert.AreEqual (defaultName, ca.Oid.FriendlyName, "Oid.FriendlyName");
			Assert.AreEqual (defaultOid, ca.Oid.Value, "Oid.Value");
			Assert.AreEqual (0, ca.Values.Count, "Values");
		}
Ejemplo n.º 30
0
		public AsnEncodedData (Oid oid, byte[] rawData)
		{
			Oid = oid;
			RawData = rawData;

			// yes, here oid == null is legal (by design), 
			// but no, it would not be legal for an oid string
			// see MSDN FDBK11479
		}
Ejemplo n.º 31
0
 private void Reset(System.Security.Cryptography.Oid oid, int keyLength, byte[] parameters)
 {
     this.m_oid        = oid;
     this.m_keyLength  = keyLength;
     this.m_parameters = parameters;
 }
Ejemplo n.º 32
0
 public AlgorithmIdentifier(System.Security.Cryptography.Oid oid, int keyLength)
 {
     this.Reset(oid, keyLength, new byte[0]);
 }
Ejemplo n.º 33
0
 public AlgorithmIdentifier(System.Security.Cryptography.Oid oid)
 {
     this.Reset(oid, 0, new byte[0]);
 }
Ejemplo n.º 34
0
 public PublicKey(System.Security.Cryptography.Oid oid, AsnEncodedData parameters, AsnEncodedData keyValue)
 {
     this.m_oid = new System.Security.Cryptography.Oid(oid);
     this.m_encodedParameters = new AsnEncodedData(parameters);
     this.m_encodedKeyValue   = new AsnEncodedData(keyValue);
 }
Ejemplo n.º 35
0
        /// <summary>
        /// Returns a formatted version of the Abstract Syntax Notation One (ASN.1)-encoded data as a string.
        /// </summary>
        /// <param name="multiLine">
        /// <strong>True</strong> if the return string should contain carriage returns; otherwise, <strong>False</strong>
        /// </param>
        /// <returns>
        /// A formatted string that represents the Abstract Syntax Notation One (ASN.1)-encoded data
        /// </returns>
        /// <remarks>Use this method if you need to print Abstract Syntax Notation One (ASN.1)-encoded data or output the
        /// information to a text box. Use the <strong>multiLine</strong> parameter to control the layout of the output.</remarks>
        public override String Format(Boolean multiLine)
        {
            if (RawData != null && RawData.Length != 0)
            {
                StringBuilder SB  = new StringBuilder();
                Asn1Reader    asn = new Asn1Reader(RawData);
                switch (Oid.Value)
                {
                // Content Type
                case "1.2.840.113549.1.9.3":
                    Oid value = Asn1Utils.DecodeObjectIdentifier(asn.RawData);
                    SB.Append("Content type (OID=1.2.840.113549.1.9.3): ");
                    if (multiLine)
                    {
                        SB.Append(Environment.NewLine + "    " + value.Value);
                    }
                    else
                    {
                        SB.Append(value.Value);
                    }
                    if (!String.IsNullOrEmpty(value.FriendlyName))
                    {
                        SB.Append("(" + value.FriendlyName + ")");
                    }
                    break;

                // Message Digest
                case "1.2.840.113549.1.9.4":
                    SB.Append("Message Digest (OID=1.2.840.113549.1.9.4): ");
                    if (multiLine)
                    {
                        SB.Append(Environment.NewLine + Asn1Utils.DecodeOctetString(asn.RawData));
                    }
                    else
                    {
                        SB.Append(Asn1Utils.DecodeOctetString(asn.RawData));
                    }
                    break;

                // Renewal certificate
                case "1.3.6.1.4.1.311.13.1":
                    X509Certificate2 cert = new X509Certificate2(asn.RawData);
                    SB.Append("Renewal Certificate (OID=1.3.6.1.4.1.311.13.1): ");
                    if (multiLine)
                    {
                        SB.Append(Environment.NewLine + "    " + cert.ToString().Replace("\r\n", "\r\n    "));
                    }
                    else
                    {
                        SB.Append(cert.ToString().Replace("\r\n", " ").Replace("   ", " ").Replace("  ", ", "));
                    }
                    break;

                //  Enrollment Name Value Pair
                case "1.3.6.1.4.1.311.13.2.1":
                    asn.MoveNext();
                    SB.Append("Enrollment Name Value Pair (OID=1.3.6.1.4.1.311.13.2.1): ");
                    if (multiLine)
                    {
                        SB.Append(Environment.NewLine + "    ");
                    }
                    SB.Append(Encoding.BigEndianUnicode.GetString(asn.GetPayload()) + "=");
                    asn.MoveNext();
                    SB.Append(Encoding.BigEndianUnicode.GetString(asn.GetPayload()));
                    if (multiLine)
                    {
                        SB.Append(Environment.NewLine);
                    }
                    break;

                // CSP Info
                case "1.3.6.1.4.1.311.13.2.2":
                    asn.MoveNext();
                    SB.Append("CSP Info (OID=1.3.6.1.4.1.311.13.2.2): ");
                    if (multiLine)
                    {
                        SB.Append(Environment.NewLine + "    ");
                    }
                    if (asn.Tag == (Int32)Asn1Type.INTEGER)
                    {
                        SB.Append("KeySpec: " + asn.GetPayload()[0]);
                        asn.MoveNext();
                    }
                    if (multiLine)
                    {
                        SB.Append(Environment.NewLine + "    ");
                    }
                    else
                    {
                        SB.Append(", ");
                    }
                    if (asn.Tag == (Int32)Asn1Type.BMPString)
                    {
                        SB.Append("Provider: " + Encoding.BigEndianUnicode.GetString(asn.GetPayload()));
                        asn.MoveNext();
                    }
                    if (multiLine)
                    {
                        SB.Append(Environment.NewLine + "    ");
                    }
                    else
                    {
                        SB.Append(", ");
                    }
                    if (asn.Tag == (Int32)Asn1Type.BIT_STRING)
                    {
                        SB.Append("Signature unused bits: " + asn.GetPayload()[0]);
                    }
                    if (multiLine)
                    {
                        SB.Append(Environment.NewLine);
                    }
                    break;

                //OS version
                case "1.3.6.1.4.1.311.13.2.3":
                    SB.Append("OS Version (OID=1.3.6.1.4.1.311.13.2.3): " + Asn1Utils.DecodeIA5String(asn.GetTagRawData()));
                    if (multiLine)
                    {
                        SB.Append(Environment.NewLine);
                    }
                    break;

                // client info
                case "1.3.6.1.4.1.311.21.20":
                    asn.MoveNext();
                    SB.Append("Client Info (OID=1.3.6.1.4.1.311.21.20): ");
                    if (multiLine)
                    {
                        SB.Append(Environment.NewLine + "    ");
                    }
                    if (asn.Tag == (Int32)Asn1Type.INTEGER)
                    {
                        Int64 id = Asn1Utils.DecodeInteger(asn.GetTagRawData());
                        SB.Append("Client ID: " + (ClientIdEnum)id + " (" + id + ")");
                        asn.MoveNext();
                    }
                    if (multiLine)
                    {
                        SB.Append(Environment.NewLine + "    ");
                    }
                    else
                    {
                        SB.Append(", ");
                    }
                    if (asn.Tag == (Int32)Asn1Type.UTF8String)
                    {
                        SB.Append("Computer name: " + Asn1Utils.DecodeUTF8String(asn.GetTagRawData()));
                        if (multiLine)
                        {
                            SB.Append(Environment.NewLine + "    ");
                        }
                        else
                        {
                            SB.Append(", ");
                        }
                        asn.MoveNext();
                        SB.Append("User name: " + Asn1Utils.DecodeUTF8String(asn.GetTagRawData()));
                        if (multiLine)
                        {
                            SB.Append(Environment.NewLine + "    ");
                        }
                        else
                        {
                            SB.Append(", ");
                        }
                        asn.MoveNext();
                        SB.Append("Process name: " + Asn1Utils.DecodeUTF8String(asn.GetTagRawData()));
                        if (multiLine)
                        {
                            SB.Append(Environment.NewLine);
                        }
                    }
                    break;

                // szOID_NT_PRINCIPAL_NAME
                case "1.3.6.1.4.1.311.20.2.3":
                    if (asn.Tag == (Byte)Asn1Type.UTF8String)
                    {
                        SB.Append("User Principal Name (OID=1.3.6.1.4.1.311.20.2.3): " + Asn1Utils.DecodeUTF8String(asn.GetTagRawData()));
                        if (multiLine)
                        {
                            SB.Append(Environment.NewLine);
                        }
                    }
                    break;

                // szOID_NTDS_REPLICATION
                case "1.3.6.1.4.1.311.25.1":
                    if (asn.Tag == (Byte)Asn1Type.OCTET_STRING)
                    {
                        SB.Append("NTDS Replication GUID (OID=1.3.6.1.4.1.311.25.1): " + new Guid(asn.GetPayload()));
                        if (multiLine)
                        {
                            SB.Append(Environment.NewLine);
                        }
                    }
                    break;

                    #region PropIDs
                // CERT_SHA1_HASH_PROP_ID
                case "1.3.6.1.4.1.311.10.11.3":
                    if (asn.Tag == (Byte)Asn1Type.OCTET_STRING)
                    {
                        SB.Append("SHA1 hash (OID=1.3.6.1.4.1.311.10.11.3): " + Asn1Utils.DecodeOctetString(asn.GetTagRawData()));
                        if (multiLine)
                        {
                            SB.Append(Environment.NewLine);
                        }
                    }
                    break;

                // CERT_MD5_HASH_PROP_ID
                case "1.3.6.1.4.1.311.10.11.4":
                    if (asn.Tag == (Byte)Asn1Type.OCTET_STRING)
                    {
                        SB.Append("SHA1 hash (OID=1.3.6.1.4.1.311.10.11.4): " + Asn1Utils.DecodeOctetString(asn.GetTagRawData()));
                        if (multiLine)
                        {
                            SB.Append(Environment.NewLine);
                        }
                    }
                    break;

                // CERT_ENHKEY_USAGE_PROP_ID
                case "1.3.6.1.4.1.311.10.11.9":
                    if (asn.Tag == (Byte)Asn1Type.OCTET_STRING)
                    {
                        asn.MoveNext();
                        asn.MoveNext();
                        SB.Append("Enhanced Key Usages (OID=1.3.6.1.4.1.311.10.11.9): ");
                        if (multiLine)
                        {
                            SB.Append(Environment.NewLine + "    ");
                        }
                        do
                        {
                            if (Asn1Utils.DecodeObjectIdentifier(asn.GetTagRawData()).FriendlyName != null)
                            {
                                SB.Append(Asn1Utils.DecodeObjectIdentifier(asn.GetTagRawData()).Value + " (" + Asn1Utils.DecodeObjectIdentifier(asn.GetTagRawData()).FriendlyName + ") ");
                            }
                            else
                            {
                                SB.Append(Asn1Utils.DecodeObjectIdentifier(asn.GetTagRawData()).Value);
                            }
                            if (multiLine)
                            {
                                SB.Append(Environment.NewLine + "    ");
                            }
                            else
                            {
                                SB.Append(", ");
                            }
                        } while (asn.MoveNext());
                    }
                    break;

                // CERT_FRIENDLY_NAME_PROP_ID
                case "1.3.6.1.4.1.311.10.11.11":
                    if (asn.Tag == (Byte)Asn1Type.OCTET_STRING)
                    {
                        SB.Append("Friendly name (OID=1.3.6.1.4.1.311.10.11.11): " + Encoding.Unicode.GetString(asn.GetPayload()));
                        if (multiLine)
                        {
                            SB.Append(Environment.NewLine);
                        }
                    }
                    break;

                // CERT_KEY_IDENTIFIER_PROP_ID
                case "1.3.6.1.4.1.311.10.11.20":
                    if (asn.Tag == (Byte)Asn1Type.OCTET_STRING)
                    {
                        SB.Append("Subject Key Identifier (OID=1.3.6.1.4.1.311.10.11.20): " + Asn1Utils.DecodeOctetString(asn.GetTagRawData()));
                        if (multiLine)
                        {
                            SB.Append(Environment.NewLine);
                        }
                    }
                    break;

                // CERT_SUBJECT_NAME_MD5_HASH_PROP_ID
                case "1.3.6.1.4.1.311.10.11.29":
                    if (asn.Tag == (Byte)Asn1Type.OCTET_STRING)
                    {
                        SB.Append("Subject name MD5 hash (OID=1.3.6.1.4.1.311.10.11.29): " + Asn1Utils.DecodeOctetString(asn.GetTagRawData()));
                        if (multiLine)
                        {
                            SB.Append(Environment.NewLine);
                        }
                    }
                    break;

                    #endregion
                default:
                    SB.Append("Unknown attribute (OID=" + Oid.Value);
                    if (!String.IsNullOrEmpty(Oid.FriendlyName))
                    {
                        SB.Append(" (" + Oid.FriendlyName + ")");
                    }
                    SB.Append("): ");
                    if (multiLine)
                    {
                        String tempString = AsnFormatter.BinaryToString(RawData, EncodingType.HexAsciiAddress);
                        SB.Append(tempString.Replace("\r\n", "\r\n    ") + Environment.NewLine);
                        SB.Append(Environment.NewLine);
                    }
                    else
                    {
                        SB.Append(AsnFormatter.BinaryToString(RawData) + Environment.NewLine);
                    }
                    break;
                }
                return(SB.ToString());
            }
            return(base.Format(multiLine));
        }
Ejemplo n.º 36
0
 public Pkcs9AttributeObject(System.Security.Cryptography.Oid oid, byte[] encodedData) : this(new AsnEncodedData(oid, encodedData))
 {
 }
Ejemplo n.º 37
0
Archivo: EFSOd.cs Proyecto: steffex/eVR
        public EFSOd(byte[] AID, X509Certificate2 CSCA, CardReader cardReader)
            : base(AID, cardReader, new byte[] { 0x00, 0x1D })
        {
            this.CSCA = CSCA;

            TLV tag = null;

            //// Haal DS certificaat uit EF.SOd data
            //// DS Certificaat bevindt zich in de EF.SOd data onder:
            //// T:'30' (ContentInfo)
            ////      T:'A0' (Content)
            ////          T:'30' (SignedData)
            ////              T:'A0' (Certificates)
            ////                  V: '30 XX XX ... XX'
            ////                      (DS certificaat begint met tag '30')
            tag = this.GetTag("1,30|1,A0|1,30|1,A0");
            if (tag != null)
            {
                DSCertificate = new X509Certificate2(tag.Value);
            }

            ////      i. Haal handtekening en algoritme uit EF.SOd
            ////         De handtekening bevindt zich in de EF.SOd data onder:
            ////         T:'30' (ContentInfo)
            ////              T:'A0' (Content)
            ////                   T:'30' (SignedData)
            ////                        T:'31' (SignerInfos)
            ////                             T:'30' (signerInfo)
            ////                                  T:'04' (Signature)
            Signature = this.GetTag("1,30|1,A0|1,30|2,31|1,30|1,04");

            //// Het signedAttrs veld bevindt zich in de EF.SOd data onder:
            //// T:'30' (ContentInfo)
            ////      T:'A0' (Content)
            ////           T:'30' (SignedData)
            ////                T:'30' (SignerInfo)
            ////                     T:'A0' (signedAttrs)
            SignedAttrs = this.GetTag("1,30|1,A0|1,30|2,31|1,30|1,A0");

            ////         Het gebruikte algoritme is te vinden in de EF.SOd onder:
            ////         T:'30' (ContentInfo)
            ////              T:'A0' (Content)
            ////                   T:'30' (SignedData)
            ////                        T:'31' (SignerInfos)
            ////                             T:'30' (SignerInfo)
            ////                                  T:''30' (SignatureAlgorithm)
            ////                                        T:'06' (algorithm)
            tag = this.GetTag("1,30|1,A0|1,30|2,31|1,30|3,30|1,06");
            if (tag != null)
            {
                SignatureAlgorithm = new System.Security.Cryptography.Oid(EVR.Utils.Oid.Decode(tag.Value));
            }

            ////    Het hash algoritme bevindt zich in EF.SOd onder:
            ////    T:'30' (ContentInfo)
            ////         T:'A0' (Content)
            ////              T:'30' (SignedData)
            ////                   T:'31' (SignerInfos)
            ////                        T:'30' (SignerInfo)
            ////                             T:'30' (digestAlgorithm)
            ////                                  T:'06' (algorithm)
            tag = this.GetTag("1,30|1,A0|1,30|2,31|1,30|2,30|1,06");
            if (tag != null)
            {
                DigestAlgorithm = new System.Security.Cryptography.Oid(EVR.Utils.Oid.Decode(tag.Value));
            }

            //// vi Haal AttributeValue uit signedAttrs
            ////    Binnen signedAttrs bevindt de AttributeValue zich onder:
            ////    T:'30' (Attribute)
            ////         T:'31' (AttrValues)
            ////              T:'04' (AttributeValue)
            AttributeValue = this.GetTag("1,30|1,A0|1,30|2,31|1,30|1,A0|2,30|1,31|1,04");

            //// vii Haal eContent (=RDWidsSecurityObject) uit EF.SOd
            ////     eContent bevindt zich onder:
            ////     T:'30' (ContentInfo)
            ////          T:'A0' (Content)
            ////               T:'30' (SignedData)
            ////                    T:'30' (encapContentInfo)
            ////                         T:'A0' (explicit content)
            ////                              T:'04' (eContent)
            EContent = this.GetTag("1,30|1,A0|1,30|1,30|1,A0|1,04");
        }
 public AsnEncodedData(string oid, byte[] rawData)
 {
     _oid    = new Oid(oid);
     RawData = rawData;
 }
Ejemplo n.º 39
0
 internal AsnEncodedData(Oid oid, CAPI.CRYPTOAPI_BLOB encodedBlob) : this(oid, CAPI.BlobToByteArray(encodedBlob))
 {
 }
Ejemplo n.º 40
0
 /// <summary>Adds an <see cref="T:System.Security.Cryptography.Oid" /> object to the <see cref="T:System.Security.Cryptography.OidCollection" /> object.</summary>
 /// <returns>The index of the added <see cref="T:System.Security.Cryptography.Oid" /> object.</returns>
 /// <param name="oid">The <see cref="T:System.Security.Cryptography.Oid" /> object to add to the collection.</param>
 public int Add(Oid oid)
 {
     return((!this._readOnly) ? this._list.Add(oid) : 0);
 }
Ejemplo n.º 41
0
        /// <summary>
        /// Encode the segments { tag, length, value } of an object identifier (Oid).
        /// </summary>
        /// <returns>The encoded segments { tag, length, value }</returns>
        internal static byte[][] SegmentedEncodeOid(Oid oid)
        {
            Debug.Assert(oid != null);

            // All exceptions past this point should just be "CryptographicException", because that's
            // how they'd come back from Desktop/Windows, since it was a non-success result of calling
            // CryptEncodeObject.
            string oidValue = oid.Value;

            if (string.IsNullOrEmpty(oidValue))
            {
                throw new CryptographicException(SR.Argument_InvalidOidValue);
            }
            if (oidValue.Length < 3 /* "1.1" is the shortest value */)
            {
                throw new CryptographicException(SR.Argument_InvalidOidValue);
            }
            if (oidValue[1] != '.')
            {
                throw new CryptographicException(SR.Argument_InvalidOidValue);
            }

            int firstRid;

            switch (oidValue[0])
            {
            case '0':
                firstRid = 0;
                break;

            case '1':
                firstRid = 1;
                break;

            case '2':
                firstRid = 2;
                break;

            default:
                throw new CryptographicException(SR.Argument_InvalidOidValue);
            }

            int startPos = 2;

            // The first two RIDs are special:
            // ITU X.690 8.19.4:
            //   The numerical value of the first subidentifier is derived from the values of the first two
            //   object identifier components in the object identifier value being encoded, using the formula:
            //       (X*40) + Y
            //   where X is the value of the first object identifier component and Y is the value of the
            //   second object identifier component.
            //       NOTE – This packing of the first two object identifier components recognizes that only
            //          three values are allocated from the root node, and at most 39 subsequent values from
            //          nodes reached by X = 0 and X = 1.

            BigInteger rid = ParseOidRid(oidValue, ref startPos);

            rid += 40 * firstRid;

            // The worst case is "1.1.1.1.1", which takes 4 bytes (5 rids, with the first two condensed)
            // Longer numbers get smaller: "2.1.127" is only 2 bytes. (81d (0x51) and 127 (0x7F))
            // So length / 2 should prevent any reallocations.
            List <byte> encodedBytes = new List <byte>(oidValue.Length / 2);

            EncodeRid(encodedBytes, ref rid);

            while (startPos < oidValue.Length)
            {
                rid = ParseOidRid(oidValue, ref startPos);

                EncodeRid(encodedBytes, ref rid);
            }

            return(new byte[][]
            {
                new byte[] { (byte)DerSequenceReader.DerTag.ObjectIdentifier },
                EncodeLength(encodedBytes.Count),
                encodedBytes.ToArray(),
            });
        }
Ejemplo n.º 42
0
 private void Reset(Oid oid, byte[] rawData)
 {
     this.Oid     = oid;
     this.RawData = rawData;
 }
Ejemplo n.º 43
0
 static WindowUser()
 {
     // This OID is used to find on Client Authentication certificates to present to the user from the certificate store.
     WindowUser.oidClientAuthentication = new Oid("1.3.6.1.5.5.7.3.2", "Client Authentication");
 }
Ejemplo n.º 44
0
        /// <summary>
        /// Questo metodo verifica se l'associazione fra marca e file è valida, verifica inoltre la
        /// validità del certificato firmatario della marca e la data di scadenza della marca; infine
        /// restituisce (se le verifiche vanno a buon fine) tutti i dati contenuti nella marca.
        /// </summary>
        /// <param name="tsRes"></param>
        /// <param name="tsReq"></param>
        /// <returns></returns>
        protected OutputResponseMarca checkMarca(TimeStampResponse tsRes, TimeStampRequest tsReq)
        {
            OutputResponseMarca outTSR = new OutputResponseMarca();

            try
            {
                tsRes.Validate(tsReq);
                outTSR.esito             = "OK";
                outTSR.descrizioneErrore = string.Empty;
            }
            catch (TspException e)
            {
                outTSR.esito             = "KO";
                outTSR.descrizioneErrore = "verifica della marca fallita: " + e.Message;
                logger.Debug("verifica della marca fallita: " + e.Message);
                //return outTSR;
            }

            TimeStampToken tsToken = tsRes.TimeStampToken;

            //Verifica data scadenza marca secondo l'ora locale
            Org.BouncyCastle.X509.Store.IX509Store store = tsToken.GetCertificates("Collection");
            Org.BouncyCastle.X509.X509Certificate  cert  = (Org.BouncyCastle.X509.X509Certificate) new ArrayList(store.GetMatches(tsToken.SignerID))[0];
            //se la data attuale è maggiore di quella di scadenza del certificato che ha firmato la marca
            //allora la marca è scaduta!!!
            if (DateTime.Now.CompareTo(cert.NotAfter.ToLocalTime()) > 0)
            {
                //outTSR.esito = "KO";
                outTSR.descrizioneErrore = "marca temporale scaduta";
                logger.Debug("marca temporale scaduta");
                //return outTSR;
            }

            try
            {
                //estrazione delle informazioni dalla marca
                outTSR.dsm            = cert.NotAfter.ToLocalTime().ToString();
                outTSR.sernum         = tsToken.TimeStampInfo.SerialNumber.ToString();
                outTSR.fhash          = byteArrayToHexa(tsToken.TimeStampInfo.TstInfo.MessageImprint.GetHashedMessage());
                outTSR.docm           = tsToken.TimeStampInfo.TstInfo.GenTime.TimeString;
                outTSR.docm_date      = tsToken.TimeStampInfo.GenTime.ToLocalTime().ToString();
                outTSR.marca          = Convert.ToBase64String(tsRes.GetEncoded());
                outTSR.algCertificato = cert.SigAlgName;
                outTSR.fromDate       = cert.NotBefore.ToLocalTime().ToString();
                outTSR.snCertificato  = cert.SerialNumber.ToString();
                //Algoritmo hash utilizzato per l'impronta
                string algHashOid = tsToken.TimeStampInfo.MessageImprintAlgOid;
                if (!string.IsNullOrEmpty(algHashOid))
                {
                    System.Security.Cryptography.Oid oidHash = new System.Security.Cryptography.Oid(algHashOid);
                    outTSR.algHash = oidHash.FriendlyName;
                }

                outTSR.TSA = new TSARFC2253();

                //Con le TSA di test potrebbe non essere valorizzato l'oggetto TSA
                logger.Debug("Controllo TSA : " + tsToken.TimeStampInfo.Tsa);
                try
                {
                    if (tsToken.TimeStampInfo.Tsa != null)
                    {
                        string oid      = string.Empty;
                        string oidValue = string.Empty;
                        logger.Debug("TagNo: " + tsToken.TimeStampInfo.Tsa.TagNo);
                        for (int n = 0; n < tsToken.TimeStampInfo.Tsa.TagNo; n++)
                        {
                            logger.Debug("Tag: " + n);
                            Org.BouncyCastle.Asn1.Asn1Sequence seq = (Org.BouncyCastle.Asn1.Asn1Sequence)tsToken.TimeStampInfo.Tsa.Name.ToAsn1Object();

                            //Obsoleto
                            //Org.BouncyCastle.Asn1.Asn1Object obj = (Org.BouncyCastle.Asn1.Asn1Object)seq.GetObjectAt(n);
                            Org.BouncyCastle.Asn1.Asn1Object obj = (Org.BouncyCastle.Asn1.Asn1Object)seq[n];

                            Org.BouncyCastle.Asn1.Asn1Set set1 = (Org.BouncyCastle.Asn1.Asn1Set)obj.ToAsn1Object();

                            //Obsoleto
                            //seq = (Org.BouncyCastle.Asn1.Asn1Sequence)set1.GetObjectAt(0);
                            //obj = (Org.BouncyCastle.Asn1.Asn1Object)seq.GetObjectAt(0);
                            seq = (Org.BouncyCastle.Asn1.Asn1Sequence)set1[0];
                            obj = (Org.BouncyCastle.Asn1.Asn1Object)seq[0];


                            oid = obj.ToString();

                            //Obsoleto
                            //obj = (Org.BouncyCastle.Asn1.Asn1Object)seq.GetObjectAt(1);
                            obj = (Org.BouncyCastle.Asn1.Asn1Object)seq[1];

                            oidValue = obj.ToString();
                            System.Security.Cryptography.Oid oid_obj = new System.Security.Cryptography.Oid(oid);
                            string friendly = oid_obj.FriendlyName;
                            logger.Debug("oid: " + oid + " friendly: " + friendly);
                            switch (friendly)
                            {
                            case "CN":
                                outTSR.TSA.CN = oidValue;
                                break;

                            case "OU":
                                outTSR.TSA.OU = oidValue;
                                break;

                            case "O":
                                outTSR.TSA.O = oidValue;
                                break;

                            case "C":
                                outTSR.TSA.C = oidValue;
                                break;
                            }
                        }
                        outTSR.TSA.TSARFC2253Name = "CN=" + outTSR.TSA.CN + ",OU=" + outTSR.TSA.OU + ",O=" + outTSR.TSA.O + ",C=" + outTSR.TSA.C;
                    }
                }
                catch (Exception e)
                {
                    logger.Debug("Eccezione controllo TSA : " + e.Message);
                }
                logger.Debug("Fine Controllo TSA");
            }
            catch (Exception eTsp)
            {
                outTSR.esito             = "KO";
                outTSR.descrizioneErrore = "estrazione delle informazioni dalla marca fallita: " + eTsp.Message;
                logger.Debug("estrazione delle informazioni dalla marca fallita: " + eTsp.Message);
                //return outTSR;
            }

            //verifico l'esistenza del documento al quale è associata la marca temporale
            //Commentata perchè l'impronta del documento è ancora calcolata con SHA1 invece che SHA256
            //DocsPaDB.Query_DocsPAWS.Documenti documento = new DocsPaDB.Query_DocsPAWS.Documenti();
            //outTSR.timestampedDoc = documento.GetDocNumberByImpronta(outTSR.fhash);
            //if (string.IsNullOrEmpty(outTSR.timestampedDoc))
            //{
            //    outTSR.timestampedDoc = "Non esiste alcun documento associato alla marca temporale.";
            //}

            //costruisco l'oggetto rappresentante il contenuto in chiaro della marca
            outTSR.DecryptedTSR             = new Marca();
            outTSR.DecryptedTSR.content     = contentMarca(outTSR);
            outTSR.DecryptedTSR.contentType = "text/html"; //"application/x-html";
            outTSR.DecryptedTSR.length      = outTSR.DecryptedTSR.content.Length;

            return(outTSR);
        }
Ejemplo n.º 45
0
        // methods

        public int Add(Oid oid)
        {
            return(_readOnly ? 0 : _list.Add(oid));
        }
Ejemplo n.º 46
0
 public AsnEncodedData(Oid oid, byte[] rawData)
 {
     Reset(oid, rawData);
 }
Ejemplo n.º 47
0
 /// <summary>
 /// Initializes a new instance of the <strong>X509Attribute</strong> class using an Oid object and a byte array
 /// </summary>
 /// <param name="oid">An Oid object that identifies attribute.</param>
 /// <param name="rawData">A byte array that contains Abstract Syntax Notation One (ASN.1)-encoded data.</param>
 public X509Attribute(Oid oid, Byte[] rawData) : base(oid, rawData)
 {
 }
Ejemplo n.º 48
0
 public AsnEncodedDataCollection()
 {
     m_list = new ArrayList();
     m_oid  = null;
 }
Ejemplo n.º 49
0
 internal PublicKey(PublicKey publicKey)
 {
     this.m_oid = new System.Security.Cryptography.Oid(publicKey.m_oid);
     this.m_encodedParameters = new AsnEncodedData(publicKey.m_encodedParameters);
     this.m_encodedKeyValue   = new AsnEncodedData(publicKey.m_encodedKeyValue);
 }
Ejemplo n.º 50
0
 /// <summary>
 /// Create a curve from the given cref="Oid".
 /// </summary>
 /// <param name="curveOid">The Oid to use.</param>
 /// <returns>An ECCurve representing a named curve.</returns>
 public static ECCurve CreateFromOid(Oid curveOid)
 {
     // Make a copy since Oid is mutable
     return(Create(new Oid(curveOid.Value, curveOid.FriendlyName)));
 }
Ejemplo n.º 51
0
 /// <summary>
 ///		Initializes a new instance of the <strong>X509Attribute</strong> class using an Oid object, an integer that
 ///		identifies the tagged attribute and a byte array. This constructor is used only for tagged attributes.
 /// </summary>
 /// <param name="oid">An Oid object that identifies attribute.</param>
 /// <param name="partId">An integer that identifies attribute.</param>
 /// <param name="rawData">A byte array that contains Abstract Syntax Notation One (ASN.1)-encoded data.</param>
 public X509Attribute(Oid oid, Int32 partId, Byte[] rawData) : base(oid, rawData)
 {
     BodyPartId = partId;
 }
Ejemplo n.º 52
0
 public int Add(Oid oid)
 {
     return(default(int));
 }
Ejemplo n.º 53
0
 internal AsnEncodedData(Oid oid)
 {
     m_oid = oid;
 }