Ejemplo n.º 1
0
        public ITestResult Perform()
        {
            byte[] testIv = { 1, 2, 3, 4, 5, 6, 7, 8 };

            Asn1Encodable[] values =
            {
                new Cast5CbcParameters(testIv, 128),
                new NetscapeCertType(NetscapeCertType.Smime),
                new VerisignCzagExtension(new DerIA5String("hello")),
            #if INCLUDE_IDEA
                new IdeaCbcPar(testIv),
            #endif
                new NetscapeRevocationUrl(new DerIA5String("http://test"))
            };

            #if INCLUDE_IDEA
            byte[] data = Base64.Decode("MA4ECAECAwQFBgcIAgIAgAMCBSAWBWhlbGxvMAoECAECAwQFBgcIFgtodHRwOi8vdGVzdA==");
            #else
            byte[] data = Base64.Decode("MA4ECAECAwQFBgcIAgIAgAMCBSAWBWhlbGxvFgtodHRwOi8vdGVzdA==");
            #endif

            try
            {
                MemoryStream bOut = new MemoryStream();
                Asn1OutputStream aOut = new Asn1OutputStream(bOut);

                for (int i = 0; i != values.Length; i++)
                {
                    aOut.WriteObject(values[i]);
                }

                if (!Arrays.AreEqual(bOut.ToArray(), data))
                {
                    return new SimpleTestResult(false, Name + ": Failed data check");
                }

                Asn1InputStream aIn = new Asn1InputStream(bOut.ToArray());

                for (int i = 0; i != values.Length; i++)
                {
                    Asn1Object o = aIn.ReadObject();

                    if (!values[i].Equals(o))
                    {
                        return new SimpleTestResult(false, Name + ": Failed equality test for " + o);
                    }

                    if (o.GetHashCode() != values[i].GetHashCode())
                    {
                        return new SimpleTestResult(false, Name + ": Failed hashCode test for " + o);
                    }
                }

                return new SimpleTestResult(true, Name + ": Okay");
            }
            catch (Exception e)
            {
                return new SimpleTestResult(false, Name + ": Failed - exception " + e.ToString(), e);
            }
        }
        public override void PerformTest()
        {
            byte[] data = { 0, 1, 0, 1, 0, 0, 1 };

            Asn1Object[] values =
            {
                new BerOctetString(data),
                new BerSequence(new DerPrintableString("hello world")),
                new BerSet(new DerPrintableString("hello world")),
                new BerTaggedObject(0, new DerPrintableString("hello world")),
                new DerApplicationSpecific(0, data),
                new DerBitString(data),
                new DerBmpString("hello world"),
                DerBoolean.True,
                DerBoolean.False,
                new DerEnumerated(100),
                new DerGeneralizedTime("20070315173729Z"),
                new DerGeneralString("hello world"),
                new DerIA5String("hello"),
                new DerInteger(1000),
                DerNull.Instance,
                new DerNumericString("123456"),
                new DerObjectIdentifier("1.1.1.10000.1"),
                new DerOctetString(data),
                new DerPrintableString("hello world"),
                new DerSequence(new DerPrintableString("hello world")),
                new DerSet(new DerPrintableString("hello world")),
                new DerT61String("hello world"),
                new DerTaggedObject(0, new DerPrintableString("hello world")),
                new DerUniversalString(data),
                new DerUnknownTag(true, 500, data),
                new DerUtcTime(new DateTime()),
                new DerUtf8String("hello world"),
                new DerVisibleString("hello world")
            };

            MemoryStream bOut = new MemoryStream();
            Asn1OutputStream aOut = new Asn1OutputStream(bOut);

            for (int i = 0; i != values.Length; i++)
            {
                aOut.WriteObject(values[i]);
            }

            Asn1InputStream aIn = new Asn1InputStream(bOut.ToArray());

            for (int i = 0; i != values.Length; i++)
            {
                Asn1Object o = aIn.ReadObject();
                if (!o.Equals(values[i]))
                {
                    Fail("Failed equality test for " + o.GetType().Name);
                }

                if (o.GetHashCode() != values[i].GetHashCode())
                {
                    Fail("Failed hashCode test for " + o.GetType().Name);
                }
            }
        }
Ejemplo n.º 3
0
        public ITestResult Perform()
        {
            byte[] testIv = { 1, 2, 3, 4, 5, 6, 7, 8 };

            Asn1Encodable[] values =
            {
                new Cast5CbcParameters(testIv,                        128),
                new NetscapeCertType(NetscapeCertType.Smime),
                new VerisignCzagExtension(new DerIA5String("hello")),
                new IdeaCbcPar(testIv),
                new NetscapeRevocationUrl(new DerIA5String("http://test"))
            };

            byte[] data = Base64.Decode("MA4ECAECAwQFBgcIAgIAgAMCBSAWBWhlbGxvMAoECAECAwQFBgcIFgtodHRwOi8vdGVzdA==");

            try
            {
                MemoryStream     bOut = new MemoryStream();
                Asn1OutputStream aOut = new Asn1OutputStream(bOut);

                for (int i = 0; i != values.Length; i++)
                {
                    aOut.WriteObject(values[i]);
                }

                if (!Arrays.AreEqual(bOut.ToArray(), data))
                {
                    return(new SimpleTestResult(false, Name + ": Failed data check"));
                }

                Asn1InputStream aIn = new Asn1InputStream(bOut.ToArray());

                for (int i = 0; i != values.Length; i++)
                {
                    Asn1Object o = aIn.ReadObject();

                    if (!values[i].Equals(o))
                    {
                        return(new SimpleTestResult(false, Name + ": Failed equality test for " + o));
                    }

                    if (o.GetHashCode() != values[i].GetHashCode())
                    {
                        return(new SimpleTestResult(false, Name + ": Failed hashCode test for " + o));
                    }
                }

                return(new SimpleTestResult(true, Name + ": Okay"));
            }
            catch (Exception e)
            {
                return(new SimpleTestResult(false, Name + ": Failed - exception " + e.ToString(), e));
            }
        }
Ejemplo n.º 4
0
        public override void PerformTest()
        {
            byte[] testIv = { 1, 2, 3, 4, 5, 6, 7, 8 };

            Asn1Encodable[] values =
            {
                new Cast5CbcParameters(testIv,                        128),
                new NetscapeCertType(NetscapeCertType.Smime),
                new VerisignCzagExtension(new DerIA5String("hello")),
                new IdeaCbcPar(testIv),
                new NetscapeRevocationUrl(new DerIA5String("http://test"))
            };

            byte[] data = Base64.Decode("MA4ECAECAwQFBgcIAgIAgAMCBSAWBWhlbGxvMAoECAECAwQFBgcIFgtodHRwOi8vdGVzdA==");

            MemoryStream     bOut = new MemoryStream();
            Asn1OutputStream aOut = new Asn1OutputStream(bOut);

            for (int i = 0; i != values.Length; i++)
            {
                aOut.WriteObject(values[i]);
            }

            if (!Arrays.AreEqual(bOut.ToArray(), data))
            {
                Fail("Failed data check");
            }

            Asn1InputStream aIn = new Asn1InputStream(bOut.ToArray());

            for (int i = 0; i != values.Length; i++)
            {
                Asn1Object o = aIn.ReadObject();

                if (!values[i].Equals(o))
                {
                    Fail("Failed equality test for " + o);
                }

                if (o.GetHashCode() != values[i].GetHashCode())
                {
                    Fail("Failed hashCode test for " + o);
                }
            }

            DoShouldFailOnExtraData();
            DoDerIntegerTest();
        }
Ejemplo n.º 5
0
        private void compositeTest()
        {
            //
            // composite test
            //
            byte[]   enc = Hex.Decode("305e310b300906035504061302415531283026060355040a0c1f546865204c6567696f6e206f662074686520426f756e637920436173746c653125301006035504070c094d656c626f75726e653011060355040b0c0a4173636f742056616c65");
            X509Name n   = X509Name.GetInstance(Asn1Object.FromByteArray(enc));

            if (!n.ToString().Equals("C=AU,O=The Legion of the Bouncy Castle,L=Melbourne+OU=Ascot Vale"))
            {
                Fail("Failed composite to string test got: " + n.ToString());
            }

            IDictionary symbols = X509Name.DefaultSymbols;

            if (!n.ToString(true, symbols).Equals("L=Melbourne+OU=Ascot Vale,O=The Legion of the Bouncy Castle,C=AU"))
            {
                Fail("Failed composite to string test got: " + n.ToString(true, symbols));
            }

            n = new X509Name(true, "L=Melbourne+OU=Ascot Vale,O=The Legion of the Bouncy Castle,C=AU");
            if (!n.ToString().Equals("C=AU,O=The Legion of the Bouncy Castle,L=Melbourne+OU=Ascot Vale"))
            {
                Fail("Failed composite to string reversal test got: " + n.ToString());
            }

            n = new X509Name("C=AU, O=The Legion of the Bouncy Castle, L=Melbourne + OU=Ascot Vale");

            MemoryStream     bOut = new MemoryStream();
            Asn1OutputStream aOut = new Asn1OutputStream(bOut);

            aOut.WriteObject(n);

            byte[] enc2 = bOut.ToArray();

            if (!Arrays.AreEqual(enc, enc2))
            {
                Fail("Failed composite string to encoding test");
            }

            //
            // dud name test - handle empty DN without barfing.
            //
            n = new X509Name("C=CH,O=,OU=dummy,[email protected]");

            n = X509Name.GetInstance(Asn1Object.FromByteArray(n.GetEncoded()));
        }
Ejemplo n.º 6
0
        public byte[] CreatePrivateKeyScript(Transaction tx, int inputIndex, byte hashType, ECPrivateKeyParameters privateKey, ECPublicKeyParameters publicKey)
        {
            //TODO
            var sha256       = new SHA256Managed();
            var scriptEngine = new ScriptEngine(this.logger);

            var publicAddress   = CreatePublicAddress(publicKey);
            var publicKeyScript = CreatePublicKeyScript(publicAddress);
            var txSignature     = scriptEngine.TxSignature(publicKeyScript.ToImmutableArray(), tx, inputIndex, hashType);
            var txSignatureHash = sha256.ComputeDoubleHash(txSignature);

            //Debug.WriteLine("Signing Tx:       {0}".Format2(txSignature.ToHexDataString()));
            //Debug.WriteLine("Signing Tx  Hash: {0}".Format2(txSignatureHash.ToHexDataString()));

            var signer = new ECDsaSigner();

            signer.Init(forSigning: true, parameters: privateKey);
            var signature = signer.GenerateSignature(txSignatureHash);
            var r         = signature[0];
            var s         = signature[1];

            byte[] sigEncoded;
            using (var stream = new MemoryStream())
            {
                using (var asn1Stream = new Asn1OutputStream(stream))
                {
                    asn1Stream.WriteObject(new DerSequence(new DerInteger(r), new DerInteger(s)));
                }

                sigEncoded = stream.ToArray().Concat(hashType);
            }

            //Debug.WriteLine("Sig R:       {0}".Format2(r.ToHexNumberStringUnsigned()));
            //Debug.WriteLine("Sig S:       {0}".Format2(s.ToHexNumberStringUnsigned()));
            //Debug.WriteLine("Sig Encoded: {0}".Format2(sigEncoded.ToHexDataString()));

            using (var privateKeyScript = new ScriptBuilder())
            {
                privateKeyScript.WritePushData(sigEncoded);
                privateKeyScript.WritePushData(publicAddress);
                //Debug.WriteLine("Private Script: {0}".Format2(privateKeyScript.GetScript().ToHexDataString()));

                return(privateKeyScript.GetScript());
            }
        }
Ejemplo n.º 7
0
        // adbe.x509.rsa_sha1 (PKCS#1)

        /**
         * Gets the bytes for the PKCS#1 object.
         * @return a byte array
         */
        public byte[] GetEncodedPKCS1()
        {
            if (externalDigest != null)
            {
                digest = externalDigest;
            }
            else
            {
                digest = sig.GenerateSignature();
            }
            MemoryStream bOut = new MemoryStream();

            Asn1OutputStream dout = new Asn1OutputStream(bOut);

            dout.WriteObject(new DerOctetString(digest));
            dout.Close();

            return(bOut.ToArray());
        }
Ejemplo n.º 8
0
        public bool IsNtagECDSASignatureValid()
        {
            if (NtagECDSASignature.Count != 0x20 || NtagSerial.Count != 8)
            {
                return(false);
            }

            var r = new byte[NtagECDSASignature.Count / 2];
            var s = new byte[NtagECDSASignature.Count / 2];

            Array.Copy(NtagECDSASignature.Array, NtagECDSASignature.Offset, r, 0, r.Length);
            Array.Copy(NtagECDSASignature.Array, NtagECDSASignature.Offset + r.Length, s, 0, s.Length);

            var uid = new byte[7];

            Array.Copy(NtagSerial.Array, NtagSerial.Offset + 0, uid, 0, 3);
            Array.Copy(NtagSerial.Array, NtagSerial.Offset + 4, uid, 3, 4);

            var curve     = SecNamedCurves.GetByName("secp128r1");
            var curveSpec = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H, curve.GetSeed());
            var key       = new ECPublicKeyParameters("ECDSA", curve.Curve.DecodePoint(NtagHelpers.NTAG_PUB_KEY), curveSpec);

            var signer = SignerUtilities.GetSigner("NONEwithECDSA");

            signer.Init(false, key);

            signer.BlockUpdate(uid, 0, uid.Length);

            using (var ms = new MemoryStream())
                using (var der = new Asn1OutputStream(ms))
                {
                    var v = new Asn1EncodableVector
                    {
                        new DerInteger(new BigInteger(1, r)),
                        new DerInteger(new BigInteger(1, s))
                    };
                    der.WriteObject(new DerSequence(v));

                    return(signer.VerifySignature(ms.ToArray()));
                }
        }
Ejemplo n.º 9
0
        /**
         * Gets the bytes for the PKCS7SignedData object. Optionally the authenticatedAttributes
         * in the signerInfo can also be set, OR a time-stamp-authority client
         * may be provided.
         * @param secondDigest the digest in the authenticatedAttributes
         * @param signingTime the signing time in the authenticatedAttributes
         * @param tsaClient TSAClient - null or an optional time stamp authority client
         * @return byte[] the bytes for the PKCS7SignedData object
         * @since   2.1.6
         */
        public byte[] GetEncodedPKCS7(byte[] secondDigest, DateTime signingTime, ITSAClient tsaClient, byte[] ocsp, ICollection <byte[]> crlBytes, CryptoStandard sigtype)
        {
            if (externalDigest != null)
            {
                digest = externalDigest;
                if (RSAdata != null)
                {
                    RSAdata = externalRSAdata;
                }
            }
            else if (externalRSAdata != null && RSAdata != null)
            {
                RSAdata = externalRSAdata;
                sig.BlockUpdate(RSAdata, 0, RSAdata.Length);
                digest = sig.GenerateSignature();
            }
            else
            {
                if (RSAdata != null)
                {
                    RSAdata = new byte[messageDigest.GetDigestSize()];
                    messageDigest.DoFinal(RSAdata, 0);
                    sig.BlockUpdate(RSAdata, 0, RSAdata.Length);
                }
                digest = sig.GenerateSignature();
            }

            // Create the set of Hash algorithms
            Asn1EncodableVector digestAlgorithms = new Asn1EncodableVector();

            foreach (string dal in digestalgos.Keys)
            {
                Asn1EncodableVector algos = new Asn1EncodableVector();
                algos.Add(new DerObjectIdentifier(dal));
                algos.Add(DerNull.Instance);
                digestAlgorithms.Add(new DerSequence(algos));
            }

            // Create the contentInfo.
            Asn1EncodableVector v = new Asn1EncodableVector();

            v.Add(new DerObjectIdentifier(SecurityIDs.ID_PKCS7_DATA));
            if (RSAdata != null)
            {
                v.Add(new DerTaggedObject(0, new DerOctetString(RSAdata)));
            }
            DerSequence contentinfo = new DerSequence(v);

            // Get all the certificates
            //
            v = new Asn1EncodableVector();
            foreach (X509Certificate xcert in certs)
            {
                Asn1InputStream tempstream = new Asn1InputStream(new MemoryStream(xcert.GetEncoded()));
                v.Add(tempstream.ReadObject());
            }

            DerSet dercertificates = new DerSet(v);

            // Create signerinfo structure.
            //
            Asn1EncodableVector signerinfo = new Asn1EncodableVector();

            // Add the signerInfo version
            //
            signerinfo.Add(new DerInteger(signerversion));

            v = new Asn1EncodableVector();
            v.Add(CertificateInfo.GetIssuer(signCert.GetTbsCertificate()));
            v.Add(new DerInteger(signCert.SerialNumber));
            signerinfo.Add(new DerSequence(v));

            // Add the digestAlgorithm
            v = new Asn1EncodableVector();
            v.Add(new DerObjectIdentifier(digestAlgorithmOid));
            v.Add(DerNull.Instance);
            signerinfo.Add(new DerSequence(v));

            // add the authenticated attribute if present
            if (secondDigest != null /*&& signingTime != null*/)
            {
                signerinfo.Add(new DerTaggedObject(false, 0, GetAuthenticatedAttributeSet(secondDigest, signingTime, ocsp, crlBytes, sigtype)));
            }
            // Add the digestEncryptionAlgorithm
            v = new Asn1EncodableVector();
            v.Add(new DerObjectIdentifier(digestEncryptionAlgorithmOid));
            v.Add(DerNull.Instance);
            signerinfo.Add(new DerSequence(v));

            // Add the digest
            signerinfo.Add(new DerOctetString(digest));

            // When requested, go get and add the timestamp. May throw an exception.
            // Added by Martin Brunecky, 07/12/2007 folowing Aiken Sam, 2006-11-15
            // Sam found Adobe expects time-stamped SHA1-1 of the encrypted digest
            if (tsaClient != null)
            {
                byte[] tsImprint = DigestAlgorithms.Digest(tsaClient.GetMessageDigest(), digest);
                byte[] tsToken   = tsaClient.GetTimeStampToken(tsImprint);
                if (tsToken != null)
                {
                    Asn1EncodableVector unauthAttributes = BuildUnauthenticatedAttributes(tsToken);
                    if (unauthAttributes != null)
                    {
                        signerinfo.Add(new DerTaggedObject(false, 1, new DerSet(unauthAttributes)));
                    }
                }
            }

            // Finally build the body out of all the components above
            Asn1EncodableVector body = new Asn1EncodableVector();

            body.Add(new DerInteger(version));
            body.Add(new DerSet(digestAlgorithms));
            body.Add(contentinfo);
            body.Add(new DerTaggedObject(false, 0, dercertificates));

            // Only allow one signerInfo
            body.Add(new DerSet(new DerSequence(signerinfo)));

            // Now we have the body, wrap it in it's PKCS7Signed shell
            // and return it
            //
            Asn1EncodableVector whole = new Asn1EncodableVector();

            whole.Add(new DerObjectIdentifier(SecurityIDs.ID_PKCS7_SIGNED_DATA));
            whole.Add(new DerTaggedObject(0, new DerSequence(body)));

            MemoryStream bOut = new MemoryStream();

            Asn1OutputStream dout = new Asn1OutputStream(bOut);

            dout.WriteObject(new DerSequence(whole));
            dout.Close();

            return(bOut.ToArray());
        }
Ejemplo n.º 10
0
        public override void PerformTest()
        {
            byte[] data = { 0, 1, 0, 1, 0, 0, 1 };

            Asn1Object[] values =
            {
                new BerOctetString(data),
                new BerSequence(new DerPrintableString("hello world")),
                new BerSet(new DerPrintableString("hello world")),
                new BerTaggedObject(0,                                 new DerPrintableString("hello world")),
                new DerApplicationSpecific(0,                          data),
                new DerBitString(data),
                new DerBmpString("hello world"),
                DerBoolean.True,
                DerBoolean.False,
                new DerEnumerated(100),
                new DerGeneralizedTime("20070315173729Z"),
                new DerGeneralString("hello world"),
                new DerIA5String("hello"),
                new DerInteger(1000),
                DerNull.Instance,
                new DerNumericString("123456"),
                new DerObjectIdentifier("1.1.1.10000.1"),
                new DerOctetString(data),
                new DerPrintableString("hello world"),
                new DerSequence(new DerPrintableString("hello world")),
                new DerSet(new DerPrintableString("hello world")),
                new DerT61String("hello world"),
                new DerTaggedObject(0,                                 new DerPrintableString("hello world")),
                new DerUniversalString(data),
                new DerUtcTime(new DateTime()),
                new DerUtf8String("hello world"),
                new DerVisibleString("hello world"),
                new DerGraphicString(Hex.Decode("deadbeef")),
                new DerVideotexString(Strings.ToByteArray("Hello World"))
            };

            MemoryStream     bOut = new MemoryStream();
            Asn1OutputStream aOut = new Asn1OutputStream(bOut);

            for (int i = 0; i != values.Length; i++)
            {
                aOut.WriteObject(values[i]);
            }

            Asn1InputStream aIn = new Asn1InputStream(bOut.ToArray());

            for (int i = 0; i != values.Length; i++)
            {
                Asn1Object o = aIn.ReadObject();
                if (!o.Equals(values[i]))
                {
                    Fail("Failed equality test for " + o.GetType().Name);
                }

                if (o.GetHashCode() != values[i].GetHashCode())
                {
                    Fail("Failed hashCode test for " + o.GetType().Name);
                }
            }
        }
Ejemplo n.º 11
0
		private void compositeTest()
		{
			//
			// composite test
			//
			byte[] enc = Hex.Decode("305e310b300906035504061302415531283026060355040a0c1f546865204c6567696f6e206f662074686520426f756e637920436173746c653125301006035504070c094d656c626f75726e653011060355040b0c0a4173636f742056616c65");
			X509Name n = X509Name.GetInstance(Asn1Object.FromByteArray(enc));

			if (!n.ToString().Equals("C=AU,O=The Legion of the Bouncy Castle,L=Melbourne+OU=Ascot Vale"))
			{
				Fail("Failed composite to string test got: " + n.ToString());
			}

            IDictionary symbols = X509Name.DefaultSymbols;
			if (!n.ToString(true, symbols).Equals("L=Melbourne+OU=Ascot Vale,O=The Legion of the Bouncy Castle,C=AU"))
			{
                Fail("Failed composite to string test got: " + n.ToString(true, symbols));
			}

			n = new X509Name(true, "L=Melbourne+OU=Ascot Vale,O=The Legion of the Bouncy Castle,C=AU");
			if (!n.ToString().Equals("C=AU,O=The Legion of the Bouncy Castle,L=Melbourne+OU=Ascot Vale"))
			{
				Fail("Failed composite to string reversal test got: " + n.ToString());
			}

			n = new X509Name("C=AU, O=The Legion of the Bouncy Castle, L=Melbourne + OU=Ascot Vale");

			MemoryStream bOut = new MemoryStream();
			Asn1OutputStream aOut = new Asn1OutputStream(bOut);

			aOut.WriteObject(n);

			byte[] enc2 = bOut.ToArray();

			if (!Arrays.AreEqual(enc, enc2))
			{
				Fail("Failed composite string to encoding test");
			}

			//
			// dud name test - handle empty DN without barfing.
			//
			n = new X509Name("C=CH,O=,OU=dummy,[email protected]");

			n = X509Name.GetInstance(Asn1Object.FromByteArray(n.GetEncoded()));
		}