DoFinal() public method

public DoFinal ( byte output, int outOff ) : int
output byte
outOff int
return int
コード例 #1
0
        /// <summary>
        /// Converts a base-58 string to a byte array, checking the checksum, and
        /// returning null if it wasn't valid.  Appending "?" to the end of the string skips
        /// the checksum calculation, but still strips the four checksum bytes from the
        /// result.
        /// </summary>
        public static byte[] Base58CheckToByteArray(string base58)
        {
            bool IgnoreChecksum = false;
            if (base58.EndsWith("?")) {
                IgnoreChecksum = true;
                base58 = base58.Substring(0, base58.Length - 1);
            }

            byte[] bb = Base58.ToByteArray(base58);
            if (bb == null || bb.Length < 4) return null;

            if (IgnoreChecksum == false) {
                Sha256Digest bcsha256a = new Sha256Digest();
                bcsha256a.BlockUpdate(bb, 0, bb.Length - 4);

                byte[] checksum = new byte[32];  //sha256.ComputeHash(bb, 0, bb.Length - 4);
                bcsha256a.DoFinal(checksum, 0);
                bcsha256a.BlockUpdate(checksum, 0, 32);
                bcsha256a.DoFinal(checksum, 0);

                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;
        }
コード例 #2
0
        /// <summary>
        /// Default constructor.  Creates a new matched pair of escrow invitation codes.
        /// </summary>
        public EscrowCodeSet()
        {
            SecureRandom sr = new SecureRandom();

            byte[] x = new byte[32];
            byte[] y = new byte[32];
            sr.NextBytes(x);
            sr.NextBytes(y);

            // Force x to be even
            // Force y to be odd
            x[31] &= 0xFE;
            y[31] |= 0x01;

            KeyPair kx = new KeyPair(x, true);
            KeyPair ky = new KeyPair(y, true);

            BigInteger xi = new BigInteger(1, x);
            BigInteger yi = new BigInteger(1, y);

            ECPoint Gx = kx.GetECPoint();
            byte[] bytesGx = Gx.GetEncoded();
            ECPoint Gy = ky.GetECPoint();
            byte[] bytesGy = Gy.GetEncoded();
            ECPoint Gxy = Gx.Multiply(yi);

            byte[] bytesGxy = Gxy.GetEncoded();
            Sha256Digest sha256 = new Sha256Digest();
            byte[] hashGxy = new byte[32];
            sha256.BlockUpdate(bytesGxy, 0, bytesGxy.Length);
            sha256.DoFinal(hashGxy, 0);
            sha256.BlockUpdate(hashGxy, 0, 32);
            sha256.DoFinal(hashGxy, 0);

            int identifier30 = ((hashGxy[0] & 0x3f) << 24) + (hashGxy[1] << 16) + (hashGxy[2] << 8) + hashGxy[3];

            byte[] invitationA = new byte[74];
            byte[] invitationB = new byte[74];

            long headA = headbaseA + (long)identifier30;
            long headB = headbaseB + (long)identifier30;

            // turn headA and headB into bytes
            for (int i = 7; i >= 0; i--) {
                invitationA[i] = (byte)(headA & 0xFF);
                invitationB[i] = (byte)(headB & 0xFF);
                headA >>= 8;
                headB >>= 8;
            }

            Array.Copy(x, 0, invitationA, 8 + 1, 32);
            Array.Copy(y, 0, invitationB, 8 + 1, 32);
            Array.Copy(bytesGy, 0, invitationA, 8 + 1 + 32, 33);
            Array.Copy(bytesGx, 0, invitationB, 8 + 1 + 32, 33);

            EscrowInvitationCodeA = Util.ByteArrayToBase58Check(invitationA);
            EscrowInvitationCodeB = Util.ByteArrayToBase58Check(invitationB);
        }
コード例 #3
0
	public static byte[] SHA256_SHA256(byte[] ba) {
		Sha256Digest bcsha256a = new Sha256Digest();
        bcsha256a.BlockUpdate(ba, 0, ba.Length);
		byte[] thehash = new byte[32];
        bcsha256a.DoFinal(thehash, 0);
        bcsha256a.BlockUpdate(thehash, 0, 32);
        bcsha256a.DoFinal(thehash, 0);
        return thehash;
	}
コード例 #4
0
    private static string GetHashDigest(Org.BouncyCastle.Crypto.Digests.Sha256Digest hash)
    {
        var digest = new byte[hash.GetDigestSize()];

        hash.DoFinal(digest, 0);
        return(BitConverter.ToString(digest).Replace("-", string.Empty).ToLower());
    }
コード例 #5
0
 /**
  * Hashes the given data.
  *
  * @param data The data to hash
  * @return byte-array containing the hashed data
  */
 public static byte[] Hash(byte[] data)
 {
     Sha256Digest sha256 = new Sha256Digest();
     sha256.BlockUpdate(data, 0, data.Length);
     byte[] hash = new byte[sha256.GetDigestSize()];
     sha256.DoFinal(hash, 0);
     return hash;
 }
コード例 #6
0
ファイル: Helpers.cs プロジェクト: lukedoolittle/telehash.net
		public static byte[] SHA256Hash(byte[] data)
		{
			var shaHash = new Sha256Digest ();
			shaHash.BlockUpdate (data, 0, data.Length);
			byte[] hashedValue = new byte[shaHash.GetDigestSize ()];
			shaHash.DoFinal(hashedValue, 0);
			return hashedValue;
		}
コード例 #7
0
ファイル: Hash.cs プロジェクト: DavidSimner/u2f
        public static byte[] Array(byte[] value)
        {
            var digest = new Sha256Digest();
            digest.BlockUpdate(value, 0, value.Length);

            var ret = new byte[digest.GetDigestSize()];
            digest.DoFinal(ret, 0);
            return ret;
        }
コード例 #8
0
ファイル: MATEncryption.cs プロジェクト: erosh/sdk-release
 public static string Sha256(string input)
 {
     var data = System.Text.Encoding.UTF8.GetBytes(input);
     Sha256Digest hash = new Sha256Digest();
     hash.BlockUpdate(data, 0, data.Length);
     byte[] result = new byte[hash.GetDigestSize()];
     hash.DoFinal(result, 0);
     return Hex.ToHexString(result);
 }
コード例 #9
0
ファイル: SHA256.cs プロジェクト: elitak/keepass
        public byte[] ComputeHash(byte[] pbData)
        {
            Sha256Digest sha256 = new Sha256Digest();
            sha256.BlockUpdate(pbData, 0, pbData.Length);

            byte[] pbHash = new byte[32];
            sha256.DoFinal(pbHash, 0);

            return pbHash;
        }
コード例 #10
0
ファイル: Utility.cs プロジェクト: heliocentric/simplemesh
        public static String SHA256(string tosha256)
        {
            Sha256Digest digest = new Sha256Digest();
            byte[] scratch = new byte[digest.GetDigestSize()];
            digest.BlockUpdate(UTF8Encoding.UTF8.GetBytes(tosha256), 0, UTF8Encoding.UTF8.GetByteCount(tosha256));
            digest.DoFinal(scratch, 0);

            string hex = BitConverter.ToString(scratch).ToLower();
            return hex.Replace("-", "");
        }
コード例 #11
0
ファイル: Helpers.cs プロジェクト: kavallo/fido-u2f-net
        public static byte[] Sha256(string text)
        {
            var bytes = new byte[text.Length * sizeof(char)];
            Buffer.BlockCopy(text.ToCharArray(), 0, bytes, 0, bytes.Length);

            var sha256 = new Sha256Digest();
            var hash = new byte[sha256.GetDigestSize()];
            sha256.BlockUpdate(bytes, 0, bytes.Length);
            sha256.DoFinal(hash, 0);
            return hash;
        }
コード例 #12
0
 private static string GetFileName(string imageUri)
 {
     var sha = new Sha256Digest();
     var stream = new DigestStream(new MemoryStream(), null, sha);
     using (var writer = new StreamWriter(stream))
     {
         writer.Write(imageUri);
     }
     byte[] buffer = new byte[sha.GetDigestSize()];
     sha.DoFinal(buffer, 0);
     string hex = BitConverter.ToString(buffer);
     string fileName = hex.Replace("-", "");
     return fileName;
 }
コード例 #13
0
    public string GetSign(byte[] msg)
    {
        //Org.BouncyCastle.Math.BigInteger d = new Org.BouncyCastle.Math.BigInteger(Convert.FromBase64String(privKey));
        byte[] prvB = StringToByteArray(prv);
        byte[] pubB = StringToByteArray(pub);
        //byte[] prvB = StringToByteArray(prvTmp);
        //byte[] pubB = StringToByteArray(pubTmp);
        Org.BouncyCastle.Math.BigInteger sk = new Org.BouncyCastle.Math.BigInteger(+1, prvB);
        Org.BouncyCastle.Math.EC.ECPoint q  = domain.G.Multiply(sk);

        byte[]     pubKeyX = q.Normalize().AffineXCoord.GetEncoded();
        byte[]     pubKeyY = q.Normalize().AffineYCoord.GetEncoded();
        BigInteger k       = GenerateRandom();

        //BigInteger k = new BigInteger(+1,StringToByteArray("015B931D9C7BF3A7A70E57868BF29712377E74355FC59032CD7547C80E179010"));
        //Debug.Log("kv:" + BitConverter.ToString(kv.ToByteArray()).Replace("-", ""));
        Debug.Log("K:" + BitConverter.ToString(k.ToByteArray()).Replace("-", ""));
        ECPoint Q = domain.G.Multiply(k);

        Org.BouncyCastle.Crypto.Digests.Sha256Digest digester = new Org.BouncyCastle.Crypto.Digests.Sha256Digest();
        byte[] h = new byte[digester.GetDigestSize()];

        digester.BlockUpdate(Q.GetEncoded(true), 0, Q.GetEncoded(true).Length);
        digester.BlockUpdate(pubB, 0, pubB.Length);
        digester.BlockUpdate(msg, 0, msg.Length);

        digester.DoFinal(h, 0);

        Org.BouncyCastle.Math.BigInteger r = new Org.BouncyCastle.Math.BigInteger(+1, h);

        BigInteger s = r.Multiply(sk);

        s = k.Subtract(s);
        s = s.Mod(domain.n);
        string rt = BitConverter.ToString(r.ToByteArray()).Replace("-", "");

        if (rt.Length > 32)
        {
            rt = rt.Remove(0, 2);
        }
        string st = BitConverter.ToString(s.ToByteArray()).Replace("-", "");

        return(rt + st);
    }
コード例 #14
0
		/// <summary>
		/// From a single given key create a hashname with the intermediate hashes of other keys
		/// </summary>
		/// <returns>The key.</returns>
		/// <param name="csid">The identifier for the cipher set as a string.</param>
		/// <param name="keyData">The key data for the given csid.</param>
		/// <param name="intermediates">Intermediates.</param>
		public static string FromKey(string csid, byte[] keyData, IDictionary<string, string> intermediates)
		{
			Sha256Digest digest = new Sha256Digest ();
			List<string> keys = new List<string>(intermediates.Keys);
			keys.Add (csid);
			keys.Sort ();

			int digestSize = digest.GetDigestSize ();
			byte[] outhash = null;
			foreach (var key in keys) {
				if (outhash != null) {
					digest.BlockUpdate (outhash, 0, digestSize);
				} else {
					outhash = new byte[digestSize];
				}
				byte inByte;
				try {
					inByte = Convert.ToByte (key, 16);
				} catch(FormatException) {
					return null;
				} catch(OverflowException) {
					return null;
				} catch (ArgumentException) {
					return null;
				}
				digest.Update (inByte);
				digest.DoFinal (outhash, 0);
				digest.Reset ();

				digest.BlockUpdate (outhash, 0, digestSize);
				if (key == csid) {
					Sha256Digest keyDigest = new Sha256Digest ();
					keyDigest.BlockUpdate (keyData, 0, keyData.Length);
					keyDigest.DoFinal (outhash, 0);
					digest.BlockUpdate (outhash, 0, outhash.Length);
				} else {
					byte[] keyIntermediate = Base32Encoder.Decode (intermediates [key]);
					digest.BlockUpdate (keyIntermediate, 0, keyIntermediate.Length);
				}
				digest.DoFinal (outhash, 0);
			}
			return Base32Encoder.Encode (outhash).TrimEnd(trimChars).ToLower();
		}
コード例 #15
0
        public static string HashSomething(string password, string something)
        {
            var dig = new Sha256Digest();
            byte[] bpassword = Encoding.UTF8.GetBytes(password);
            dig.BlockUpdate(bpassword, 0, bpassword.Length);
            var key = new byte[dig.GetDigestSize()];
            dig.DoFinal(key, 0);

            var hmac = new HMac(new Sha256Digest());
            hmac.Init(new KeyParameter(key));
            byte[] input = Encoding.UTF8.GetBytes(something);
            hmac.BlockUpdate(input, 0, input.Length);
            var output = new byte[hmac.GetMacSize()];
            hmac.DoFinal(output, 0);

            var sb = new StringBuilder(output.Length*2);
            foreach (byte b in output)
            {
                sb.AppendFormat("{0:x2}", b);
            }
            return sb.ToString();
        }
コード例 #16
0
		public ITestResult Perform()
        {
            IDigest digest = new Sha256Digest();
            byte[] resBuf = new byte[digest.GetDigestSize()];
            string resStr;

			//
            // test 1
            //
            digest.DoFinal(resBuf, 0);

            resStr = Hex.ToHexString(resBuf);
            if (!resVec1.Equals(resStr))
            {
                return new SimpleTestResult(false,
                    "SHA-256 failing standard vector test 1"
                    + SimpleTest.NewLine
                    + "    expected: " + resVec1
                    + SimpleTest.NewLine
                    + "    got     : " + resStr);
            }

            //
            // test 2
            //
            byte[]  bytes = Hex.Decode(testVec2);

            digest.BlockUpdate(bytes, 0, bytes.Length);

            digest.DoFinal(resBuf, 0);

            resStr = Hex.ToHexString(resBuf);
            if (!resVec2.Equals(resStr))
            {
                return new SimpleTestResult(false,
                    "SHA-256 failing standard vector test 2"
                    + SimpleTest.NewLine
                    + "    expected: " + resVec2
                    + SimpleTest.NewLine
                    + "    got     : " + resStr);
            }

            //
            // test 3
            //
            bytes = Hex.Decode(testVec3);

            digest.BlockUpdate(bytes, 0, bytes.Length);

            digest.DoFinal(resBuf, 0);

            resStr = Hex.ToHexString(resBuf);
            if (!resVec3.Equals(resStr))
            {
                return new SimpleTestResult(false,
                    "SHA-256 failing standard vector test 3"
                    + SimpleTest.NewLine
                    + "    expected: " + resVec3
                    + SimpleTest.NewLine
                    + "    got     : " + resStr);
            }

            //
            // test 4
            //
            bytes = Hex.Decode(testVec4);

            digest.BlockUpdate(bytes, 0, bytes.Length);

            digest.DoFinal(resBuf, 0);

            resStr = Hex.ToHexString(resBuf);
            if (!resVec4.Equals(resStr))
            {
                return new SimpleTestResult(false,
                    "SHA-256 failing standard vector test 4"
                    + SimpleTest.NewLine
                    + "    expected: " + resVec4
                    + SimpleTest.NewLine
                    + "    got     : " + resStr);
            }

            //
            // test 5
            //
            bytes = Hex.Decode(testVec4);

            digest.BlockUpdate(bytes, 0, bytes.Length/2);

            // clone the IDigest
            IDigest d = new Sha256Digest((Sha256Digest)digest);

            digest.BlockUpdate(bytes, bytes.Length/2, bytes.Length - bytes.Length/2);
            digest.DoFinal(resBuf, 0);

            resStr = Hex.ToHexString(resBuf);
            if (!resVec4.Equals(resStr))
            {
                return new SimpleTestResult(false,
                    "SHA-256 failing standard vector test 5"
                    + SimpleTest.NewLine
                    + "    expected: " + resVec4
                    + SimpleTest.NewLine
                    + "    got     : " + resStr);
            }

            d.BlockUpdate(bytes, bytes.Length/2, bytes.Length - bytes.Length/2);
            d.DoFinal(resBuf, 0);

            resStr = Hex.ToHexString(resBuf);
            if (!resVec4.Equals(resStr))
            {
                return new SimpleTestResult(false,
                    "SHA-256 failing standard vector test 5"
                    + SimpleTest.NewLine
                    + "    expected: " + resVec4
                    + SimpleTest.NewLine
                    + "    got     : " + resStr);
            }

            // test 6
            bytes = Hex.Decode(testVec5);
            for ( int i = 0; i < 100000; i++ )
            {
                digest.BlockUpdate(bytes, 0, bytes.Length);
            }
            digest.DoFinal(resBuf, 0);

            resStr = Hex.ToHexString(resBuf);
            if (!resVec5.Equals(resStr))
            {
                return new SimpleTestResult(false,
                    "SHA-256 failing standard vector test 6"
                    + SimpleTest.NewLine
                    + "    expected: " + resVec5
                    + SimpleTest.NewLine
                    + "    got     : " + resStr);
            }

            return new SimpleTestResult(true, Name + ": Okay");
        }
コード例 #17
0
 public static string ByteArrayToBase58Check(byte[] ba)
 {
     byte[] bb = new byte[ba.Length + 4];
     Array.Copy(ba, bb, ba.Length);
     Sha256Digest bcsha256a = new Sha256Digest();
     bcsha256a.BlockUpdate(ba, 0, ba.Length);
     byte[] thehash = new byte[32];
     bcsha256a.DoFinal(thehash, 0);
     bcsha256a.BlockUpdate(thehash, 0, 32);
     bcsha256a.DoFinal(thehash, 0);
     for (int i = 0; i < 4; i++) bb[ba.Length + i] = thehash[i];
     return Base58.FromByteArray(bb);
 }
コード例 #18
0
ファイル: Message.cs プロジェクト: Rustemt/rovermob
 private static byte[] ComputeHash(object document)
 {
     var sha = new Sha256Digest();
     var stream = new DigestStream(new MemoryStream(), null, sha);
     using (var writer = new StreamWriter(stream))
     {
         string mementoToString = JsonConvert.SerializeObject(document);
         writer.Write(mementoToString);
     }
     byte[] buffer = new byte[sha.GetDigestSize()];
     sha.DoFinal(buffer, 0);
     return buffer;
 }
コード例 #19
0
ファイル: SignHandler.cs プロジェクト: hgaard/OOAPI
        private static Boolean SignatureMatches(string encodedSignature, string encodedAgreement, string signTextTransformation, OpensignSignature opensignSignature)
        {
            if (!encodedAgreement.Equals(encodedSignature))
            {
                return false;
            }

            var stylesheetDigest = opensignSignature.StylesheetDigest;
            if (stylesheetDigest != null)
            {
                if (signTextTransformation == null)
                {
                    throw new ArgumentException("signTextTransformation is required for XML signing");
                }

                var digest = new Sha256Digest();
                var encode = new ASCIIEncoding();
                byte[] stylesheetBytes = encode.GetBytes(signTextTransformation);
                digest.BlockUpdate(stylesheetBytes, 0, stylesheetBytes.Length);
                var digestBytes = new byte[digest.GetDigestSize()];
                digest.DoFinal(digestBytes, 0);
                var calculatedDigest = Encoding.UTF8.GetString(digestBytes, 0, digestBytes.Length);

                return stylesheetDigest.Equals(calculatedDigest);
            }
            return true;
        }
コード例 #20
0
		private byte[] Hash(byte[] data)
		{
			var hash = new byte[32];
			var sha256 = new Sha256Digest();
			sha256.BlockUpdate(data, 0, data.Length);
			sha256.DoFinal(hash, 0);
			return hash;
		}
コード例 #21
0
		internal static byte[] GetCertificateAssocicationData(TlsaSelector selector, TlsaMatchingType matchingType, X509Certificate certificate)
		{
			byte[] selectedBytes;
			switch (selector)
			{
				case TlsaSelector.FullCertificate:
					selectedBytes = certificate.GetRawCertData();
					break;

				case TlsaSelector.SubjectPublicKeyInfo:
					selectedBytes = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(DotNetUtilities.FromX509Certificate(certificate).GetPublicKey()).GetDerEncoded();
					break;

				default:
					throw new NotSupportedException();
			}

			byte[] matchingBytes;
			switch (matchingType)
			{
				case TlsaMatchingType.Full:
					matchingBytes = selectedBytes;
					break;

				case TlsaMatchingType.Sha256Hash:
					Sha256Digest sha256Digest = new Sha256Digest();
					sha256Digest.BlockUpdate(selectedBytes, 0, selectedBytes.Length);
					matchingBytes = new byte[sha256Digest.GetDigestSize()];
					sha256Digest.DoFinal(matchingBytes, 0);
					break;

				case TlsaMatchingType.Sha512Hash:
					Sha512Digest sha512Digest = new Sha512Digest();
					sha512Digest.BlockUpdate(selectedBytes, 0, selectedBytes.Length);
					matchingBytes = new byte[sha512Digest.GetDigestSize()];
					sha512Digest.DoFinal(matchingBytes, 0);
					break;

				default:
					throw new NotSupportedException();
			}

			return matchingBytes;
		}
コード例 #22
0
 private bool verifyAddressHash(string addressBase58, byte[] hex)
 {
     // check address hash
     UTF8Encoding utf8 = new UTF8Encoding(false);
     Sha256Digest sha256 = new Sha256Digest();
     byte[] addrhash = new byte[32];
     byte[] addrtext = utf8.GetBytes(addressBase58);
     sha256.BlockUpdate(addrtext, 0, addrtext.Length);
     sha256.DoFinal(addrhash, 0);
     sha256.BlockUpdate(addrhash, 0, 32);
     sha256.DoFinal(addrhash, 0);
     if (addrhash[0] != hex[3] || addrhash[1] != hex[4] || addrhash[2] != hex[5] || addrhash[3] != hex[6]) {
         return false;
     }
     return true;
 }
コード例 #23
0
        private void btnVccVerifyConfirmationCode_Click(object sender, EventArgs e)
        {
            lblResult.Visible = false;

            // check for null entry
            if (tbxVccPassphrase.Text == "") {
                MessageBox.Show("Passphrase is required.", "Passphrase required", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            if (tbxVccConfirmationCode.Text == "") {
                MessageBox.Show("Confirmation code is required.", "Confirmation code required", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            // Parse confirmation code.
            byte[] confbytes = Util.Base58CheckToByteArray(tbxVccConfirmationCode.Text.Trim());
            if (confbytes == null) {
                // is it even close?
                if (tbxVccConfirmationCode.Text.StartsWith("cfrm38")) {
                    MessageBox.Show("This is not a valid confirmation code.  It has the right prefix, but " +
                        "doesn't contain valid confirmation data.  Possible typo or incomplete?",
                        "Invalid confirmation code", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }

                MessageBox.Show("This is not a valid confirmation code.", "Invalid confirmation code", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            if (confbytes.Length != 51 || confbytes[0] != 0x64 || confbytes[1] != 0x3B || confbytes[2] != 0xF6 ||
                confbytes[3] != 0xA8 || confbytes[4] != 0x9A || confbytes[18] < 0x02 || confbytes[18] > 0x03) {

                // Unrecognized Base58 object.  Do we know what this is?  Tell the user.
                object result = StringInterpreter.Interpret(tbxVccConfirmationCode.Text.Trim());
                if (result != null) {

                    // did we actually get an encrypted private key?  if so, just try to decrypt it.
                    if (result is PassphraseKeyPair) {
                        PassphraseKeyPair ppkp = result as PassphraseKeyPair;
                        if (ppkp.DecryptWithPassphrase(tbxVccPassphrase.Text)) {
                            confirmIsValid(ppkp.GetAddress().AddressBase58);
                            MessageBox.Show("What you provided contains a private key, not just a confirmation. " +
                                "Confirmation is successful, and with this correct passphrase, " +
                                "you are also able to spend the funds from the address.", "This is actually a private key",
                                MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return;
                        } else {
                            MessageBox.Show("This is not a valid confirmation code.  It looks like an " +
                                "encrypted private key.  Decryption was attempted but the passphrase couldn't decrypt it", "Invalid confirmation code", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                            return;
                        }
                    }

                    string objectKind = result.GetType().Name;
                    if (objectKind == "AddressBase") {
                        objectKind = "an Address";
                    } else {
                        objectKind = "a " + objectKind;
                    }

                    MessageBox.Show("This is not a valid confirmation code.  Instead, it looks like " + objectKind +
                      ".  Perhaps you entered the wrong thing?  Confirmation codes " +
                    "start with \"cfrm\".", "Invalid confirmation code", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }

                MessageBox.Show("This is not a valid confirmation code.", "Invalid confirmation code", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;

            }

            // extract ownersalt and get an intermediate
            byte[] ownersalt = new byte[8];
            Array.Copy(confbytes, 10, ownersalt, 0, 8);

            bool includeHashStep = (confbytes[5] & 0x04) == 0x04;
            Bip38Intermediate intermediate = new Bip38Intermediate(tbxVccPassphrase.Text, ownersalt, includeHashStep);

            // derive the 64 bytes we need
            // get ECPoint from passpoint
            PublicKey pk = new PublicKey(intermediate.passpoint);

            byte[] addresshashplusownersalt = new byte[12];
            Array.Copy(confbytes, 6, addresshashplusownersalt, 0, 4);
            Array.Copy(intermediate.ownerentropy, 0, addresshashplusownersalt, 4, 8);

            // derive encryption key material
            byte[] derived = new byte[64];
            SCrypt.ComputeKey(intermediate.passpoint, addresshashplusownersalt, 1024, 1, 1, 1, derived);

            byte[] derivedhalf2 = new byte[32];
            Array.Copy(derived, 32, derivedhalf2, 0, 32);

            byte[] unencryptedpubkey = new byte[33];
            // recover the 0x02 or 0x03 prefix
            unencryptedpubkey[0] = (byte)(confbytes[18] ^ (derived[63] & 0x01));

            // decrypt
            var aes = Aes.Create();
            aes.KeySize = 256;
            aes.Mode = CipherMode.ECB;
            aes.Key = derivedhalf2;
            ICryptoTransform decryptor = aes.CreateDecryptor();

            decryptor.TransformBlock(confbytes, 19, 16, unencryptedpubkey, 1);
            decryptor.TransformBlock(confbytes, 19, 16, unencryptedpubkey, 1);
            decryptor.TransformBlock(confbytes, 19 + 16, 16, unencryptedpubkey, 17);
            decryptor.TransformBlock(confbytes, 19 + 16, 16, unencryptedpubkey, 17);

            // xor out the padding
            for (int i = 0; i < 32; i++) unencryptedpubkey[i + 1] ^= derived[i];

            // reconstitute the ECPoint
            var ps = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp256k1");
            ECPoint point;
            try {
                point = ps.Curve.DecodePoint(unencryptedpubkey);

                // multiply passfactor.  Result is going to be compressed.
                ECPoint pubpoint = point.Multiply(new BigInteger(1, intermediate.passfactor));

                // Do we want it uncompressed?  then we will have to uncompress it.
                byte flagbyte = confbytes[5];
                if ((flagbyte & 0x20) == 0x00) {
                    pubpoint = ps.Curve.CreatePoint(pubpoint.X.ToBigInteger(), pubpoint.Y.ToBigInteger(), false);
                }

                // Convert to bitcoin address and check address hash.
                PublicKey generatedaddress = new PublicKey(pubpoint);

                // get addresshash
                UTF8Encoding utf8 = new UTF8Encoding(false);
                Sha256Digest sha256 = new Sha256Digest();
                byte[] generatedaddressbytes = utf8.GetBytes(generatedaddress.AddressBase58);
                sha256.BlockUpdate(generatedaddressbytes, 0, generatedaddressbytes.Length);
                byte[] addresshashfull = new byte[32];
                sha256.DoFinal(addresshashfull, 0);
                sha256.BlockUpdate(addresshashfull, 0, 32);
                sha256.DoFinal(addresshashfull, 0);

                for (int i = 0; i < 4; i++) {
                    if (addresshashfull[i] != confbytes[i + 6]) {
                        MessageBox.Show("This passphrase is wrong or does not belong to this confirmation code.", "Invalid passphrase", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        return;
                    }
                }

                confirmIsValid(generatedaddress.AddressBase58);
            } catch {
                // Might throw an exception - not every 256-bit integer is a valid X coordinate
                MessageBox.Show("This passphrase is wrong or does not belong to this confirmation code.", "Invalid passphrase", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
        }
コード例 #24
0
        public override bool DecryptWithPassphrase(string passphrase)
        {
            if (passphrase == null) {
                return false;
            }

            byte[] hex = Util.Base58CheckToByteArray(_encryptedKey);
            KeyPair tempkey = null;

            if (hex.Length == 39 && hex[0] == 1 && hex[1] == 0x42) {
                UTF8Encoding utf8 = new UTF8Encoding(false);
                byte[] addresshash = new byte[] { hex[3], hex[4], hex[5], hex[6] };

                byte[] derivedBytes = new byte[64];
                SCrypt.ComputeKey(utf8.GetBytes(passphrase), addresshash, 16384, 8, 8, 8, derivedBytes);

                var aes = Aes.Create();
                aes.KeySize = 256;
                aes.Mode = CipherMode.ECB;
                byte[] aeskey = new byte[32];
                Array.Copy(derivedBytes, 32, aeskey, 0, 32);
                aes.Key = aeskey;
                ICryptoTransform decryptor = aes.CreateDecryptor();

                byte[] decrypted = new byte[32];
                decryptor.TransformBlock(hex, 7, 16, decrypted, 0);
                decryptor.TransformBlock(hex, 7, 16, decrypted, 0);
                decryptor.TransformBlock(hex, 23, 16, decrypted, 16);
                decryptor.TransformBlock(hex, 23, 16, decrypted, 16);
                for (int x = 0; x < 32; x++) decrypted[x] ^= derivedBytes[x];

                tempkey = new KeyPair(decrypted, compressed: IsCompressedPoint);

                Sha256Digest sha256 = new Sha256Digest();
                byte[] addrhash = new byte[32];
                byte[] addrtext = utf8.GetBytes(tempkey.AddressBase58);
                sha256.BlockUpdate(addrtext, 0, addrtext.Length);
                sha256.DoFinal(addrhash, 0);
                sha256.BlockUpdate(addrhash, 0, 32);
                sha256.DoFinal(addrhash, 0);
                if (addrhash[0] != hex[3] || addrhash[1] != hex[4] || addrhash[2] != hex[5] || addrhash[3] != hex[6]) {
                    return false;
                }
                _privKey = tempkey.PrivateKeyBytes;
                _pubKey = tempkey.PublicKeyBytes;
                _hash160 = tempkey.Hash160;
                return true;
            } else if (hex.Length == 39 && hex[0] == 1 && hex[1] == 0x43) {

                // produce the intermediate from the passphrase

                // get ownersalt and encryptedpart2 since they are in the record
                byte[] ownersalt = new byte[8];
                Array.Copy(hex, 7, ownersalt, 0, 8);
                bool includeHashStep = (hex[2] & 4) == 4;
                Bip38Intermediate intermediate = new Bip38Intermediate(passphrase, ownersalt, includeHashStep);
                this.LotNumber = intermediate.LotNumber;
                this.SequenceNumber = intermediate.SequenceNumber;

                tempkey = decryptUsingIntermediate(intermediate, hex);
                if (verifyAddressHash(tempkey.AddressBase58, hex) == false) return false;
            }
            _privKey = tempkey.PrivateKeyBytes;
            _pubKey = tempkey.PublicKeyBytes;
            _hash160 = tempkey.Hash160;
            return true;
        }
コード例 #25
0
        private KeyPair decryptUsingIntermediate(Bip38Intermediate intermediate, byte[] hex)
        {
            if (intermediate.passfactor == null) {
                throw new ArgumentException("This is an encryption-only intermediate code because it was not created from a passphrase.  An intermediate must have been created from passphrase to be used for decryption");
            }

            byte[] encryptedpart2 = new byte[16];
            Array.Copy(hex, 23, encryptedpart2, 0, 16);

            // get the first part of encryptedpart1 (the rest is encrypted within encryptedpart2)
            byte[] encryptedpart1 = new byte[16];
            Array.Copy(hex, 15, encryptedpart1, 0, 8);

            // derive decryption key
            byte[] addresshashplusownerentropy = new byte[12];
            Array.Copy(hex, 3, addresshashplusownerentropy, 0, 4);
            Array.Copy(intermediate.ownerentropy, 0, addresshashplusownerentropy, 4, 8);
            byte[] derived = new byte[64];
            SCrypt.ComputeKey(intermediate.passpoint, addresshashplusownerentropy, 1024, 1, 1, 1, derived);
            byte[] derivedhalf2 = new byte[32];
            Array.Copy(derived, 32, derivedhalf2, 0, 32);

            // decrypt encrypted payload
            var aes = Aes.Create();
            aes.KeySize = 256;
            aes.Mode = CipherMode.ECB;
            aes.Key = derivedhalf2;
            ICryptoTransform decryptor = aes.CreateDecryptor();

            byte[] unencryptedpart2 = new byte[16];
            decryptor.TransformBlock(encryptedpart2, 0, 16, unencryptedpart2, 0);
            decryptor.TransformBlock(encryptedpart2, 0, 16, unencryptedpart2, 0);
            for (int i = 0; i < 16; i++) {
                unencryptedpart2[i] ^= derived[i + 16];
            }

            // take the decrypted part and recover encrypted part 1
            Array.Copy(unencryptedpart2, 0, encryptedpart1, 8, 8);

            // decrypt part 1
            byte[] unencryptedpart1 = new byte[16];
            decryptor.TransformBlock(encryptedpart1, 0, 16, unencryptedpart1, 0);
            decryptor.TransformBlock(encryptedpart1, 0, 16, unencryptedpart1, 0);
            for (int i = 0; i < 16; i++) {
                unencryptedpart1[i] ^= derived[i];
            }

            // recover seedb
            byte[] seedb = new byte[24];
            Array.Copy(unencryptedpart1, 0, seedb, 0, 16);
            Array.Copy(unencryptedpart2, 8, seedb, 16, 8);

            // turn seedb into factorb
            Sha256Digest sha256 = new Sha256Digest();
            sha256.BlockUpdate(seedb, 0, 24);
            byte[] factorb = new byte[32];
            sha256.DoFinal(factorb, 0);
            sha256.BlockUpdate(factorb, 0, 32);
            sha256.DoFinal(factorb, 0);

            // get private key
            var ps = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp256k1");
            BigInteger privatekey = new BigInteger(1, intermediate.passfactor).Multiply(new BigInteger(1, factorb)).Mod(ps.N);

            // use private key
            return new KeyPair(privatekey, this.IsCompressedPoint, this._addressType);
        }
コード例 #26
0
        /// <summary>
        /// Encryption constructor to create a new random key from an intermediate
        /// </summary>
        public Bip38KeyPair(Bip38Intermediate intermediate, bool retainPrivateKeyWhenPossible=false)
        {
            // generate seedb
            byte[] seedb = new byte[24];
            SecureRandom sr = new SecureRandom();
            sr.NextBytes(seedb);

            // get factorb as sha256(sha256(seedb))
            Sha256Digest sha256 = new Sha256Digest();
            sha256.BlockUpdate(seedb, 0, 24);
            factorb = new byte[32];
            sha256.DoFinal(factorb, 0);
            sha256.BlockUpdate(factorb, 0, 32);
            sha256.DoFinal(factorb, 0);

            // get ECPoint from passpoint
            PublicKey pk = new PublicKey(intermediate.passpoint);

            ECPoint generatedpoint = pk.GetECPoint().Multiply(new BigInteger(1, factorb));
            byte[] generatedpointbytes = generatedpoint.GetEncoded();
            PublicKey generatedaddress = new PublicKey(generatedpointbytes);

            // get addresshash
            UTF8Encoding utf8 = new UTF8Encoding(false);
            byte[] generatedaddressbytes = utf8.GetBytes(generatedaddress.AddressBase58);
            sha256.BlockUpdate(generatedaddressbytes, 0, generatedaddressbytes.Length);
            byte[] addresshashfull = new byte[32];
            sha256.DoFinal(addresshashfull, 0);
            sha256.BlockUpdate(addresshashfull, 0, 32);
            sha256.DoFinal(addresshashfull, 0);

            byte[] addresshashplusownerentropy = new byte[12];
            Array.Copy(addresshashfull, 0, addresshashplusownerentropy, 0, 4);
            Array.Copy(intermediate.ownerentropy, 0, addresshashplusownerentropy, 4, 8);

            // derive encryption key material
            derived = new byte[64];
            SCrypt.ComputeKey(intermediate.passpoint, addresshashplusownerentropy, 1024, 1, 1, 1, derived);

            byte[] derivedhalf2 = new byte[32];
            Array.Copy(derived, 32, derivedhalf2, 0, 32);

            byte[] unencryptedpart1 = new byte[16];
            for (int i = 0; i < 16; i++) {
                unencryptedpart1[i] = (byte)(seedb[i] ^ derived[i]);
            }
            byte[] encryptedpart1 = new byte[16];

            // encrypt it
            var aes = Aes.Create();
            aes.KeySize = 256;
            aes.Mode = CipherMode.ECB;
            aes.Key = derivedhalf2;
            ICryptoTransform encryptor = aes.CreateEncryptor();

            encryptor.TransformBlock(unencryptedpart1, 0, 16, encryptedpart1, 0);
            encryptor.TransformBlock(unencryptedpart1, 0, 16, encryptedpart1, 0);

            byte[] unencryptedpart2 = new byte[16];
            for (int i = 0; i < 8; i++) {
                unencryptedpart2[i] = (byte)(encryptedpart1[i + 8] ^ derived[i + 16]);
            }
            for (int i = 0; i < 8; i++) {
                unencryptedpart2[i + 8] = (byte)(seedb[i + 16] ^ derived[i + 24]);
            }

            byte[] encryptedpart2 = new byte[16];
            encryptor.TransformBlock(unencryptedpart2, 0, 16, encryptedpart2, 0);
            encryptor.TransformBlock(unencryptedpart2, 0, 16, encryptedpart2, 0);

            byte[] result = new byte[39];
            result[0] = 0x01;
            result[1] = 0x43;
            result[2] = generatedaddress.IsCompressedPoint ? (byte)0x20 : (byte)0x00;
            if (intermediate.LotSequencePresent) result[2] |= 0x04;

            Array.Copy(addresshashfull, 0, result, 3, 4);
            Array.Copy(intermediate.ownerentropy, 0, result, 7, 8);
            Array.Copy(encryptedpart1, 0, result, 15, 8);
            Array.Copy(encryptedpart2, 0, result, 23, 16);

            _encryptedKey = Util.ByteArrayToBase58Check(result);
            _pubKey = generatedaddress.PublicKeyBytes;
            _hash160 = generatedaddress.Hash160;

            var ps = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp256k1");

            if (retainPrivateKeyWhenPossible && intermediate.passfactor != null) {
                BigInteger privatekey = new BigInteger(1, intermediate.passfactor).Multiply(new BigInteger(1, factorb)).Mod(ps.N);
                _privKey = new KeyPair(privatekey).PrivateKeyBytes;

            }

            // create the confirmation code
            confirmationCodeInfo = new byte[51];
            // constant provides for prefix "cfrm38"
            confirmationCodeInfo[0] = 0x64;
            confirmationCodeInfo[1] = 0x3B;
            confirmationCodeInfo[2] = 0xF6;
            confirmationCodeInfo[3] = 0xA8;
            confirmationCodeInfo[4] = 0x9A;
            // fields for flagbyte, addresshash, and ownerentropy all copy verbatim
            Array.Copy(result, 2, confirmationCodeInfo, 5, 1 + 4 + 8);
        }
 private static string GetHashDigest(Sha256Digest hash)
 {
     var digest = new byte[hash.GetDigestSize()];
     hash.DoFinal(digest, 0);
     return BitConverter.ToString(digest).Replace("-", string.Empty).ToLower();
 }
コード例 #28
0
ファイル: Hashes.cs プロジェクト: nikropht/NBitcoin
 public static byte[] SHA256(byte[] data, int count)
 {
     Sha256Digest sha256 = new Sha256Digest();
     sha256.BlockUpdate(data, 0, count);
     byte[] rv = new byte[32];
     sha256.DoFinal(rv, 0);
     return rv;
 }
コード例 #29
0
        public Exception DecryptWithPassphrase(string passphrase)
        {
            // check for null entry
            if (passphrase == null || passphrase == "") {
                return new ArgumentException("Passphrase is required");
            }

            Bip38Intermediate intermediate = new Bip38Intermediate(passphrase, _ownerentropy, LotSequencePresent);

            // derive the 64 bytes we need
            // get ECPoint from passpoint
            PublicKey pk = new PublicKey(intermediate.passpoint);

            byte[] addresshashplusownerentropy = Util.ConcatenateByteArrays(_addressHash, intermediate.ownerentropy);

            // derive encryption key material
            byte[] derived = new byte[64];
            SCrypt.ComputeKey(intermediate.passpoint, addresshashplusownerentropy, 1024, 1, 1, 1, derived);

            byte[] derivedhalf2 = new byte[32];
            Array.Copy(derived, 32, derivedhalf2, 0, 32);

            byte[] unencryptedpubkey = new byte[33];
            // recover the 0x02 or 0x03 prefix
            unencryptedpubkey[0] = (byte)(_encryptedpointb[0] ^ (derived[63] & 0x01));

            // decrypt
            var aes = Aes.Create();
            aes.KeySize = 256;
            aes.Mode = CipherMode.ECB;
            aes.Key = derivedhalf2;
            ICryptoTransform decryptor = aes.CreateDecryptor();

            decryptor.TransformBlock(_encryptedpointb, 1, 16, unencryptedpubkey, 1);
            decryptor.TransformBlock(_encryptedpointb, 1, 16, unencryptedpubkey, 1);
            decryptor.TransformBlock(_encryptedpointb, 1 + 16, 16, unencryptedpubkey, 17);
            decryptor.TransformBlock(_encryptedpointb, 1 + 16, 16, unencryptedpubkey, 17);

            // xor out the padding
            for (int i = 0; i < 32; i++) unencryptedpubkey[i + 1] ^= derived[i];

            // reconstitute the ECPoint
            var ps = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp256k1");
            ECPoint point;
            try {
                point = ps.Curve.DecodePoint(unencryptedpubkey);

                // multiply passfactor.  Result is going to be compressed.
                ECPoint pubpoint = point.Multiply(new BigInteger(1, intermediate.passfactor));

                // Do we want it uncompressed?  then we will have to uncompress it.
                if (IsCompressedPoint==false) {
                    pubpoint = ps.Curve.CreatePoint(pubpoint.X.ToBigInteger(), pubpoint.Y.ToBigInteger(), false);
                }

                // Convert to bitcoin address and check address hash.
                PublicKey generatedaddress = new PublicKey(pubpoint);

                // get addresshash
                UTF8Encoding utf8 = new UTF8Encoding(false);
                Sha256Digest sha256 = new Sha256Digest();
                byte[] generatedaddressbytes = utf8.GetBytes(generatedaddress.AddressBase58);
                sha256.BlockUpdate(generatedaddressbytes, 0, generatedaddressbytes.Length);
                byte[] addresshashfull = new byte[32];
                sha256.DoFinal(addresshashfull, 0);
                sha256.BlockUpdate(addresshashfull, 0, 32);
                sha256.DoFinal(addresshashfull, 0);

                for (int i = 0; i < 4; i++) {
                    if (addresshashfull[i] != _addressHash[i]) {
                        return new ArgumentException("This passphrase is wrong or does not belong to this confirmation code.");
                    }
                }

                this.PublicKey = generatedaddress;
            } catch {
                return new ArgumentException("This passphrase is wrong or does not belong to this confirmation code.");
            }
            return null;
        }
コード例 #30
0
 public static byte[] ComputeSha256(byte[] ofwhat)
 {
     Sha256Digest sha256 = new Sha256Digest();
     sha256.BlockUpdate(ofwhat, 0, ofwhat.Length);
     byte[] rv = new byte[32];
     sha256.DoFinal(rv, 0);
     return rv;
 }
コード例 #31
0
ファイル: Digester.cs プロジェクト: bibou1324/clienteafirma
        public static byte[] Digest(byte[] data, String algo)
        {
            if (algo == null)
            {
                throw new ArgumentNullException("El algoritmo de huella digital no puede ser nulo");
            }
            if (data == null)
            {
                throw new ArgumentNullException("Los datos no pueden ser nulos");
            }

            switch (algo)
            {
                /**
                 * ALGORITMOS DE HASING
                 */
                case AOSignConstants.SIGN_ALGORITHM_SHA1:
                    {
                        Sha1Digest dig = new Sha1Digest();
                        dig.BlockUpdate(data, 0, data.Length);
                        byte[] result = new byte[dig.GetDigestSize()];
                        dig.DoFinal(result, 0);
                        return result;
                    }

                case AOSignConstants.SIGN_ALGORITHM_SHA256:
                    {
                        Sha256Digest dig = new Sha256Digest();
                        dig.BlockUpdate(data, 0, data.Length);
                        byte[] result = new byte[dig.GetDigestSize()];
                        dig.DoFinal(result, 0);
                        return result;
                    }

                case AOSignConstants.SIGN_ALGORITHM_SHA384:
                    {
                        Sha384Digest dig = new Sha384Digest();
                        dig.BlockUpdate(data, 0, data.Length);
                        byte[] result = new byte[dig.GetDigestSize()];
                        dig.DoFinal(result, 0);
                        return result;
                    }

                case AOSignConstants.SIGN_ALGORITHM_SHA512:
                    {
                        Sha512Digest dig = new Sha512Digest();
                        dig.BlockUpdate(data, 0, data.Length);
                        byte[] result = new byte[dig.GetDigestSize()];
                        dig.DoFinal(result, 0);
                        return result;
                    }

                case AOSignConstants.SIGN_ALGORITHM_RIPEMD160:
                    {
                        RipeMD160Digest dig = new RipeMD160Digest();
                        dig.BlockUpdate(data, 0, data.Length);
                        byte[] result = new byte[dig.GetDigestSize()];
                        dig.DoFinal(result, 0);
                        return result;
                    }
                case AOSignConstants.SIGN_ALGORITHM_MD5:
                    {
                        MD5Digest dig = new MD5Digest();
                        dig.BlockUpdate(data, 0, data.Length);
                        byte[] result = new byte[dig.GetDigestSize()];
                        dig.DoFinal(result, 0);
                        return result;
                    }

                case AOSignConstants.SIGN_ALGORITHM_MD2:
                    {
                        MD2Digest dig = new MD2Digest();
                        dig.BlockUpdate(data, 0, data.Length);
                        byte[] result = new byte[dig.GetDigestSize()];
                        dig.DoFinal(result, 0);
                        return result;
                    }

                default:
                    // You can use the default case.
                    throw new ArgumentNullException("El algoritmo no es reconocido");
            }

            throw new ArgumentNullException("Algoritmo de hash no soportado: " + algo);
        }
コード例 #32
0
 /// <summary>
 /// Creates a new key pair using the SHA256 hash of a given string as the private key.
 /// </summary>
 public static KeyPair CreateFromString(string tohash)
 {
     UTF8Encoding utf8 = new UTF8Encoding(false);
     byte[] forsha = utf8.GetBytes(tohash);
     Sha256Digest sha256 = new Sha256Digest();
     sha256.BlockUpdate(forsha, 0, forsha.Length);
     byte[] thehash = new byte[32];
     sha256.DoFinal(thehash, 0);
     return new KeyPair(thehash);
 }