예제 #1
0
        /// <summary>
        /// Creates a signature from the given <paramref name="message"/>.
        /// <para>
        /// A created signature can be verified by the corresponding
        /// <see cref="PublicKey"/>.
        /// </para>
        /// <para>
        /// Signatures can be created by only the <see cref="PrivateKey"/>
        /// which corresponds a <see cref="PublicKey"/> to verify these
        /// signatures.
        /// </para>
        /// <para>
        /// To sum up, a signature is used to guarantee:
        /// </para>
        /// <list type="bullet">
        /// <item><description>that the <paramref name="message"/> was created
        /// by someone possessing the corresponding <see cref="PrivateKey"/>,
        /// </description></item>
        /// <item><description>that the possessor cannot deny having sent the
        /// <paramref name="message"/>, and</description></item>
        /// <item><description>that the <paramref name="message"/> was not
        /// forged in the middle of transit.</description></item>
        /// </list>
        /// </summary>
        /// <param name="message">A message to sign in <see cref="byte"/> array
        /// representation.</param>
        /// <returns>A signature that verifies the <paramref name="message"/>.
        /// It can be verified using
        /// <see cref="Libplanet.Crypto.PublicKey.Verify(byte[], byte[])"/>
        /// method.</returns>
        /// <seealso cref="Libplanet.Crypto.PublicKey.Verify(byte[], byte[])"/>
        public byte[] Sign(byte[] message)
        {
            var h      = new Sha256Digest();
            var hashed = new byte[h.GetDigestSize()];

            h.BlockUpdate(message, 0, message.Length);
            h.DoFinal(hashed, 0);
            h.Reset();

            var kCalculator = new HMacDsaKCalculator(h);
            var signer      = new ECDsaSigner(kCalculator);

            signer.Init(true, keyParam);
            BigInteger[] rs = signer.GenerateSignature(hashed);
            var          r  = rs[0];
            var          s  = rs[1];

            BigInteger otherS = keyParam.Parameters.N.Subtract(s);

            if (s.CompareTo(otherS) == 1)
            {
                s = otherS;
            }

            var bos = new MemoryStream(72);
            var seq = new DerSequenceGenerator(bos);

            seq.AddObject(new DerInteger(r));
            seq.AddObject(new DerInteger(s));
            seq.Close();
            return(bos.ToArray());
        }
예제 #2
0
        protected override void EncodeParameters(Asn1Generator generator)
        {
            // Id
            var id = new DerApplicationSpecific(TAG_PARAM_ID, BinaryParser.ConvertInt16(Id, ByteEndianess.BigEndian));

            // Keyset - IA Modulus
            var iaModulus = new DerApplicationSpecific(TAG_KEYSET_IAMODULUS, new byte[PlaidApplication.LENGTH_KEY_RSA]);

            // Keyset - IA Exponent
            var iaExponent = new DerApplicationSpecific(TAG_KEYSET_IAEXPONENT, new byte[PlaidApplication.LENGTH_PUBLIC_EXPONENT]);

            // Keyset - FAKey
            var faKey = new DerApplicationSpecific(TAG_KEYSET_FAKEY, new byte[PlaidApplication.LENGTH_KEY_AES]);

            // Rules
            List <DerOctetString> rules = new List <DerOctetString>();

            foreach (var rule in Rules)
            {
                rules.Add(new DerOctetString(rule));
            }

            // Parameters (Choice)
            var parameters = new DerSequenceGenerator(generator.GetRawOutputStream(), OP_KEY_CREATE, false);

            parameters.AddObject(id);
            parameters.AddObject(new DerApplicationSpecific(TAG_PARAM_KEY, new Asn1EncodableVector(iaModulus, iaExponent, faKey)));
            parameters.AddObject(new DerApplicationSpecific(TAG_PARAM_RULES, new Asn1EncodableVector(rules.ToArray())));
            parameters.Close();

            // SamId
            var samId = new DerApplicationSpecific(TAG_SAMID, BinaryParser.ConvertInt16(SamId, ByteEndianess.BigEndian));

            generator.AddObject(samId);
        }
예제 #3
0
        public byte[] Sign(byte[] data, string signatureAlgorithm)
        {
            if (PrivateKey == null)
            {
                throw new ArgumentException("Unable to sign data, private key not found");
            }
            if (data == null || data.Length == 0)
            {
                throw new ArgumentException("Unable to sign empty data");
            }
            ISigner signer = SignerUtilities.GetSigner(signatureAlgorithm);

            signer.Init(true, PrivateKey);
            signer.BlockUpdate(data, 0, data.Length);
            byte[] signature = signer.GenerateSignature();
            if (PrivateKey is ECPrivateKeyParameters)
            {
                ECPrivateKeyParameters privkey = (ECPrivateKeyParameters)PrivateKey;
                BigInteger             N       = privkey.Parameters.N;
                BigInteger[]           sigs    = DecodeECDSASignature(signature);
                sigs = PreventMalleability(sigs, N);
                using (MemoryStream ms = new MemoryStream())
                {
                    DerSequenceGenerator seq = new DerSequenceGenerator(ms);
                    seq.AddObject(new DerInteger(sigs[0]));
                    seq.AddObject(new DerInteger(sigs[1]));
                    seq.Close();
                    ms.Flush();
                    signature = ms.ToArray();
                }
            }

            return(signature);
        }
예제 #4
0
        /// <summary>
        /// sign csr
        /// </summary>
        /// <param name="signer">signature interface</param>
        /// <param name="key">EC private key</param>
        /// <param name="src">source data</param>
        /// <returns>signature result</returns>
        public static byte[] CsrSign(this ISigner signer, AsymmetricKeyParameter key, byte[] src, BigInteger curveN)
        {
            signer.Init(true, key);
            signer.BlockUpdate(src, 0, src.Length);
            byte[] signature = signer.GenerateSignature();

            Asn1Sequence sequence = Asn1Sequence.GetInstance(signature);
            DerInteger   r        = (DerInteger)sequence[0];
            DerInteger   s        = (DerInteger)sequence[1];

            BigInteger[] sigs = new BigInteger[] { r.Value, s.Value };

            sigs = SignerExtends.preventMalleability(sigs, curveN);
            byte[] bs;
            using (MemoryStream ms = new MemoryStream())
            {
                DerSequenceGenerator seq = new DerSequenceGenerator(ms);
                seq.AddObject(new DerInteger(sigs[0]));
                seq.AddObject(new DerInteger(sigs[1]));
                seq.Close();
                bs = ms.ToArray();
            }

            return(bs);
        }
예제 #5
0
        /**
         * used asn1 and get hash
         *
         * @param blockNumber
         * @param previousHash
         * @param dataHash
         * @return byte[]
         * @throws IOException
         * @throws InvalidIllegalArgumentException
         */
        public static byte[] CalculateBlockHash(HFClient client, long blockNumber, byte[] previousHash, byte[] dataHash)
        {
            if (previousHash == null)
            {
                throw new ArgumentException("previousHash parameter is null.");
            }

            if (dataHash == null)
            {
                throw new ArgumentException("dataHash parameter is null.");
            }

            if (null == client)
            {
                throw new ArgumentException("client parameter is null.");
            }

            ICryptoSuite cryptoSuite = client.CryptoSuite;

            if (null == cryptoSuite)
            {
                throw new ArgumentException("Client crypto suite has not  been set.");
            }

            MemoryStream         s   = new MemoryStream();
            DerSequenceGenerator seq = new DerSequenceGenerator(s);

            seq.AddObject(new DerInteger((int)blockNumber));
            seq.AddObject(new DerOctetString(previousHash));
            seq.AddObject(new DerOctetString(dataHash));
            seq.Close();
            s.Flush();
            return(cryptoSuite.Hash(s.ToArray()));
        }
예제 #6
0
        /// <summary>
        ///  使用私钥进行签名
        /// </summary>
        /// <param name="macdata">签名原串</param>
        /// <param name="privateKey">私钥</param>
        /// <returns></returns>
        public static byte[] Sign(byte[] macdata, AsymmetricKeyParameter privateKey)
        {
            Org.BouncyCastle.Crypto.Signers.SM2Signer signer = new Org.BouncyCastle.Crypto.Signers.SM2Signer();
            signer.Init(true, privateKey);
            signer.BlockUpdate(macdata, 0, macdata.Length);
            byte[] sign = signer.GenerateSignature();
            return(sign);

            Asn1Sequence sequence = Asn1Sequence.GetInstance(sign);
            DerInteger   r        = (DerInteger)sequence[0];
            DerInteger   s        = (DerInteger)sequence[1];

            BigInteger[] bigs = new BigInteger[] { r.Value, s.Value };

            byte[] bs;
            using (MemoryStream ms = new MemoryStream())
            {
                DerSequenceGenerator seq = new DerSequenceGenerator(ms);
                seq.AddObject(new DerInteger(bigs[0]));
                seq.AddObject(new DerInteger(bigs[1]));
                seq.Close();
                bs = ms.ToArray();
            }
            return(bs);
        }
예제 #7
0
        private static void Sign(UnsignedTransaction unsignedTransaction, string privateKey, bool isHex, bool addPubKey,
                                 bool forceCompressed = false)
        {
            bool compressed = false;
            var  bytes      = isHex ? privateKey.FromHexString() : GetBytesFromBase58Key(privateKey);

            if (bytes.Length == 33 && bytes[32] == 1)
            {
                compressed = true;
                bytes      = bytes.Take(32).ToArray();
            }

            var privKeyB       = new BigInteger(1, bytes);
            var parms          = SecNamedCurves.GetByName("secp256k1");
            var curve          = new ECDomainParameters(parms.Curve, parms.G, parms.N, parms.H);
            var halfCurveOrder = parms.N.ShiftRight(1);

            var point = curve.G.Multiply(privKeyB);

            if (compressed || forceCompressed)
            {
                point = new FpPoint(curve.Curve, point.X, point.Y, true);
            }

            var publicKey = point.GetEncoded();
            var signer    = new ECDsaSigner();
            var privKey   = new ECPrivateKeyParameters(privKeyB, curve);

            signer.Init(true, privKey);

            foreach (string toSign in unsignedTransaction.ToSign)
            {
                if (addPubKey)
                {
                    unsignedTransaction.PubKeys.Add(publicKey.ToHexString());
                }

                var components = signer.GenerateSignature(toSign.FromHexString());
                var r          = components[0];
                var s          = components[1];

                if (s.CompareTo(halfCurveOrder) > 0)
                {
                    s = curve.N.Subtract(s);
                }

                using (var ms = new MemoryStream())
                    using (var asn = new Asn1OutputStream(ms)) {
                        var seq = new DerSequenceGenerator(asn);
                        seq.AddObject(new DerInteger(r));
                        seq.AddObject(new DerInteger(s));

                        seq.Close();

                        string signedString = ms.ToArray().ToHexString();

                        unsignedTransaction.Signatures.Add(signedString);
                    }
            }
        }
예제 #8
0
        public byte[] ToDER(bool compressed)
        {
            AssertPrivateKey();
            MemoryStream baos = new MemoryStream();

            // ASN1_SEQUENCE(EC_PRIVATEKEY) = {
            //   ASN1_SIMPLE(EC_PRIVATEKEY, version, LONG),
            //   ASN1_SIMPLE(EC_PRIVATEKEY, privateKey, ASN1_OCTET_STRING),
            //   ASN1_EXP_OPT(EC_PRIVATEKEY, parameters, ECPKPARAMETERS, 0),
            //   ASN1_EXP_OPT(EC_PRIVATEKEY, publicKey, ASN1_BIT_STRING, 1)
            // } ASN1_SEQUENCE_END(EC_PRIVATEKEY)
            DerSequenceGenerator seq = new DerSequenceGenerator(baos);

            seq.AddObject(new DerInteger(1));             // version
            seq.AddObject(new DerOctetString(PrivateKey.D.ToByteArrayUnsigned()));


            //Did not managed to generate the same der as brainwallet by using this
            //seq.AddObject(new DerTaggedObject(0, Secp256k1.ToAsn1Object()));
            Asn1Object secp256k1Der = null;

            if (compressed)
            {
                secp256k1Der = DerSequence.FromByteArray(DataEncoders.Encoders.Hex.DecodeData("308182020101302c06072a8648ce3d0101022100fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f300604010004010704210279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798022100fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141020101"));
            }
            else
            {
                secp256k1Der = DerSequence.FromByteArray(DataEncoders.Encoders.Hex.DecodeData("3081a2020101302c06072a8648ce3d0101022100fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f300604010004010704410479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8022100fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141020101"));
            }
            seq.AddObject(new DerTaggedObject(0, secp256k1Der));
            seq.AddObject(new DerTaggedObject(1, new DerBitString(GetPubKey(compressed).ToBytes())));
            seq.Close();
            return(baos.ToArray());
        }
예제 #9
0
        public static byte[] SignTransaction(byte[] data, byte[] privateKey)
        {
            ECDsaSigner        signer = new ECDsaSigner();
            X9ECParameters     spec   = SecNamedCurves.GetByName("secp256k1");
            ECDomainParameters domain = new ECDomainParameters(spec.Curve, spec.G, spec.N);

            ECPrivateKeyParameters privateKeyParms =
                new ECPrivateKeyParameters(new BigInteger(1, privateKey), domain);
            ParametersWithRandom paramxs = new ParametersWithRandom(privateKeyParms);

            signer.Init(true, paramxs);

            var signature = signer.GenerateSignature(data); //sign and get R and S

            //return as DER format
            using (MemoryStream outStream = new MemoryStream(80))
            {
                DerSequenceGenerator seq = new DerSequenceGenerator(outStream);
                seq.AddObject(new DerInteger(signature[0]));                                                              //r
                seq.AddObject(new DerInteger(signature[1]));                                                              //s
                seq.AddObject(new DerInteger(GetRecoveryId(signature[0].ToByteArray(),
                                                           signature[1].ToByteArray(), data, GetPublicKey(privateKey)))); //v
                seq.Close();
                return(outStream.ToArray());
            }
        }
예제 #10
0
        /// <summary>
        /// data signature
        /// </summary>
        /// <param name="signer">signature interface</param>
        /// <param name="key">EC private key</param>
        /// <param name="src">source data</param>
        /// <returns>signature result</returns>
        public static byte[] Sign(this ISigner signer, ECPrivateKeyParameters key, byte[] src)
        {
            signer.Init(true, key);
            signer.BlockUpdate(src, 0, src.Length);
            byte[] sign = signer.GenerateSignature();

            Asn1Sequence sequence = Asn1Sequence.GetInstance(sign);
            DerInteger   r        = (DerInteger)sequence[0];
            DerInteger   s        = (DerInteger)sequence[1];

            BigInteger[] bigs = new BigInteger[] { r.Value, s.Value };

            var N = key.Parameters.N;

            bigs = preventMalleability(bigs, N);

            byte[] bs;
            using (MemoryStream ms = new MemoryStream())
            {
                DerSequenceGenerator seq = new DerSequenceGenerator(ms);
                seq.AddObject(new DerInteger(bigs[0]));
                seq.AddObject(new DerInteger(bigs[1]));
                seq.Close();
                bs = ms.ToArray();
            }

            return(bs);
        }
예제 #11
0
        public static byte[] Sign(byte[] bytes, byte[] privateKey)
        {
            var x9EcParameters = SecNamedCurves.GetByName("secp256k1");
            var ecParams       = new ECDomainParameters(x9EcParameters.Curve, x9EcParameters.G, x9EcParameters.N, x9EcParameters.H);

            var privateKeyBigInteger = new BigInteger((new byte[] { 0x00 }).Concat(privateKey).ToArray());

            var signer = new ECDsaSigner();

            var privateKeyParameters = new ECPrivateKeyParameters(privateKeyBigInteger, ecParams);

            signer.Init(true, privateKeyParameters);

            var signature = signer.GenerateSignature(bytes);

            var memoryStream = new MemoryStream();

            var sequenceGenerator = new DerSequenceGenerator(memoryStream);

            sequenceGenerator.AddObject(new DerInteger(signature[0]));
            sequenceGenerator.AddObject(new DerInteger(signature[1]));
            sequenceGenerator.Close();

            var signingResult = memoryStream.ToArray();

            return(signingResult);
        }
예제 #12
0
        /// <summary>
        /// Calculates an ECDSA signature in DER format for the given input hash. Note that the input is expected to be
        /// 32 bytes long.
        /// </summary>
        public byte[] Sign(byte[] input, Org.BouncyCastle.Math.BigInteger privateKey)
        {
            const string BITCOIN_CURVE = "secp256k1";
            ECDsaSigner  signer        = new ECDsaSigner();

            Org.BouncyCastle.Asn1.X9.X9ECParameters ecp = SecNamedCurves.GetByName(BITCOIN_CURVE);
            ECDomainParameters EcParameters             = new ECDomainParameters(ecp.Curve, ecp.G, ecp.N, ecp.H);

            var privateKeyParameters = new ECPrivateKeyParameters(privateKey, EcParameters);

            signer.Init(true, privateKeyParameters);
            var signatures = signer.GenerateSignature(input);

            // What we get back from the signer are the two components of a signature, r and s. To get a flat byte stream
            // of the type used by BitCoin we have to encode them using DER encoding, which is just a way to pack the two
            // components into a structure.
            using (var byteOutputStream = new MemoryStream())
            {
                var derSequenceGenerator = new DerSequenceGenerator(byteOutputStream);
                derSequenceGenerator.AddObject(new DerInteger(signatures[0]));
                derSequenceGenerator.AddObject(new DerInteger(signatures[1]));
                derSequenceGenerator.Close();
                return(byteOutputStream.ToArray());
            }
        }
예제 #13
0
        public byte[] Sign(HashDigest <T> messageHash, PrivateKey privateKey)
        {
            var h           = new Sha256Digest();
            var kCalculator = new HMacDsaKCalculator(h);
            var signer      = new ECDsaSigner(kCalculator);

            signer.Init(true, privateKey.KeyParam);
            BigInteger[] rs = signer.GenerateSignature(messageHash.ToByteArray());
            var          r  = rs[0];
            var          s  = rs[1];

            BigInteger otherS = privateKey.KeyParam.Parameters.N.Subtract(s);

            if (s.CompareTo(otherS) == 1)
            {
                s = otherS;
            }

            var bos = new MemoryStream(72);
            var seq = new DerSequenceGenerator(bos);

            seq.AddObject(new DerInteger(r));
            seq.AddObject(new DerInteger(s));
            seq.Close();
            return(bos.ToArray());
        }
예제 #14
0
        public string SignMessage(string msg, string privKey)
        {
            //$.checkArgument(text);
            string hashMsg = DoubleHashMessageReverse(msg);

            // Debugging Only
            //Console.WriteLine("Hashed Message: " + hashMsg);
            //Console.WriteLine("Hashed Message in Bytes: " + BitConverter.ToString(Encoding.Unicode.GetBytes(hashMsg)));
            byte[] bytedPrivKey = ConvertToByteArray(privKey);

            // Retrieve the private key in bigint
            BigInteger privateKeyInt = new BigInteger(+1, ConvertToByteArray(privKey));

            // Reconstruct the curve
            X9ECParameters parameters = SecNamedCurves.GetByName("secp256k1");
            //Org.BouncyCastle.Math.EC.ECPoint point = parameters.G.Multiply(privateKeyInt);

            // Setup the signer
            // https://www.programcreek.com/java-api-examples/index.php?api=org.bouncycastle.crypto.signers.ECDSASigner
            // Cant new ECDsaSigner(new HMacDsaKCalculator(new Sha256Digest())); Because Btc doesn't use those..
            ECDsaSigner signer = new ECDsaSigner();

            // Construct the ECDomainParameters
            // https://programtalk.com/java-api-usage-examples/org.bouncycastle.crypto.params.ECDomainParameters/ => How to get the parameters
            ECDomainParameters ecDomainParams = new ECDomainParameters(parameters.Curve, parameters.G, parameters.N, parameters.H);
            ECKeyParameters    keyParams      = new ECPrivateKeyParameters(privateKeyInt, ecDomainParams);

            signer.Init(true, keyParams);
            BigInteger[] signature = signer.GenerateSignature(Encoding.Unicode.GetBytes(hashMsg));

            // https://stackoverflow.com/questions/37572306/verifying-ecdsa-signature-with-bouncy-castle-in-c-sharp
            MemoryStream stream = new MemoryStream();

            //DerOutputStream der = new DerOutputStream(stream);

            try
            {
                //Asn1EncodableVector seq = new Asn1EncodableVector();
                //seq.Add(new DerInteger(signature[0]));
                //seq.Add(new DerInteger(signature[1]));
                //der.WriteObject(new DerSequence(seq));
                DerSequenceGenerator seq = new DerSequenceGenerator(stream);
                seq.AddObject(new DerInteger(signature[0]));
                seq.AddObject(new DerInteger(signature[1]));
                seq.Close();

                byte[] bitResult = stream.ToArray();

                PrintByteArray(bitResult);

                Console.WriteLine("MemoryStream Output: " + BitConverter.ToString(bitResult).Replace("-", string.Empty));

                return(BitConverter.ToString(bitResult).Replace("-", string.Empty));
            }
            catch (IOException e)
            {
                return(e.ToString());
            }
        }
예제 #15
0
        public byte[] ToDER()
        {
            var derSignature = new MemoryStream(64);
            var sequence     = new DerSequenceGenerator(derSignature);

            sequence.AddObject(new DerInteger(R));
            sequence.AddObject(new DerInteger(S));
            sequence.Close();

            return(derSignature.ToArray());
        }
예제 #16
0
        /**
         * What we get back from the signer are the two components of a signature, r and s. To get a flat byte stream
         * of the type used by Bitcoin we have to encode them using DER encoding, which is just a way to pack the two
         * components into a structure.
         */
        public byte[] ToDER()
        {
            // Usually 70-72 bytes.
            MemoryStream         bos = new MemoryStream(72);
            DerSequenceGenerator seq = new DerSequenceGenerator(bos);

            seq.AddObject(new DerInteger(R));
            seq.AddObject(new DerInteger(S));
            seq.Close();
            return(bos.ToArray());
        }
예제 #17
0
        public byte[] ToDER()
        {
            var bos = new MemoryStream(72);
            var seq = new DerSequenceGenerator(bos);

            seq.AddObject(new DerInteger(R));
            seq.AddObject(new DerInteger(S));
            seq.Close();

            return(bos.ToArray());
        }
예제 #18
0
파일: EcKey.cs 프로젝트: wtcoin/dotblock
            /// <summary>
            /// DER is an international standard for serializing data structures which is widely used in cryptography.
            /// It's somewhat like protocol buffers but less convenient. This method returns a standard DER encoding
            /// of the signature, as recognized by OpenSSL and other libraries.
            /// </summary>
            /// <param name="sighash">
            /// The signature hash.
            /// </param>
            public byte[] EncodeToDer(byte sighash)
            {
                // Usually 70-72 bytes.
                MemoryStream         bos = new MemoryStream(72);
                DerSequenceGenerator seq = new DerSequenceGenerator(bos);

                seq.AddObject(new DerInteger(this.R));
                seq.AddObject(new DerInteger(this.S));
                seq.Close();
                return(bos.ToArray().Concat(new[] { sighash }).ToArray());
            }
예제 #19
0
        protected MemoryStream DerByteStream()
        {
            // Usually 70-72 bytes.
            var bos = new MemoryStream(72);
            var seq = new DerSequenceGenerator(bos);

            seq.AddObject(new DerInteger(R));
            seq.AddObject(new DerInteger(S));
            seq.Close();
            return(bos);
        }
예제 #20
0
 public byte[] ToDer()
 {
     // Usually 70-72 bytes.
     using (var ms = new MemoryStream(72))
     {
         var seq = new DerSequenceGenerator(ms);
         seq.AddObject(new DerInteger(R));
         seq.AddObject(new DerInteger(S.ToByteArray().Take(32).ToArray()));
         seq.Close();
         return(ms.ToArray());
     }
 }
예제 #21
0
		public void TestDerWriting()
        {
            MemoryStream bOut = new MemoryStream();
            DerSequenceGenerator seqGen = new DerSequenceGenerator(bOut);

			seqGen.AddObject(new DerInteger(BigInteger.Zero));

			seqGen.AddObject(new DerObjectIdentifier("1.1"));

			seqGen.Close();

			Assert.IsTrue(Arrays.AreEqual(seqData, bOut.ToArray()), "basic DER writing test failed.");
        }
예제 #22
0
		public void TestDerImplicitTaggedSequenceWriting()
        {
            MemoryStream bOut = new MemoryStream();
            DerSequenceGenerator seqGen = new DerSequenceGenerator(bOut, 1, false);

			seqGen.AddObject(new DerInteger(BigInteger.Zero));

			seqGen.AddObject(new DerObjectIdentifier("1.1"));

			seqGen.Close();

			Assert.IsTrue(Arrays.AreEqual(implTagSeqData, bOut.ToArray()), "implicit tag writing test failed.");
        }
예제 #23
0
        public void TestDerImplicitTaggedSequenceWriting()
        {
            MemoryStream         bOut   = new MemoryStream();
            DerSequenceGenerator seqGen = new DerSequenceGenerator(bOut, 1, false);

            seqGen.AddObject(new DerInteger(BigInteger.Zero));

            seqGen.AddObject(new DerObjectIdentifier("1.1"));

            seqGen.Close();

            Assert.IsTrue(Arrays.AreEqual(implTagSeqData, bOut.ToArray()), "implicit tag writing test failed.");
        }
예제 #24
0
            public byte[] EncodeToDER()
            {
                MemoryStream         memoryStream      = new MemoryStream(72);
                DerSequenceGenerator sequenceGenerator = new DerSequenceGenerator(memoryStream);
                DerInteger           derInteger1       = new DerInteger(this.r);

                sequenceGenerator.AddObject(derInteger1);
                DerInteger derInteger2 = new DerInteger(this.s);

                sequenceGenerator.AddObject(derInteger2);
                sequenceGenerator.Close();
                return(memoryStream.ToArray());
            }
예제 #25
0
        public void TestDerWriting()
        {
            MemoryStream         bOut   = new MemoryStream();
            DerSequenceGenerator seqGen = new DerSequenceGenerator(bOut);

            seqGen.AddObject(new DerInteger(BigInteger.Zero));

            seqGen.AddObject(new DerObjectIdentifier("1.1"));

            seqGen.Close();

            Assert.IsTrue(Arrays.AreEqual(seqData, bOut.ToArray()), "basic DER writing test failed.");
        }
예제 #26
0
        private static byte[] Ieee1363ToDer(byte[] input)
        {
            // Input is (r, s), each of them exactly half of the array.
            // Output is the DER encoded value of SEQUENCE(INTEGER(r), INTEGER(s)).
            int halfLength = input.Length / 2;

            MemoryStream         encoded   = new MemoryStream();
            DerSequenceGenerator generator = new DerSequenceGenerator(encoded);

            generator.AddObject(Ieee1363KeyParameterIntegerToDer(input, 0, halfLength));          //add r
            generator.AddObject(Ieee1363KeyParameterIntegerToDer(input, halfLength, halfLength)); //add s
            generator.Close();

            return(encoded.ToArray());
        }
예제 #27
0
        private byte[] GetFingerprintBytes()
        {
            using (var bOut = new MemoryStream())
            {
                DerSequenceGenerator seqGen1 = new DerSequenceGenerator(bOut);

                seqGen1.AddObject(new DerTaggedObject(false, 0, new DerOctetString(_publicKey)));

                seqGen1.Close();

                var encoded = bOut.ToArray();

                return(encoded);
            }
        }
예제 #28
0
        /// <summary>
        /// Calculates an ECDSA signature in DER format for the given input hash. Note that the input is expected to be
        /// 32 bytes long.
        /// </summary>
        public byte[] Sign(byte[] input)
        {
            var ecDsaSigner          = new ECDsaSigner();
            var privateKeyParameters = new ECPrivateKeyParameters(_privateKey, EcParams);

            ecDsaSigner.Init(true, privateKeyParameters);
            var signature = ecDsaSigner.GenerateSignature(input);

            using (var memoryStream = new MemoryStream()) {
                var sequenceGenerator = new DerSequenceGenerator(memoryStream);
                sequenceGenerator.AddObject(new DerInteger(signature[0]));
                sequenceGenerator.AddObject(new DerInteger(signature[1]));
                sequenceGenerator.Close();
                return(memoryStream.ToArray());
            }
        }
예제 #29
0
        //http://www.bouncycastle.org/csharp/index.html
        public byte[] SerializeBinary(byte[] signature)
        {
            using (var bOut = new MemoryStream())
            {
                DerSequenceGenerator seqGen1 = new DerSequenceGenerator(bOut, 4, false);

                seqGen1.AddObject(new DerTaggedObject(false, 0, new DerOctetString(_publicKey)));

                seqGen1.AddObject(new DerTaggedObject(false, 1, new DerOctetString(signature)));

                seqGen1.Close();

                var encoded = bOut.ToArray();

                return(encoded);
            }
        }
예제 #30
0
        public byte[] Encode()
        {
            MemoryStream         stream   = new MemoryStream();
            DerSequenceGenerator sequence = new DerSequenceGenerator(stream);

            foreach (short k in this)
            {
                sequence.AddObject(new DerOctetString(Converters.IntToArray(k)));
            }

            sequence.Close();

            byte[] response = stream.ToArray();
            stream.Close();

            return(response);
        }
예제 #31
0
        public byte[] Encode()
        {
            var           stream   = new MemoryStream();
            Asn1Generator sequence = new DerSequenceGenerator(stream);

            // Counter (We don't populate the value, the PACSAM does)
            sequence.AddObject(new DerInteger(0));

            // Operation
            sequence.AddObject(new DerEnumerated(OperationCode));

            // Request Parameters (OPTIONAL)
            EncodeParameters(sequence);

            // Done
            sequence.Close();
            return(stream.ToArray());
        }
예제 #32
0
		public void TestNestedDerWriting()
        {
            MemoryStream bOut = new MemoryStream();
            DerSequenceGenerator seqGen1 = new DerSequenceGenerator(bOut);

			seqGen1.AddObject(new DerInteger(BigInteger.Zero));

			seqGen1.AddObject(new DerObjectIdentifier("1.1"));

			DerSequenceGenerator seqGen2 = new DerSequenceGenerator(seqGen1.GetRawOutputStream());

			seqGen2.AddObject(new DerInteger(BigInteger.One));

			seqGen2.Close();

			seqGen1.Close();

			Assert.IsTrue(Arrays.AreEqual(nestedSeqData, bOut.ToArray()), "nested DER writing test failed.");
        }
예제 #33
0
        public void TestNestedExplicitTagDerWriting()
        {
            MemoryStream         bOut    = new MemoryStream();
            DerSequenceGenerator seqGen1 = new DerSequenceGenerator(bOut);

            seqGen1.AddObject(new DerInteger(BigInteger.Zero));

            seqGen1.AddObject(new DerObjectIdentifier("1.1"));

            DerSequenceGenerator seqGen2 = new DerSequenceGenerator(seqGen1.GetRawOutputStream(), 1, true);

            seqGen2.AddObject(new DerInteger(BigInteger.ValueOf(1)));

            seqGen2.Close();

            seqGen1.Close();

            Assert.IsTrue(Arrays.AreEqual(nestedSeqExpTagData, bOut.ToArray()), "nested explicit tagged DER writing test failed.");
        }
예제 #34
0
		public void TestNestedStructure()
		{
			MemoryStream bOut = new MemoryStream();

			BerSequenceGenerator sGen = new BerSequenceGenerator(bOut);

			sGen.AddObject(new DerObjectIdentifier(CmsObjectIdentifiers.CompressedData.Id));

			BerSequenceGenerator cGen = new BerSequenceGenerator(sGen.GetRawOutputStream(), 0, true);

			cGen.AddObject(new DerInteger(0));

			//
			// AlgorithmIdentifier
			//
			DerSequenceGenerator algGen = new DerSequenceGenerator(cGen.GetRawOutputStream());

			algGen.AddObject(new DerObjectIdentifier("1.2"));

			algGen.Close();

			//
			// Encapsulated ContentInfo
			//
			BerSequenceGenerator eiGen = new BerSequenceGenerator(cGen.GetRawOutputStream());

			eiGen.AddObject(new DerObjectIdentifier("1.1"));

			BerOctetStringGenerator octGen = new BerOctetStringGenerator(eiGen.GetRawOutputStream(), 0, true);

			//
			// output containing zeroes
			//
			Stream outStream = octGen.GetOctetOutputStream();

			outStream.Write(new byte[] { 1, 2, 3, 4 }, 0, 4);
			outStream.Write(new byte[4], 0, 4);
			outStream.Write(new byte[20], 0, 20);

			outStream.Close();
			eiGen.Close();
			cGen.Close();
			sGen.Close();

			//
			// reading back
			//
			Asn1StreamParser aIn = new Asn1StreamParser(bOut.ToArray());

			ContentInfoParser cp = new ContentInfoParser((Asn1SequenceParser)aIn.ReadObject());

			CompressedDataParser comData = new CompressedDataParser((Asn1SequenceParser)cp.GetContent(Asn1Tags.Sequence));
			ContentInfoParser content = comData.GetEncapContentInfo();

			Asn1OctetStringParser bytes = (Asn1OctetStringParser)content.GetContent(Asn1Tags.OctetString);

			Stream inStream = bytes.GetOctetStream();
			int count = 0;

			while (inStream.ReadByte() >= 0)
			{
				count++;
			}

			Assert.AreEqual(28, count);
		}
예제 #35
0
 protected internal MemoryStream DerByteStream()
 {
     // Usually 70-72 bytes.
     MemoryStream bos = new MemoryStream(72);
     DerSequenceGenerator seq = new DerSequenceGenerator(bos);
     seq.AddObject(new DerInteger(R));
     seq.AddObject(new DerInteger(S));
     seq.Close();
     return bos;
 }