/// <summary> /// Creates address from public key /// </summary> /// <param name="publicKey"></param> /// <param name="networkType"></param> /// <returns></returns> public static Address CreateFromPublicKey(string publicKey, NetworkType networkType) { // step 1) sha-3(256) public key var digestSha3 = new Sha3Digest(256); var stepOne = new byte[Key]; digestSha3.BlockUpdate(publicKey.FromHex(), 0, Key); digestSha3.DoFinal(stepOne, 0); // step 2) perform ripemd160 on previous step var digestRipeMd160 = new RipeMD160Digest(); var stepTwo = new byte[Ripemd160]; digestRipeMd160.BlockUpdate(stepOne, 0, Key); digestRipeMd160.DoFinal(stepTwo, 0); // step3) prepend network byte var stepThree = new[] { networkType.GetValueInByte() }.Concat(stepTwo).ToArray(); // step 4) perform sha3 on previous step var stepFour = new byte[Key]; digestSha3.BlockUpdate(stepThree, 0, Ripemd160 + 1); digestSha3.DoFinal(stepFour, 0); // step 5) retrieve checksum var stepFive = new byte[Checksum]; Array.Copy(stepFour, 0, stepFive, 0, Checksum); // step 6) append stepFive to result of stepThree var stepSix = new byte[AddressDecoded]; Array.Copy(stepThree, 0, stepSix, 0, Ripemd160 + 1); Array.Copy(stepFive, 0, stepSix, Ripemd160 + 1, Checksum); // step 7) return base 32 encode address byte array return(CreateFromRawAddress(stepSix.ToBase32String())); }
/// <summary> /// Create an Address from a given public key and network type. /// </summary> /// <param name="publicKey">The public key.</param> /// <param name="networkType">The network type</param> /// <returns>Address.</returns> public Address(string publicKey, NetworkType.Types networkType) { // step 1) sha-3(256) public key var digestSha3 = new KeccakDigest(256); var stepOne = new byte[Constants.Key]; digestSha3.BlockUpdate(publicKey.FromHex(), 0, Constants.Key); digestSha3.DoFinal(stepOne, 0); // step 2) perform ripemd160 on previous step var digestRipeMd160 = new RipeMD160Digest(); var stepTwo = new byte[Constants.Ripemd160]; digestRipeMd160.BlockUpdate(stepOne, 0, Constants.Key); digestRipeMd160.DoFinal(stepTwo, 0); // step3) prepend network byte var stepThree = new[] { networkType.GetNetwork() }.Concat(stepTwo).ToArray(); // step 4) perform sha3 on previous step var stepFour = new byte[Constants.Key]; digestSha3.BlockUpdate(stepThree, 0, Constants.Ripemd160 + 1); digestSha3.DoFinal(stepFour, 0); // step 5) retrieve checksum var stepFive = new byte[Constants.Checksum]; Array.Copy(stepFour, 0, stepFive, 0, Constants.Checksum); // step 6) append stepFive to resulst of stepThree var stepSix = new byte[Constants.AddressDecoded]; Array.Copy(stepThree, 0, stepSix, 0, Constants.Ripemd160 + 1); Array.Copy(stepFive, 0, stepSix, Constants.Ripemd160 + 1, Constants.Checksum); // step 7) return base 32 encode address byte array Initialize(stepSix.ToBase32String()); }
private static String DeriveSIN(byte[] pubKeyBytes) { // Get sha256 hash and then the RIPEMD-160 hash of the public key (this call gets the result in one step). byte[] hash = new SHA256Managed().ComputeHash(pubKeyBytes); RipeMD160Digest ripeMd160Digest = new RipeMD160Digest(); ripeMd160Digest.BlockUpdate(hash, 0, hash.Length); byte[] output = new byte[20]; ripeMd160Digest.DoFinal(output, 0); byte[] pubKeyHash = output; // Convert binary pubKeyHash, SINtype and version to Hex String version = "0F"; String SINtype = "02"; String pubKeyHashHex = bytesToHex(pubKeyHash); // Concatenate all three elements String preSIN = version + SINtype + pubKeyHashHex; // Convert the hex string back to binary and double sha256 hash it leaving in binary both times byte[] preSINbyte = hexToBytes(preSIN); byte[] hash2Bytes = DoubleDigest(preSINbyte); // Convert back to hex and take first four bytes String hashString = bytesToHex(hash2Bytes); String first4Bytes = hashString.Substring(0, 8); // Append first four bytes to fully appended SIN string String unencoded = preSIN + first4Bytes; byte[] unencodedBytes = new BigInteger(unencoded, 16).ToByteArray(); String encoded = Encode(unencodedBytes); return(encoded); }
public ITestResult Perform() { IDigest digest = new RipeMD160Digest(); byte[] resBuf = new byte[digest.GetDigestSize()]; for (int i = 0; i < messages.Length; i++) { byte[] m = Encoding.ASCII.GetBytes(messages[i]); digest.BlockUpdate(m, 0, m.Length); digest.DoFinal(resBuf, 0); if (!Arrays.AreEqual(resBuf, Hex.Decode(digests[i]))) { return(new SimpleTestResult(false, Name + ": Vector " + i + " failed")); } } // // test 2 // byte[] mm = Encoding.ASCII.GetBytes(messages[messages.Length - 1]); digest.BlockUpdate(mm, 0, mm.Length / 2); // clone the IDigest IDigest d = new RipeMD160Digest((RipeMD160Digest)digest); digest.BlockUpdate(mm, mm.Length / 2, mm.Length - mm.Length / 2); digest.DoFinal(resBuf, 0); if (!Arrays.AreEqual(resBuf, Hex.Decode(digests[digests.Length - 1]))) { return(new SimpleTestResult(false, "RipeMD160 failing clone test" + SimpleTest.NewLine + " expected: " + digests[digests.Length - 1] + SimpleTest.NewLine + " got : " + Hex.ToHexString(resBuf))); } d.BlockUpdate(mm, mm.Length / 2, mm.Length - mm.Length / 2); d.DoFinal(resBuf, 0); if (!Arrays.AreEqual(resBuf, Hex.Decode(digests[digests.Length - 1]))) { return(new SimpleTestResult(false, "RipeMD160 failing clone test - part 2" + SimpleTest.NewLine + " expected: " + digests[digests.Length - 1] + SimpleTest.NewLine + " got : " + Hex.ToHexString(resBuf))); } for (int i = 0; i < 1000000; i++) { digest.Update((byte)'a'); } digest.DoFinal(resBuf, 0); if (!Arrays.AreEqual(resBuf, Hex.Decode(MillionADigest))) { return(new SimpleTestResult(false, Name + ": Million a's failed")); } return(new SimpleTestResult(true, Name + ": Okay")); }
public static byte[] RIPEMD160(byte[] data, int offset, int count) { #if !DNXCORE50 using (var ripm = new RIPEMD160Managed()) { return ripm.ComputeHash(data, offset, count); } #else RipeMD160Digest ripemd = new RipeMD160Digest(); ripemd.BlockUpdate(data, offset, count); byte[] rv = new byte[20]; ripemd.DoFinal(rv, 0); return rv; #endif }
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); }
// This are implented as static constructors to translate Dart factory /// Derives the private key from the given [mnemonic] using the specified /// [networkInfo]. public static Wallet derive(List <String> mnemonic, NetworkInfo networkInfo, String lastDerivationPathSegment = "0") { Mnemonic bip39; // Get the mnemonic as a single concatenated string String mnemonicString = String.Join(' ', mnemonic); // Check the mnemonic try { bip39 = new Mnemonic(mnemonicString); } catch (ArgumentException e) { System.ArgumentException argEx = new System.ArgumentException($"Invalid mnemonic string - Exception ${e.Message} - '${mnemonicString}'"); throw argEx; } // Get the seed - byte[]. !!!Note the empty password - OK! byte[] seed = bip39.DeriveSeed(); // Using the seed in a BIP32 instance ExtKey root = new ExtKey(seed); // Check for correct lastDerivationPathSegment int segValue = -1; bool isNumeric = int.TryParse(lastDerivationPathSegment, out segValue); if ((isNumeric == false) || (segValue < 0)) { // Exception - derivation path not valid! System.ArgumentException argEx = new System.ArgumentException($"Argument Exception - Invalid Derivation Path: '{lastDerivationPathSegment}'"); throw argEx; } // Create the Keypath - with the last Path Segment String derivedPathString = $"{DERIVATION_PATH}/{lastDerivationPathSegment}"; KeyPath derivationPath = new KeyPath(derivedPathString); // Get the node ExtKey derivedNode = root.Derive(derivationPath); // Get the private key byte[] privateKey = derivedNode.PrivateKey.ToBytes(); // Get the curve data X9ECParameters secp256k1 = ECNamedCurveTable.GetByName("secp256k1"); ECPoint point = secp256k1.G; // Compute the curve point associated to the private key BigInteger bigInt = new BigInteger(HexEncDec.ByteArrayToString(privateKey), (int)16); ECPoint curvePoint = point.Multiply(bigInt); // Get the public key - Be Careful, this MUST be compressed format!!! byte[] publicKeyBytes = curvePoint.GetEncoded(true); // Get the address Sha256Digest sha256digest = new Sha256Digest(); sha256digest.BlockUpdate(publicKeyBytes, 0, publicKeyBytes.Length); // byte[] sha256digestOut = new byte[sha256digest.GetByteLength()]; byte[] sha256digestOut = new byte[sha256digest.GetDigestSize()]; sha256digest.DoFinal(sha256digestOut, 0); RipeMD160Digest ripeMD160Digest = new RipeMD160Digest(); ripeMD160Digest.BlockUpdate(sha256digestOut, 0, sha256digestOut.Length); // byte[] address = new byte[ripeMD160Digest.GetByteLength()]; byte[] address = new byte[ADDRESS_LENGTH]; ripeMD160Digest.DoFinal(address, 0); // Return the key bytes return(new Wallet(address: address, publicKey: publicKeyBytes, privateKey: privateKey, networkInfo: networkInfo)); }