ToByteArrayUnsigned() public méthode

public ToByteArrayUnsigned ( ) : byte[]
Résultat byte[]
 private SrpConstants(string hexN, string decG)
 {
     N = new BigInteger(hexN, 16);
     Nb = N.ToByteArrayUnsigned();
     g = new BigInteger(decG, 10);
     gb = g.ToByteArrayUnsigned();
     kb = ComputeHash(Nb, gb);
     k = new BigInteger(1, kb);
     kb2 = Xor(ComputeHash(Nb), ComputeHash(gb));
 }
        /// <summary>
        /// Generates a KeyPair using a BigInteger as a private key.
        /// BigInteger is checked for appropriate range.
        /// </summary>
        public KeyPair(BigInteger bi, bool compressed = false, byte addressType = 0)
        {
            this.IsCompressedPoint = compressed;
            this.AddressType = addressType;

            var ps = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp256k1");
            if (bi.CompareTo(ps.N) >= 0 || bi.SignValue <= 0) {
                throw new ArgumentException("BigInteger is out of range of valid private keys");
            }
            byte[] bb = Util.Force32Bytes(bi.ToByteArrayUnsigned());
            PrivateKeyBytes = bb;
        }
		internal static void Encode(
			BcpgOutputStream	bcpgOut,
			BigInteger			val)
		{
			bcpgOut.WriteShort((short) val.BitLength);
			bcpgOut.Write(val.ToByteArrayUnsigned());
		}
		public ECPrivateKeyStructure(
            BigInteger key)
        {
			this.seq = new DerSequence(
				new DerInteger(1),
				new DerOctetString(key.ToByteArrayUnsigned()));
        }
		public ECPrivateKeyStructure(
			BigInteger key)
		{
			if (key == null)
				throw new ArgumentNullException("key");

			this.seq = new DerSequence(
				new DerInteger(1),
				new DerOctetString(key.ToByteArrayUnsigned()));
		}
 private static Byte[] ConvertRsaParametersField(BigInteger n, Int32 size)
 {
     var byteArrayUnsigned = n.ToByteArrayUnsigned();
     if (byteArrayUnsigned.Length == size)
         return byteArrayUnsigned;
     if (byteArrayUnsigned.Length > size)
         throw new ArgumentException("Specified size too small", nameof(size));
     var numArray = new Byte[size];
     Array.Copy(byteArrayUnsigned, 0, numArray, size - byteArrayUnsigned.Length, byteArrayUnsigned.Length);
     return numArray;
 }
Exemple #7
0
 public void TestAddBigInt()
 {
     BlobBuilder builder = new BlobBuilder();
       BigInteger value = new BigInteger("12398259028592293582039293420948023");
       builder.AddBigIntBlob(value);
       byte[] valueBytes = value.ToByteArrayUnsigned();
       //Assert.That(valueBytes[0], Is.EqualTo(0));
       byte[] expected = new byte[valueBytes.Length + 4];
       Array.Copy(valueBytes.Length.ToBytes(), expected, 4);
       Array.Copy(valueBytes, 0, expected, 4, valueBytes.Length);
       Assert.That(builder.GetBlob(), Is.EqualTo(expected));
 }
        /**
         * Return the passed in value as an unsigned byte array of specified length, zero-extended as necessary.
         *
         * @param length desired length of result array.
         * @param n value to be converted.
         * @return a byte array of specified length, with leading zeroes as necessary given the size of n.
         */
        public static byte[] AsUnsignedByteArray(int length, BigInteger n)
        {
            byte[] bytes = n.ToByteArrayUnsigned();

            if (bytes.Length > length)
                throw new ArgumentException("standard length exceeded", "n");

            if (bytes.Length == length)
                return bytes;

            byte[] tmp = new byte[length];
            Array.Copy(bytes, 0, tmp, tmp.Length - bytes.Length, bytes.Length);
            return tmp;
        }
        public ECPrivateKeyStructure(
            BigInteger key)
        {
            //            byte[] bytes = key.ToByteArray();
            //
            //			if (bytes[0] == 0)
            //            {
            //                byte[] tmp = new byte[bytes.Length - 1];
            //                Array.Copy(bytes, 1, tmp, 0, tmp.Length);
            //                bytes = tmp;
            //            }
            byte[] bytes = key.ToByteArrayUnsigned();

            seq = new DerSequence(new DerInteger(1), new DerOctetString(bytes));
        }
Exemple #10
0
        private static ECDsa LoadPrivateKey(byte[] key)
        {
            var privKeyInt = new Org.BouncyCastle.Math.BigInteger(+1, key);
            var parameters = SecNamedCurves.GetByName("secp256r1");
            var ecPoint    = parameters.G.Multiply(privKeyInt);
            var privKeyX   = ecPoint.Normalize().XCoord.ToBigInteger().ToByteArrayUnsigned();
            var privKeyY   = ecPoint.Normalize().YCoord.ToBigInteger().ToByteArrayUnsigned();

            return(ECDsa.Create(new ECParameters
            {
                Curve = ECCurve.NamedCurves.nistP256,
                D = privKeyInt.ToByteArrayUnsigned(),
                Q = new ECPoint
                {
                    X = privKeyX,
                    Y = privKeyY
                }
            }));
        }
		public static byte[] IntegerToBytes(
            BigInteger	s,
            int			qLength)
        {
			// TODO Add methods to allow writing BigInteger to existing byte array?
			byte[] bytes = s.ToByteArrayUnsigned();

			if (bytes.Length > qLength)
				throw new ArgumentException("s does not fit in specified number of bytes", "s");

			if (qLength > bytes.Length)
            {
                byte[] tmp = new byte[qLength];
                Array.Copy(bytes, 0, tmp, tmp.Length - bytes.Length, bytes.Length);
                return tmp;
            }

			return bytes;
        }
        public static byte[] IntegerToBytes(BigInteger s, int qLength)
        {
            byte[] bytes = s.ToByteArrayUnsigned();

            if (qLength < bytes.Length)
            {
                byte[] tmp = new byte[qLength];
                Array.Copy(bytes, bytes.Length - tmp.Length, tmp, 0, tmp.Length);
                return tmp;
            }
            else if (qLength > bytes.Length)
            {
                byte[] tmp = new byte[qLength];
                Array.Copy(bytes, 0, tmp, tmp.Length - bytes.Length, bytes.Length);
                return tmp;
            }

            return bytes;
        }
Exemple #13
0
        public byte[] ConvertOutput(
			BigInteger result)
        {
            byte[] output = result.ToByteArrayUnsigned();

            if (forEncryption)
            {
                int outSize = GetOutputBlockSize();

                // TODO To avoid this, create version of BigInteger.ToByteArray that
                // writes to an existing array
                if (output.Length < outSize) // have ended up with less bytes than normal, lengthen
                {
                    byte[] tmp = new byte[outSize];
                    output.CopyTo(tmp, tmp.Length - output.Length);
                    output = tmp;
                }
            }

            return output;
        }
        public ECPrivateKeyStructure(
            BigInteger		key,
            DerBitString	publicKey,
            Asn1Encodable	parameters)
        {
            if (key == null)
                throw new ArgumentNullException("key");

            Asn1EncodableVector v = new Asn1EncodableVector(
                new DerInteger(1),
                new DerOctetString(key.ToByteArrayUnsigned()));

            if (parameters != null)
            {
                v.Add(new DerTaggedObject(true, 0, parameters));
            }

            if (publicKey != null)
            {
                v.Add(new DerTaggedObject(true, 1, publicKey));
            }

            this.seq = new DerSequence(v);
        }
        public static ECPoint ECDSA_SIG_recover_key_GFp(BigInteger[] sig, byte[] hash, int recid, bool check)
        {
            X9ECParameters ecParams = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp256k1");
            int i = recid / 2;

            Console.WriteLine("r: "+ToHex(sig[0].ToByteArrayUnsigned()));
            Console.WriteLine("s: "+ToHex(sig[1].ToByteArrayUnsigned()));

            BigInteger order = ecParams.N;
            BigInteger field = (ecParams.Curve as FpCurve).Q;
            BigInteger x = order.Multiply(new BigInteger(i.ToString())).Add(sig[0]);
            if (x.CompareTo(field) >= 0) throw new Exception("X too large");

            Console.WriteLine("Order: "+ToHex(order.ToByteArrayUnsigned()));
            Console.WriteLine("Field: "+ToHex(field.ToByteArrayUnsigned()));

            byte[] compressedPoint = new Byte[x.ToByteArrayUnsigned().Length+1];
            compressedPoint[0] = (byte) (0x02+(recid%2));
            Buffer.BlockCopy(x.ToByteArrayUnsigned(), 0, compressedPoint, 1, compressedPoint.Length-1);
            ECPoint R = ecParams.Curve.DecodePoint(compressedPoint);

            Console.WriteLine("R: "+ToHex(R.GetEncoded()));

            if (check)
            {
                ECPoint O = R.Multiply(order);
                if (!O.IsInfinity) throw new Exception("Check failed");
            }

            int n = (ecParams.Curve as FpCurve).Q.ToByteArrayUnsigned().Length*8;
            BigInteger e = new BigInteger(1, hash);
            if (8*hash.Length > n)
            {
                e = e.ShiftRight(8-(n & 7));
            }
            e = BigInteger.Zero.Subtract(e).Mod(order);
            BigInteger rr = sig[0].ModInverse(order);
            BigInteger sor = sig[1].Multiply(rr).Mod(order);
            BigInteger eor = e.Multiply(rr).Mod(order);
            ECPoint Q = ecParams.G.Multiply(eor).Add(R.Multiply(sor));

            Console.WriteLine("n: "+n);
            Console.WriteLine("e: "+ToHex(e.ToByteArrayUnsigned()));
            Console.WriteLine("rr: "+ToHex(rr.ToByteArrayUnsigned()));
            Console.WriteLine("sor: "+ToHex(sor.ToByteArrayUnsigned()));
            Console.WriteLine("eor: "+ToHex(eor.ToByteArrayUnsigned()));
            Console.WriteLine("Q: "+ToHex(Q.GetEncoded()));

            return Q;
        }
Exemple #16
0
 /// <summary>
 /// Adds byte[] to builder as Ssh1 sub-blob
 /// </summary>
 /// <param name="blob"></param>
 public void AddSsh1BigIntBlob(BigInteger aBigInt)
 {
     ushort size = (ushort)(aBigInt.BitLength);
     AddByte((byte)((size >> 8) & 0xFF));
     AddByte((byte)(size & 0xFF));
     byte[] bytes = aBigInt.ToByteArrayUnsigned();
     byteList.AddRange(bytes);
 }
 /**
 * Return the passed in value as an unsigned byte array.
 *
 * @param value value to be converted.
 * @return a byte array without a leading zero byte if present in the signed encoding.
 */
 public static byte[] AsUnsignedByteArray(
     BigInteger n)
 {
     return n.ToByteArrayUnsigned();
 }
Exemple #18
0
        public void TestAddSsh1BigIntBlob()
        {
            BlobBuilder builder = new BlobBuilder();
              BigInteger value = new BigInteger("12398259028592293582039293420948023");
              builder.AddSsh1BigIntBlob(value);
              byte[] valueBytes = value.ToByteArrayUnsigned();
              byte[] expected = new byte[valueBytes.Length + 2];

              ushort size = (ushort)(value.BitLength);
              expected[0] = (byte)((size >> 8) & 0xFF);
              expected[1] = (byte)(size & 0xFF);

              Array.Copy(valueBytes, 0, expected, 2, valueBytes.Length);
              Assert.That(builder.GetBlob(), Is.EqualTo(expected));
        }
        /// <summary>
        /// Generate a set of M-of-N parts for a specific private key.
        /// If desiredPrivKey is null, then a random key will be selected.
        /// </summary>
        public void Generate(int PartsNeededToDecode, int PartsToGenerate, byte[] desiredPrivKey)
        {
            if (PartsNeededToDecode > PartsToGenerate) {
                throw new ApplicationException("Number of parts needed exceeds number of parts to generate.");
            }

            if (PartsNeededToDecode > 8 || PartsToGenerate > 8) {
                throw new ApplicationException("Maximum number of parts is 8");
            }

            if (PartsNeededToDecode < 1 || PartsToGenerate < 1) {
                throw new ApplicationException("Minimum number of parts is 1");
            }

            if (desiredPrivKey != null && desiredPrivKey.Length != 32) {
                throw new ApplicationException("Desired private key must be 32 bytes");
            }

            KeyParts.Clear();
            decodedKeyParts.Clear();

            SecureRandom sr = new SecureRandom();

            // Get 8 random big integers into v[i].
            byte[][] vvv = new byte[8][];
            BigInteger[] v = new BigInteger[8];

            for (int i = 0; i < 8; i++) {
                byte[] b = new byte[32];
                sr.NextBytes(b, 0, 32);
                // For larger values of i, chop off some most-significant-bits to prevent overflows as they are
                // multiplied with increasingly larger factors.
                if (i >= 7) {
                    b[0] &= 0x7f;
                }
                v[i] = new BigInteger(1, b);
                Debug.WriteLine(String.Format("v({0})={1}", i, v[i].ToString()));

            }

            // if a certain private key is desired, then specify it.
            if (desiredPrivKey != null) {
                // replace v[0] with xor(v[1...7]) xor desiredPrivKey
                BigInteger newv0 = BigInteger.Zero;
                for (int i=1; i<PartsNeededToDecode; i++) {
                    newv0 = newv0.Xor(v[i]);
                }
                v[0] = newv0.Xor(new BigInteger(1,desiredPrivKey));

            }

            // Generate the expected private key from all the parts
            BigInteger privkey = new BigInteger("0");
            for (int i = 0; i < PartsNeededToDecode; i++) {
                privkey = privkey.Xor(v[i]);
            }

            // Get the bitcoin address
            byte[] keybytes = privkey.ToByteArrayUnsigned();
            // make sure we have 32 bytes, we'll need it
            if (keybytes.Length < 32) {
                byte[] array32 = new byte[32];
                Array.Copy(keybytes, 0, array32, 32 - keybytes.Length, keybytes.Length);
                keybytes = array32;
            }
            KeyPair = new KeyPair(keybytes);

            byte[] checksum = Util.ComputeSha256(BitcoinAddress);

            // Generate the parts
            for (int i = 0; i < PartsToGenerate; i++) {
                BigInteger total = new BigInteger("0");
                for (int j = 0; j < PartsNeededToDecode; j++) {

                    int factor = 1;
                    for (int ii = 0; ii <= i; ii++) factor = factor * (j + 1);

                    BigInteger bfactor = new BigInteger(factor.ToString());

                    total = total.Add(v[j].Multiply(bfactor));
                }

                Debug.WriteLine(String.Format(" pc{0}={1}", i, total.ToString()));
                byte[] parts = new byte[39];
                parts[0] = 0x4f;
                parts[1] = (byte)(0x93 + PartsNeededToDecode);
                int parts23 = (((checksum[0] << 8) + checksum[1]) & 0x1ff);
                Debug.WriteLine("checksum " + parts23.ToString());
                parts23 += 0x6000;
                parts23 += (i << 9);
                byte[] btotal = total.ToByteArrayUnsigned();
                for (int jj = 0; jj < btotal.Length; jj++) {
                    parts[jj + 4 + (35 - btotal.Length)] = btotal[jj];
                }

                parts[2] = (byte)((parts23 & 0xFF00) >> 8);
                parts[3] = (byte)(parts23 & 0xFF);

                KeyParts.Add(Util.ByteArrayToBase58Check(parts));
                decodedKeyParts.Add(parts);
            }
        }
		// TODO Move functionality to more general class
		private static byte[] ConvertRSAParametersField(BigInteger n, int size)
		{
			byte[] bs = n.ToByteArrayUnsigned();

			if (bs.Length == size)
				return bs;

			if (bs.Length > size)
				throw new ArgumentException("Specified size too small", "size");

			byte[] padded = new byte[size];
			Array.Copy(bs, 0, padded, size - bs.Length, bs.Length);
			return padded;
		}
 private static void UpdateDigest(IDigest d, BigInteger b)
 {
     byte[] bytes = b.ToByteArrayUnsigned();
     d.BlockUpdate(bytes, 0, bytes.Length);
 }
Exemple #22
0
 public static string BigHex(BigInteger pub)
 {
     return Hex.ToHexString(pub.ToByteArrayUnsigned()).ToUpper();
 }
Exemple #23
0
 public static byte[] FromBigNum(Org.BouncyCastle.Math.BigInteger bi)
 {
     byte[] rgbT = bi.ToByteArrayUnsigned();
     return(rgbT);
 }
Exemple #24
0
        //Following code from https://bitcointalk.org/index.php?topic=25141.0

        public static byte[] Base58ToByteArray(string base58)
        {
            Org.BouncyCastle.Math.BigInteger bi2 = new Org.BouncyCastle.Math.BigInteger("0");
            string b58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";

            bool IgnoreChecksum = false;

            foreach (char c in base58)
            {
                if (b58.IndexOf(c) != -1)
                {
                    bi2 = bi2.Multiply(new Org.BouncyCastle.Math.BigInteger("58"));
                    bi2 = bi2.Add(new Org.BouncyCastle.Math.BigInteger(b58.IndexOf(c).ToString()));
                }
                else if (c == '?')
                {
                    IgnoreChecksum = true;
                }
                else
                {
                    return(null);
                }
            }

            byte[] bb = bi2.ToByteArrayUnsigned();

            // interpret leading '1's as leading zero bytes
            foreach (char c in base58)
            {
                if (c != '1')
                {
                    break;
                }
                byte[] bbb = new byte[bb.Length + 1];
                Array.Copy(bb, 0, bbb, 1, bb.Length);
                bb = bbb;
            }

            if (bb.Length < 4)
            {
                return(null);
            }

            if (IgnoreChecksum == false)
            {
                SHA256CryptoServiceProvider sha256 = new SHA256CryptoServiceProvider();
                byte[] checksum = sha256.ComputeHash(bb, 0, bb.Length - 4);
                checksum = sha256.ComputeHash(checksum);
                for (int i = 0; i < 4; i++)
                {
                    if (checksum[i] != bb[bb.Length - 4 + i])
                    {
                        return(null);
                    }
                }
            }

            byte[] rv = new byte[bb.Length - 4];
            Array.Copy(bb, 0, rv, 0, bb.Length - 4);
            return(rv);
        }
        public override Key GetKey(string password)
        {
            var encrypted = PartialEncrypted.ToArray();
            //Derive passfactor using scrypt with ownerentropy and the user's passphrase and use it to recompute passpoint
            byte[] passfactor = CalculatePassFactor(password,LotSequence, OwnerEntropy);
            var passpoint = CalculatePassPoint(passfactor);

            var derived = SCrypt.BitcoinComputeDerivedKey2(passpoint, this.AddressHash.Concat(this.OwnerEntropy).ToArray());

            //Decrypt encryptedpart1 to yield the remainder of seedb.
            var seedb = BitcoinEncryptedSecret.DecryptSeed(encrypted, derived);
            var factorb = Hashes.Hash256(seedb).ToBytes();

            var curve = ECKey.CreateCurve();

            //Multiply passfactor by factorb mod N to yield the private key associated with generatedaddress.
            var keyNum = new BigInteger(1, passfactor).Multiply(new BigInteger(1, factorb)).Mod(curve.N);
            var keyBytes = keyNum.ToByteArrayUnsigned();
            if(keyBytes.Length < 32)
                keyBytes = new byte[32 - keyBytes.Length].Concat(keyBytes).ToArray();

            var key = new Key(keyBytes, fCompressedIn: IsCompressed);

            var generatedaddress = key.PubKey.GetAddress(Network);
            var addresshash = HashAddress(generatedaddress);

            if(!Utils.ArrayEqual(addresshash, AddressHash))
                throw new SecurityException("Invalid password");

            return key;
        }