Exemple #1
0
        private void Dump(SaveType dumpType)
        {
            SaveFileDialog fileDialog = new SaveFileDialog();

            if (DialogResult.OK == fileDialog.ShowDialog())
            {
                switch (dumpType)
                {
                case SaveType.Node:
                    Asn1.Encode(fileDialog.FileName, this.Asn1Node);
                    break;

                case SaveType.Data:
                    Asn1.EncodeData(fileDialog.FileName, this.Asn1Node);
                    break;

                case SaveType.Text:
                    Asn1.ExportText(fileDialog.FileName, this.Asn1Node);
                    break;

                default:
                    break;
                }
            }
        }
Exemple #2
0
        public void Should_serialize_integer_from_bytes()
        {
            // Arrange
            var byteArrays = new byte[][]
            {
                new byte[] { 0 },
                new byte[] { 127 },
                new byte[] { 0, 127 },
                new byte[] { 128 },
                new byte[] { 1, 0, 0 },
                new byte[0],
                new byte[] { 0, 165, 163, 214, 2, 169, 62 }
            }.Select(data => new DerInteger(data));

            var expectedSerializedValues = new[]
            {
                new byte[] { 2, 1, 0 },
                new byte[] { 2, 1, 127 },
                new byte[] { 2, 2, 0, 127 },
                new byte[] { 2, 2, 0, 128 }, // da das 1. Bit zur Vorzeichenerkennung genutzt wird, wird bei >= 128 ein 0-Byte voran gestellt
                new byte[] { 2, 3, 1, 0, 0 },
                new byte[] { 2, 0 },
                new byte[] { 2, 7, 0, 165, 163, 214, 2, 169, 62 }
            };

            // Act
            var result = byteArrays.Select(i => Asn1.Encode(i)).ToArray();

            // Assert
            result.Length.Should().Be(expectedSerializedValues.Length);
            for (int i = 0; i < expectedSerializedValues.Length; i++)
            {
                result[i].Should().Equal(expectedSerializedValues[i]);
            }
        }
        public void Asn1_ParseItem_reads_packed_size()
        {
            const int size = 127;
            var       item = Asn1.ParseItem(("027F" + "AB".Repeat(size)).DecodeHex());

            Assert.Equal(size, item.Value.Length);
        }
        public void Asn1_ParseItem_reads_single_byte_size()
        {
            const int size = 128;
            var       item = Asn1.ParseItem(("028180" + "AB".Repeat(size)).DecodeHex());

            Assert.Equal(size, item.Value.Length);
        }
Exemple #5
0
        private void UpdateHexViewerData()
        {
            byte[] data;

            if (rootNode != null)
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    Asn1.Encode(ms, rootNode);
                    data = ms.ToArray();
                }
            }
            else
            {
                data = new byte[0];
            }
            hexViewer.View(data);

            Asn1TreeNode selectedNode = treeView1.SelectedNode as Asn1TreeNode;

            if (selectedNode != null)
            {
                // TODO: length is incorrect for indefinite length nodes
                hexViewer.Highlight((int)selectedNode.Asn1Node.StartByte, (int)(Asn1.GetTotalByteCount(selectedNode.Asn1Node)));
            }
        }
        private static void ParseDeadBeefItem(byte tag, Asn1.Kind kind)
        {
            var item = Asn1.ParseItem($"{tag:X2}04DEADBEEF".DecodeHex());

            Assert.Equal(kind, item.Key);
            Assert.Equal(new byte[] { 0xDE, 0xAD, 0xBE, 0xEF }, item.Value);
        }
        /**
         * create with a signer with extra signed/unsigned attributes.
         */
        public TimeStampTokenGenerator(
			AsymmetricKeyParameter	key,
			X509Certificate			cert,
			string					digestOID,
			string					tsaPolicyOID,
			Asn1.Cms.AttributeTable	signedAttr,
			Asn1.Cms.AttributeTable	unsignedAttr)
        {
            this.key = key;
            this.cert = cert;
            this.digestOID = digestOID;
            this.tsaPolicyOID = tsaPolicyOID;
            this.unsignedAttr = unsignedAttr;

            TspUtil.ValidateCertificate(cert);

            //
            // add the essCertid
            //
            Hashtable signedAttrs;
            if (signedAttr != null)
            {
                signedAttrs = signedAttr.ToHashtable();
            }
            else
            {
                signedAttrs = new Hashtable();
            }

            IDigest digest;
            try
            {
                digest = DigestUtilities.GetDigest("SHA-1");
            }
            catch (Exception e)
            {
                throw new TspException("Can't find a SHA-1 implementation.", e);
            }

            try
            {
                byte[] certEncoded = cert.GetEncoded();
                digest.BlockUpdate(certEncoded, 0, certEncoded.Length);
                byte[] hash = DigestUtilities.DoFinal(digest);

                EssCertID essCertid = new EssCertID(hash);

                Asn1.Cms.Attribute attr = new Asn1.Cms.Attribute(
                    PkcsObjectIdentifiers.IdAASigningCertificate,
                    new DerSet(new SigningCertificate(essCertid)));

                signedAttrs[attr.AttrType] = attr;
            }
            catch (CertificateEncodingException e)
            {
                throw new TspException("Exception processing certificate.", e);
            }

            this.signedAttr = new Asn1.Cms.AttributeTable(signedAttrs);
        }
        private static void ParseDeadBeefItem(byte tag, Asn1.Kind kind)
        {
            var item = Asn1.ParseItem(string.Format("{0:X2}04DEADBEEF", tag).DecodeHex());

            Assert.AreEqual(kind, item.Key);
            Assert.AreEqual(new byte[] { 0xDE, 0xAD, 0xBE, 0xEF }, item.Value);
        }
        public void Asn1_ParseItem_reads_multi_byte_size()
        {
            const int size = 260;
            var       item = Asn1.ParseItem(("02820104" + "AB".Repeat(size)).DecodeHex());

            Assert.Equal(size, item.Value.Length);
        }
Exemple #10
0
 private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
 {
     if (hexViewer.Visible)
     {
         Asn1Tag node = (e.Node as Asn1TreeNode).Asn1Node;
         hexViewer.Highlight((int)node.StartByte, (int)Asn1.GetTotalByteCount(node));
     }
 }
Exemple #11
0
        public void Should_serialize_a_sequence()
        {
            // Arrange
            var sequence = new Sequence(new ObjectIdentifier(new Oid("2.5.4.8")), new UTF8String("NRW"));

            var bytes = Asn1.Encode(sequence);

            // Assert
            bytes.Should().Equal(0x30, 0x0A, 0x06, 0x03, 0x55, 0x04, 0x08, 0x0C, 0x03, 0x4E, 0x52, 0x57);
        }
Exemple #12
0
        public void Should_serialize_integer_from_int()
        {
            var ints     = new int[] { 0, 127, 128, 256 * 256 };
            var asn1ints = ints.Select(i => new DerInteger(i));

            var bytes = asn1ints.Select(i => Asn1.Encode(i)).ToArray();

            bytes[0].Should().Equal(0x02, 1, 0);
            bytes[1].Should().Equal(0x02, 1, 127);
            bytes[2].Should().Equal(0x02, 2, 0, 128); // da das 1. Bit zur Vorzeichenerkennung genutzt wird, wird bei >= 128 ein 0-Byte voran gestellt
            bytes[3].Should().Equal(0x02, 3, 1, 0, 0);
        }
		/**
		 * create with a signer with extra signed/unsigned attributes.
		 */
		public TimeStampTokenGenerator(
			AsymmetricKeyParameter	key,
			X509Certificate			cert,
			string					digestOID,
			string					tsaPolicyOID,
			Asn1.Cms.AttributeTable	signedAttr,
			Asn1.Cms.AttributeTable	unsignedAttr)
		{
			this.key = key;
			this.cert = cert;
			this.digestOID = digestOID;
			this.tsaPolicyOID = tsaPolicyOID;
			this.unsignedAttr = unsignedAttr;

			TspUtil.ValidateCertificate(cert);

			//
			// Add the ESSCertID attribute
			//
			IDictionary signedAttrs;
			if (signedAttr != null)
			{
				signedAttrs = signedAttr.ToDictionary();
			}
			else
			{
				signedAttrs = Platform.CreateHashtable();
			}

			try
			{
				byte[] hash = DigestUtilities.CalculateDigest("SHA-1", cert.GetEncoded());

				EssCertID essCertid = new EssCertID(hash);

				Asn1.Cms.Attribute attr = new Asn1.Cms.Attribute(
					PkcsObjectIdentifiers.IdAASigningCertificate,
					new DerSet(new SigningCertificate(essCertid)));

				signedAttrs[attr.AttrType] = attr;
			}
			catch (CertificateEncodingException e)
			{
				throw new TspException("Exception processing certificate.", e);
			}
			catch (SecurityUtilityException e)
			{
				throw new TspException("Can't find a SHA-1 implementation.", e);
			}

			this.signedAttr = new Asn1.Cms.AttributeTable(signedAttrs);
		}
        /**
        * add a signer with extra signed/unsigned attributes.
        */
        public void AddSigner(
            AsymmetricKeyParameter	privateKey,
            X509Certificate			cert,
            string					digestOID,
            Asn1.Cms.AttributeTable	signedAttr,
            Asn1.Cms.AttributeTable	unsignedAttr)
        {
            string encOID = GetEncOid(privateKey, digestOID);

            signerInfs.Add(new SignerInf(this, privateKey, cert, digestOID, encOID,
                new DefaultSignedAttributeTableGenerator(signedAttr),
                new SimpleAttributeTableGenerator(unsignedAttr),
                signedAttr));
        }
 internal SignerInf(
     CmsSignedGenerator outer,
     ISignatureFactory sigCalc,
     SignerIdentifier signerIdentifier,
     CmsAttributeTableGenerator sAttr,
     CmsAttributeTableGenerator unsAttr,
     Asn1.Cms.AttributeTable baseSignedTable)
 {
     this.outer = outer;
     this.sigCalc = sigCalc;
     this.signerIdentifier = signerIdentifier;
     this.digestOID = new DefaultDigestAlgorithmIdentifierFinder().find((AlgorithmIdentifier)sigCalc.AlgorithmDetails).Algorithm.Id;
     this.encOID = ((AlgorithmIdentifier)sigCalc.AlgorithmDetails).Algorithm.Id;
     this.sAttr = sAttr;
     this.unsAttr = unsAttr;
     this.baseSignedTable = baseSignedTable;
 }
			internal SignerInf(
                CmsSignedGenerator			outer,
	            AsymmetricKeyParameter		key,
	            SignerIdentifier			signerIdentifier,
	            string						digestOID,
	            string						encOID,
	            CmsAttributeTableGenerator	sAttr,
	            CmsAttributeTableGenerator	unsAttr,
	            Asn1.Cms.AttributeTable		baseSignedTable)
	        {
                this.outer = outer;
                this.key = key;
                this.signerIdentifier = signerIdentifier;
                this.digestOID = digestOID;
                this.encOID = encOID;
	            this.sAttr = sAttr;
	            this.unsAttr = unsAttr;
	            this.baseSignedTable = baseSignedTable;
            }
Exemple #17
0
        public void OpenFile(string file)
        {
            SuspendLayout();

            try
            {
                using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
                {
                    try
                    {
                        byte[] pemData = PemReader.ReadPem(fs);

                        using (MemoryStream ms = new MemoryStream(pemData))
                        {
                            rootNode = Asn1.Decode(ms);
                        }
                    }
                    catch (ArgumentException)
                    {
                        fs.Position = 0;
                        rootNode = Asn1.Decode(fs);
                    }

                    stsFile.Text = string.Concat("File: ", file);
                    stsSize.Text = string.Concat("Size: ", fs.Length.ToString(), " bytes");
                    Text = string.Concat(TitleBase, " - ", file);
                }

                ShowAsn1(rootNode);
                UpdateHexViewerData();
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "Error while opening file: " + ex.Message, "Error opening file", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
            }

            ResumeLayout();
        }
			internal SignerInf(
                CmsSignedGenerator			outer,
	            AsymmetricKeyParameter		key,
	            SignerIdentifier			signerIdentifier,
	            string						digestOID,
	            string						encOID,
	            CmsAttributeTableGenerator	sAttr,
	            CmsAttributeTableGenerator	unsAttr,
	            Asn1.Cms.AttributeTable		baseSignedTable)
	        {
                string digestName = Helper.GetDigestAlgName(digestOID);

                string signatureName = digestName + "with" + Helper.GetEncryptionAlgName(encOID);

                this.outer = outer;
                this.sigCalc = new Asn1SignatureFactory(signatureName, key);
                this.signerIdentifier = signerIdentifier;
                this.digestOID = digestOID;
                this.encOID = encOID;
	            this.sAttr = sAttr;
	            this.unsAttr = unsAttr;
	            this.baseSignedTable = baseSignedTable;
            }
Exemple #19
0
        public static RSAParameters DecodeRsaParameters(string pkcs8PrivateKey)
        {
            const string PrivateKeyPrefix = "-----BEGIN PRIVATE KEY-----";
            const string PrivateKeySuffix = "-----END PRIVATE KEY-----";

            Utilities.ThrowIfNullOrEmpty(pkcs8PrivateKey, nameof(pkcs8PrivateKey));
            pkcs8PrivateKey = pkcs8PrivateKey.Trim();
            if (!pkcs8PrivateKey.StartsWith(PrivateKeyPrefix) || !pkcs8PrivateKey.EndsWith(PrivateKeySuffix))
            {
                throw new ArgumentException(
                          $"PKCS8 data must be contained within '{PrivateKeyPrefix}' and '{PrivateKeySuffix}'.", nameof(pkcs8PrivateKey));
            }
            string base64PrivateKey =
                pkcs8PrivateKey.Substring(PrivateKeyPrefix.Length, pkcs8PrivateKey.Length - PrivateKeyPrefix.Length - PrivateKeySuffix.Length);

            // FromBase64String() ignores whitespace, so further Trim()ing isn't required.
            byte[] pkcs8Bytes = Convert.FromBase64String(base64PrivateKey);

            object ans1 = Asn1.Decode(pkcs8Bytes);

            object[] parameters = (object[])((object[])ans1)[2];

            var rsaParmeters = new RSAParameters
            {
                Modulus  = TrimLeadingZeroes((byte[])parameters[1]),
                Exponent = TrimLeadingZeroes((byte[])parameters[2], alignTo8Bytes: false),
                D        = TrimLeadingZeroes((byte[])parameters[3]),
                P        = TrimLeadingZeroes((byte[])parameters[4]),
                Q        = TrimLeadingZeroes((byte[])parameters[5]),
                DP       = TrimLeadingZeroes((byte[])parameters[6]),
                DQ       = TrimLeadingZeroes((byte[])parameters[7]),
                InverseQ = TrimLeadingZeroes((byte[])parameters[8]),
            };

            return(rsaParmeters);
        }
Exemple #20
0
        /// <summary>
        /// Enabling encryption
        /// </summary>
        /// <param name="packet">EncryptionRequestPacket</param>
        private void ModernEnableEncryption(IPacket packet)
        {
            var request = (EncryptionRequestPacket)packet;

            var hash = Asn1.GetServerIDHash(request.PublicKey, request.SharedKey, request.ServerId);

            if (!Yggdrasil.ClientAuth(_minecraft.AccessToken, _minecraft.SelectedProfile, hash))
            {
                throw new Exception("Yggdrasil error: Not authenticated.");
            }

            var rsaParameter = Asn1.GetRsaParameters(request.PublicKey);

            var encryptedSecret = Asn1.EncryptData(rsaParameter, request.SharedKey);
            var encryptedVerify = Asn1.EncryptData(rsaParameter, request.VerificationToken);

            BeginSendPacket(new EncryptionResponsePacket
            {
                SharedSecret      = encryptedSecret,
                VerificationToken = encryptedVerify
            }, null, null);

            _stream.InitializeEncryption(request.SharedKey);
        }
        /**
        * add a signer with extra signed/unsigned attributes.
        * @throws NoSuchAlgorithmException
        * @throws InvalidKeyException
        */
        public void AddSigner(
            AsymmetricKeyParameter	privateKey,
            X509Certificate			cert,
            string					digestOid,
            Asn1.Cms.AttributeTable	signedAttr,
            Asn1.Cms.AttributeTable	unsignedAttr)
        {
			AddSigner(privateKey, cert, digestOid,
				new DefaultSignedAttributeTableGenerator(signedAttr),
				new SimpleAttributeTableGenerator(unsignedAttr));
		}
		/**
		* add a signer with extra signed/unsigned attributes.
		* @throws NoSuchAlgorithmException
		* @throws InvalidKeyException
		*/
		public void AddSigner(
			AsymmetricKeyParameter	privateKey,
			byte[]					subjectKeyID,
			string					digestOid,
			Asn1.Cms.AttributeTable	signedAttr,
			Asn1.Cms.AttributeTable	unsignedAttr)
	    {
	        AddSigner(privateKey, subjectKeyID, digestOid,
				new DefaultSignedAttributeTableGenerator(signedAttr),
				new SimpleAttributeTableGenerator(unsignedAttr));
		}
 internal SignerInf(CmsSignedGenerator outer, AsymmetricKeyParameter key, SignerIdentifier signerIdentifier, string digestOID, string encOID,
     CmsAttributeTableGenerator sAttr, CmsAttributeTableGenerator unsAttr, Asn1.Cms.AttributeTable baseSignedTable)
 {
     _outer = outer;
     _key = key;
     _signerIdentifier = signerIdentifier;
     _digestOID = digestOID;
     _encOID = encOID;
     _sAttr = sAttr;
     _unsAttr = unsAttr;
     _baseSignedTable = baseSignedTable;
 }
        public void Should_serialize_a_certificate_signing_request()
        {
            /*
             * var keyManager = new FileKeyStore(Environment.CurrentDirectory);
             * var rsa = keyManager.GetOrCreateKey("test.startliste.info");
             * var key = rsa.ExportParameters(true);
             */

            var key = RSAPrivateKey.ParsePem(@"
-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEAq57sJKTDY5K3w9Gf40xDhpHwyOshO2EXEg4doP4tX6+eAHUP
h04Kb3/X2jfgdQHGjTYMyv9Q0AZ5msMOUjxnxbt1GvhVih/yaDOqjysWbBXbRWFZ
5eBk6PHbYmPTVcfE9RyyNS8bp9ykZgJoU0Q1V2UxjQX5JkMJLnFxegKkw/fSZizj
IlUSjnDCP13Gs/cmualyqxlZipsSzaAuasoeIT/qanick3UL+tATIJJ8Zytacntj
Gca9ZMs6xtmvSkumEd2d6pBsIItEwRIG0+9MFb7q7yTySiewFs/+5duEpIL+K83k
IX0nB+15TsjZFnJ+6rLY+YRifjc8vVZHeFD8iwIDAQABAoIBAERetQuqGe7mqc/Y
iH5YSQRoyoh4Z45M0RCP0Azthaz7fRIIkI2iMPUXdKoKHaDveqaR9EnAqfSdx784
WtG3H849rlr2uLkkngEWKCoOC8o2cNq0fEhge0Lz6ybIxw4C3juZ2YLnh/h5JYNA
DUiywR9WgIWCbi3ogdVfO0pUmEg7IG6Q0KLPicabLwcrBKDAloBdS/q7aeFrSEIG
0Hu+CJCKPterdYbFmJ5zHFmOYvToIkX5AYT+G1EfaGx4FHly0wC1eSZIaU/krNd/
U9vdMA2gd8alcG/GwOih5RunIJoGad20hh6gLsw8KHX0s2GDlRvk2Q71cH2YEdo4
SXe7Tw0CgYEA3epZNvO/gZj/YM5ljcn6Hxf2/RscqreH2K4GM0yTp6OEOvm6Dg4t
9JOA+6YxT3Dbf8aEcWDleDcJJY4EfkL4Lqq2dn4vbF+AevVAH1Ml6/ZJwvFuqcMk
9g8FJQqO/Ul/MrFHhi4oXzg3dZPeMKZTN2ACZHiKTwzC0GtCzXdRGVUCgYEAxfsA
1CCUpgsjKvhBxLvpVqIEi5gzMarO7UvgVprvZ/0NFGkgrQC5c3Hhs5mrsf8pB1Gf
EJvTaFGGgr9o2+JzVXs9PJ1njEoelS35PUrHZ8raW2TWJQVAToCfzbylPTY0sJEl
iX++fJJa7AjgYPcriOiZbtBTZHBiqpdAKsC+Pl8CgYEAh25J3BuNuE3jLPVJTOsC
1o8NkRJGwHkZUseByTTmt9w3Crb1MTa+HREYGnwmg9DgZG6GzZrQ8DjGQEEXxOai
B/jvOglwb7co9eFOrM9VyVeZVHt7iecqW3B3N0/mS/XaxtkiSWVKBjKMxhjj9NTM
3HKfgyl9Xxjum7uaHULAH7ECgYATPwJmnMA2oBCMJdQm7umRHXD5rRMU+fjhwqWN
ZcRuRIBYApxFlTNyEJkTX5X8WMTBTGL9N1jG5F4CKd9kuM/jeHaMhPTDA5WThQOc
vL9DzMmLZvMWaDtHJmPimTsrBzD6FTIj+sIm1Ad4uKgvZPfbeFkqF6BzvCUrVkbL
oS8dWwKBgGevHLbGPIeNjrAN3YK3T0VaeB60aigK1PRb+qHL4TDngK2wG6Xy6XVd
iQoWlyFgiNQ/qJcD8dcVwT83KvogfIGb/PLZ9LLRkt4g4ZEKj76gaQIr/U/DVB2I
yXgq378FifWsRemLckRjOC+T0brxqxzqPflbe+c2AHZgMSjuRplC
-----END RSA PRIVATE KEY-----").Key;

            var data = new CertificateRequestData("test.startliste.info", key)
            {
                C  = "DE",
                S  = "NRW",
                L  = "Werther",
                O  = "Aero Club Bünde",
                OU = ""
            };

            var csr    = Pkcs10.Encode(data);
            var der    = Pkcs10.EncodeAsDer(data);
            var base64 = Pkcs10.EncodeAsBase64(data);
            var bytes  = Asn1.Encode(csr);

            Assert.Equal(
                @"-----BEGIN NEW CERTIFICATE REQUEST-----
MIICZDCCAUwCAQAwHzEdMBsGA1UEAwwUdGVzdC5zdGFydGxpc3RlLmluZm8wggEi
MA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCrnuwkpMNjkrfD0Z/jTEOGkfDI
6yE7YRcSDh2g/i1fr54AdQ+HTgpvf9faN+B1AcaNNgzK/1DQBnmaww5SPGfFu3Ua
+FWKH/JoM6qPKxZsFdtFYVnl4GTo8dtiY9NVx8T1HLI1Lxun3KRmAmhTRDVXZTGN
BfkmQwkucXF6AqTD99JmLOMiVRKOcMI/Xcaz9ya5qXKrGVmKmxLNoC5qyh4hP+pq
eJyTdQv60BMgknxnK1pye2MZxr1kyzrG2a9KS6YR3Z3qkGwgi0TBEgbT70wVvurv
JPJKJ7AWz/7l24Skgv4rzeQhfScH7XlOyNkWcn7qstj5hGJ+Nzy9Vkd4UPyLAgMB
AAGgADANBgkqhkiG9w0BAQsFAAOCAQEALuD1Xha1+qUH1eiXlMO6xiFUtKPMnwR1
XgYf7OILUnFvG4gdE80clIKR8smLOg59nURhIzHhPRacT5jRmcbl4zruZhL8yCuV
JOacbdoV69iElZ4BODJwHmJPGajcAw89bUFLezPwRflDlVuiw8/ldAQWsyWtnKVI
n9IgTWDEDboUIrUgv+sRwEue+fOCEtVOj1X4Yi0jOCsnihzn0pQNvvU/w9Vpe5Jr
Gm1FyD6z3pdGktxJKW3ns+xYcova+2nQeSbuVFHA/OTmIckrDa87EUJNbNVWLtwo
FXTQmRtze3w5yKOadkSEyr6FG3qq+3IukRgiuxK12SsN7dE0sIO7ow==
-----END NEW CERTIFICATE REQUEST-----".Replace("\r\n", "\n"), base64);

            File.WriteAllBytes(@"request.der", der);
            File.WriteAllText(@"request.txt", base64);

            // openssl req -in r:\request.txt -noout -text
        }
        /**
         * add a signer, specifying the digest encryption algorithm, with extra signed/unsigned attributes.
         *
         * @param key signing key to use
         * @param cert certificate containing corresponding public key
         * @param encryptionOID digest encryption algorithm OID
         * @param digestOID digest algorithm OID
         * @param signedAttr table of attributes to be included in signature
         * @param unsignedAttr table of attributes to be included as unsigned
         */
        public void AddSigner(
            IAsymmetricKeyParameter privateKey,
			X509Certificate			cert,
			string					encryptionOID,
			string					digestOID,
			Asn1.Cms.AttributeTable	signedAttr,
			Asn1.Cms.AttributeTable	unsignedAttr)
        {
            doAddSigner(privateKey, GetSignerIdentifier(cert), encryptionOID, digestOID,
                new DefaultSignedAttributeTableGenerator(signedAttr),
                new SimpleAttributeTableGenerator(unsignedAttr),
                signedAttr);
        }
Exemple #26
0
        public Asn1TreeNode(Asn1Tag asn1Node)
        {
            this.Asn1Node = asn1Node;

            // Use data length instead of full byte count
            this.Text = string.Concat("(", asn1Node.StartByte, ", ", (asn1Node.IndefiniteLength ? "inf" : Asn1.GetTotalByteCount(asn1Node).ToString()), ") ", asn1Node.ShortDescription);
            if (!asn1Node.Constructed)
            {
                this.Text += string.Concat(": ", asn1Node.DataText);
            }
            if (asn1Node.Class == Asn1.Class.Universal && asn1Node.Identifier <= 31)
            {
                this.ImageIndex = Asn1ImageIndexes[asn1Node.Identifier];
            }
            else
            {
                this.ImageIndex = 32;
            }
            this.SelectedImageIndex = this.ImageIndex;

            this.ContextMenu = CreateContextMenu();
        }
	    /**
	     * add a signer with extra signed/unsigned attributes.
		 *
		 * @param key signing key to use
		 * @param subjectKeyID subjectKeyID of corresponding public key
		 * @param digestOID digest algorithm OID
		 * @param signedAttr table of attributes to be included in signature
		 * @param unsignedAttr table of attributes to be included as unsigned
	     */
		public void AddSigner(
			AsymmetricKeyParameter	privateKey,
			byte[]					subjectKeyID,
			string					digestOID,
			Asn1.Cms.AttributeTable	signedAttr,
			Asn1.Cms.AttributeTable	unsignedAttr)
		{
			AddSigner(privateKey, subjectKeyID, GetEncOid(privateKey, digestOID), digestOID,
				signedAttr, unsignedAttr); 
		}
		private void doAddSigner(
			AsymmetricKeyParameter		privateKey,
			SignerIdentifier            signerIdentifier,
			string                      encryptionOID,
			string                      digestOID,
			CmsAttributeTableGenerator  signedAttrGen,
			CmsAttributeTableGenerator  unsignedAttrGen,
			Asn1.Cms.AttributeTable		baseSignedTable)
		{
			signerInfs.Add(new SignerInf(this, privateKey, signerIdentifier, digestOID, encryptionOID,
				signedAttrGen, unsignedAttrGen, baseSignedTable));
		}
		internal protected virtual Asn1Set GetAttributeSet(
            Asn1.Cms.AttributeTable attr)
        {
			return attr == null
				?	null
				:	new DerSet(attr.ToAsn1EncodableVector());
        }
Exemple #30
0
		public TimeStampToken(
			Asn1.Cms.ContentInfo contentInfo)
			: this(new CmsSignedData(contentInfo))
		{
		}
		private bool DoVerify(
			AsymmetricKeyParameter	key,
			Asn1.Cms.AttributeTable	signedAttrTable)
		{
			string digestName = Helper.GetDigestAlgName(this.DigestAlgOid);
			IDigest digest = Helper.GetDigestInstance(digestName);

			DerObjectIdentifier sigAlgOid = this.encryptionAlgorithm.ObjectID;
			Asn1Encodable sigParams = this.encryptionAlgorithm.Parameters;
			ISigner sig;

			if (sigAlgOid.Equals(Asn1.Pkcs.PkcsObjectIdentifiers.IdRsassaPss))
			{
				// RFC 4056 2.2
				// When the id-RSASSA-PSS algorithm identifier is used for a signature,
				// the AlgorithmIdentifier parameters field MUST contain RSASSA-PSS-params.
				if (sigParams == null)
					throw new CmsException("RSASSA-PSS signature must specify algorithm parameters");

				try
				{
					// TODO Provide abstract configuration mechanism

					Asn1.Pkcs.RsassaPssParameters pss = Asn1.Pkcs.RsassaPssParameters.GetInstance(
						sigParams.ToAsn1Object());

					if (!pss.HashAlgorithm.ObjectID.Equals(this.digestAlgorithm.ObjectID))
						throw new CmsException("RSASSA-PSS signature parameters specified incorrect hash algorithm");
					if (!pss.MaskGenAlgorithm.ObjectID.Equals(Asn1.Pkcs.PkcsObjectIdentifiers.IdMgf1))
						throw new CmsException("RSASSA-PSS signature parameters specified unknown MGF");

					IDigest pssDigest = DigestUtilities.GetDigest(pss.HashAlgorithm.ObjectID);
					int saltLength = pss.SaltLength.Value.IntValue;
					byte trailerField = (byte) pss.TrailerField.Value.IntValue;

					// RFC 4055 3.1
					// The value MUST be 1, which represents the trailer field with hexadecimal value 0xBC
					if (trailerField != 1)
						throw new CmsException("RSASSA-PSS signature parameters must have trailerField of 1");

					sig = new PssSigner(new RsaBlindedEngine(), pssDigest, saltLength);
				}
				catch (Exception e)
				{
					throw new CmsException("failed to set RSASSA-PSS signature parameters", e);
				}
			}
			else
			{
				// TODO Probably too strong a check at the moment
//				if (sigParams != null)
//					throw new CmsException("unrecognised signature parameters provided");

				string signatureName = digestName + "with" + Helper.GetEncryptionAlgName(this.EncryptionAlgOid);

				sig = Helper.GetSignatureInstance(signatureName);
			}

			try
			{
				sig.Init(false, key);

				if (signedAttributes == null)
				{
					if (content != null)
					{
						content.Write(new CmsSignedDataGenerator.SigOutputStream(sig));
						content.Write(new CmsSignedDataGenerator.DigOutputStream(digest));

						resultDigest = DigestUtilities.DoFinal(digest);
					}
					else
					{
						resultDigest = digestCalculator.GetDigest();

						// need to decrypt signature and check message bytes
						return VerifyDigest(resultDigest, key, this.GetSignature());
					}
				}
				else
				{
					byte[] hash;
					if (content != null)
					{
						content.Write(
							new CmsSignedDataGenerator.DigOutputStream(digest));

						hash = DigestUtilities.DoFinal(digest);
					}
					else if (digestCalculator != null)
					{
						hash = digestCalculator.GetDigest();
					}
					else
					{
						hash = null;
					}

					resultDigest = hash;

					Asn1.Cms.Attribute dig = signedAttrTable[Asn1.Cms.CmsAttributes.MessageDigest];
					Asn1.Cms.Attribute type = signedAttrTable[Asn1.Cms.CmsAttributes.ContentType];

					if (dig == null)
					{
						throw new SignatureException("no hash for content found in signed attributes");
					}

					if (type == null && !contentType.Equals(CmsAttributes.CounterSignature))
					{
						throw new SignatureException("no content type id found in signed attributes");
					}

					Asn1Object hashObj = dig.AttrValues[0].ToAsn1Object();

					if (hashObj is Asn1OctetString)
					{
						byte[] signedHash = ((Asn1OctetString)hashObj).GetOctets();

						if (!Arrays.AreEqual(hash, signedHash))
						{
							throw new SignatureException("content hash found in signed attributes different");
						}
					}
					else if (hashObj is DerNull)
					{
						if (hash != null)
						{
							throw new SignatureException("NULL hash found in signed attributes when one expected");
						}
					}

					if (type != null)
					{
						DerObjectIdentifier typeOID = (DerObjectIdentifier)type.AttrValues[0];

						if (!typeOID.Equals(contentType))
						{
							throw new SignatureException("contentType in signed attributes different");
						}
					}

					byte[] tmp = this.GetEncodedSignedAttributes();
					sig.BlockUpdate(tmp, 0, tmp.Length);
				}

				return sig.VerifySignature(this.GetSignature());
			}
			catch (InvalidKeyException e)
			{
				throw new CmsException(
					"key not appropriate to signature in message.", e);
			}
			catch (IOException e)
			{
				throw new CmsException(
					"can't process mime object to create signature.", e);
			}
			catch (SignatureException e)
			{
				throw new CmsException(
					"invalid signature format in message: " + e.Message, e);
			}
		}
Exemple #32
0
 private static void ParseDeadBeefItem(byte tag, Asn1.Kind kind)
 {
     var item = Asn1.ParseItem(string.Format("{0:X2}04DEADBEEF", tag).DecodeHex());
     Assert.AreEqual(kind, item.Key);
     Assert.AreEqual(new byte[] {0xDE, 0xAD, 0xBE, 0xEF}, item.Value);
 }
Exemple #33
0
 public void Asn1_ParseItem_throws_on_invalid_tag()
 {
     Asn1.ParseItem("0D04DEADBEEF".DecodeHex());
 }
        /**
        * add a signer with extra signed/unsigned attributes.
		*
		* @param key signing key to use
		* @param cert certificate containing corresponding public key
		* @param digestOID digest algorithm OID
		* @param signedAttr table of attributes to be included in signature
		* @param unsignedAttr table of attributes to be included as unsigned
        */
        public void AddSigner(
            AsymmetricKeyParameter	privateKey,
            X509Certificate			cert,
            string					digestOID,
            Asn1.Cms.AttributeTable	signedAttr,
            Asn1.Cms.AttributeTable	unsignedAttr)
        {
			AddSigner(privateKey, cert, GetEncOid(privateKey, digestOID), digestOID,
				signedAttr, unsignedAttr);
		}
Exemple #35
0
		/**
		* Return a signer information object with the passed in unsigned
		* attributes replacing the ones that are current associated with
		* the object passed in.
		*
		* @param signerInformation the signerInfo to be used as the basis.
		* @param unsignedAttributes the unsigned attributes to add.
		* @return a copy of the original SignerInformationObject with the changed attributes.
		*/
		public static SignerInformation ReplaceUnsignedAttributes(
			SignerInformation		signerInformation,
			Asn1.Cms.AttributeTable	unsignedAttributes)
		{
			SignerInfo sInfo = signerInformation.info;
			Asn1Set unsignedAttr = null;

			if (unsignedAttributes != null)
			{
				unsignedAttr = new DerSet(unsignedAttributes.ToAsn1EncodableVector());
			}

			return new SignerInformation(
				new SignerInfo(
					sInfo.SignerID,
					sInfo.DigestAlgorithm,
					sInfo.AuthenticatedAttributes,
					sInfo.DigestEncryptionAlgorithm,
					sInfo.EncryptedDigest,
					unsignedAttr),
				signerInformation.contentType,
				signerInformation.content,
				null);
		}
		/**
		 * add a signer, specifying the digest encryption algorithm, with extra signed/unsigned attributes.
		 *
		 * @param key signing key to use
		 * @param subjectKeyID subjectKeyID of corresponding public key
		 * @param encryptionOID digest encryption algorithm OID
		 * @param digestOID digest algorithm OID
		 * @param signedAttr table of attributes to be included in signature
		 * @param unsignedAttr table of attributes to be included as unsigned
		 */
		public void AddSigner(
			AsymmetricKeyParameter	privateKey,
			byte[]					subjectKeyID,
			string					encryptionOID,
			string					digestOID,
			Asn1.Cms.AttributeTable	signedAttr,
			Asn1.Cms.AttributeTable	unsignedAttr)
		{
			doAddSigner(privateKey, GetSignerIdentifier(subjectKeyID), encryptionOID, digestOID,
				new DefaultSignedAttributeTableGenerator(signedAttr),
				new SimpleAttributeTableGenerator(unsignedAttr),
				signedAttr);
		}
		private void CheckAttribute(byte[] expected, Asn1.Cms.Attribute	attr)
		{
			DerOctetString value = (DerOctetString)attr.AttrValues[0];

            Assert.AreEqual(new DerOctetString(expected), value);
		}
        private bool DoVerify(
			AsymmetricKeyParameter	key,
			Asn1.Cms.AttributeTable	signedAttrTable)
        {
            string digestName = Helper.GetDigestAlgName(this.DigestAlgOid);
            string signatureName = digestName + "with"
                + Helper.GetEncryptionAlgName(this.EncryptionAlgOid);
            ISigner sig = Helper.GetSignatureInstance(signatureName);
            IDigest digest = Helper.GetDigestInstance(digestName);

            try
            {
                sig.Init(false, key);

                if (signedAttributes == null)
                {
                    if (content != null)
                    {
                        content.Write(new CmsSignedDataGenerator.SigOutputStream(sig));
                        content.Write(new CmsSignedDataGenerator.DigOutputStream(digest));

                        _resultDigest = DigestUtilities.DoFinal(digest);
                    }
                    else
                    {
                        _resultDigest = _digest;

                        // need to decrypt signature and check message bytes
                        return VerifyDigest(_digest, key, this.GetSignature());
                    }
                }
                else
                {
                    byte[] hash;
                    if (content != null)
                    {
                        content.Write(
                            new CmsSignedDataGenerator.DigOutputStream(digest));

                        hash = DigestUtilities.DoFinal(digest);
                    }
                    else
                    {
                        hash = _digest;
                    }

                    _resultDigest = hash;

                    Asn1.Cms.Attribute dig = signedAttrTable[Asn1.Cms.CmsAttributes.MessageDigest];
                    Asn1.Cms.Attribute type = signedAttrTable[Asn1.Cms.CmsAttributes.ContentType];

                    if (dig == null)
                    {
                        throw new SignatureException("no hash for content found in signed attributes");
                    }

                    if (type == null)
                    {
                        throw new SignatureException("no content type id found in signed attributes");
                    }

                    Asn1Object hashObj = dig.AttrValues[0].ToAsn1Object();

                    if (hashObj is Asn1OctetString)
                    {
                        byte[] signedHash = ((Asn1OctetString)hashObj).GetOctets();

                        if (!Arrays.AreEqual(hash, signedHash))
                        {
                            throw new SignatureException("content hash found in signed attributes different");
                        }
                    }
                    else if (hashObj is DerNull)
                    {
                        if (hash != null)
                        {
                            throw new SignatureException("NULL hash found in signed attributes when one expected");
                        }
                    }

                    DerObjectIdentifier typeOID = (DerObjectIdentifier)type.AttrValues[0];

                    if (!typeOID.Equals(contentType))
                    {
                        throw new SignatureException("contentType in signed attributes different");
                    }

                {
                    byte[] tmp = this.GetEncodedSignedAttributes();
                    sig.BlockUpdate(tmp, 0, tmp.Length);
                }
                }

                return sig.VerifySignature(this.GetSignature());
            }
            catch (InvalidKeyException e)
            {
                throw new CmsException(
                    "key not appropriate to signature in message.", e);
            }
            catch (IOException e)
            {
                throw new CmsException(
                    "can't process mime object to create signature.", e);
            }
            catch (SignatureException e)
            {
                throw new CmsException(
                    "invalid signature format in message: " + e.Message, e);
            }
        }
 public void Asn1_ParseItem_throws_on_invalid_tag()
 {
     Exceptions.AssertThrowsInternalError(() => Asn1.ParseItem("0D04DEADBEEF".DecodeHex()),
                                          "Unknown ASN.1 tag 13");
 }