Skip to content

Instantly share code, notes, and snippets.

@imyourm8
Created June 23, 2018 10:41
Show Gist options
  • Save imyourm8/9ac28190f892b4a7457ef88bfcdccfc1 to your computer and use it in GitHub Desktop.
Save imyourm8/9ac28190f892b4a7457ef88bfcdccfc1 to your computer and use it in GitHub Desktop.
BIP39 & BIP32 C# example implementation
/*
This code allows you to export BIP39 12 words phrase and use it with Ethereum/Loom
To check Popular derivative paths look here https://www.myetherwallet.com/#view-wallet-info
Or here is quick cheatsheet https://gyazo.com/a4199116750b57a02917eb255d4c033e
Dependency on very nice library https://github.com/MetacoSA/NBitcoin - clone and build it
*/
using NBitcoin;
using Org.BouncyCastle.Asn1.Sec;
using Org.BouncyCastle.Math;
public bool LoadFromMnemonic(string mnemonicPhrase, string keyPath = "m/44'/60'/0'/0", string password = null) {
try {
var mnemonic = new Mnemonic(mnemonicPhrase);
var keyPathToDerive = KeyPath.Parse(keyPath);
var pk = new ExtKey(mnemonic.DeriveSeed(password)).Derive(keyPathToDerive);
ExtKey keyNew = pk.Derive(0);
var pkeyBytes = keyNew.PrivateKey.PubKey.ToBytes();
var ecParams = SecNamedCurves.GetByName("secp256k1");
var point = ecParams.Curve.DecodePoint(pkeyBytes);
var xCoord = point.XCoord.GetEncoded();
var yCoord = point.YCoord.GetEncoded();
var uncompressedBytes = new byte[64];
// copy X coordinate
Array.Copy(xCoord, uncompressedBytes, xCoord.Length);
// copy Y coordinate
for (int i = 0; i < 32 && i < yCoord.Length; i++) {
uncompressedBytes[uncompressedBytes.Length - 1 - i] = yCoord[yCoord.Length - 1 - i];
}
var PrivateKey = keyNew.PrivateKey.ToBytes();
var PublicKey = pkeyBytes;
// ethereum address is last 20 bytes of keccak(uncompressed public key)
// use any c# keccak implementation.
var PublicKeyString = CryptoUtils.BytesToHexString(Utils.Solidity.Keccak(uncompressedBytes)).Substring(24);
} catch (Exception _) {
return false;
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment