/// <summary> /// Initializes an ECDSA instance given a key and the type of key which it is. /// </summary> /// <param name="key">The key data for either a public or private key.</param> /// <param name="keyType">The type of key this provided key is.</param> public EthereumEcdsaNative(Memory <byte> key, EthereumEcdsaKeyType keyType) { // Set our type of key. KeyType = keyType; // If this is a public key, we will convert our type to uncompressed, sliced prefix (ethereum format) if (keyType == EthereumEcdsaKeyType.Public) { key = ConvertPublicKeyFormat(key, false, true); } // Obtain our expected size, and if our key exceeds that, we cut off the head. int expectedSize = keyType == EthereumEcdsaKeyType.Public ? PUBLIC_KEY_SIZE : PRIVATE_KEY_SIZE; if (key.Length > expectedSize) { UnmanagedKey = key.Slice(key.Length - expectedSize); } else if (key.Length < expectedSize) { // If it's too small, we add to it. Memory <byte> newKey = new byte[expectedSize]; key.CopyTo(newKey.Slice(newKey.Length - key.Length)); // And we update our key. UnmanagedKey = newKey; } else { UnmanagedKey = key; } }
public EthereumEcdsaBouncyCastle(Memory <byte> key, EthereumEcdsaKeyType keyType) { // Set the key type KeyType = keyType; // Instantiate our key depending on what type of key it is. if (KeyType == EthereumEcdsaKeyType.Public) { // If it's only 64 bytes, we need to add our prefix. (Source: https://en.bitcoin.it/wiki/Elliptic_Curve_Digital_Signature_Algorithm) if (key.Length == PUBLIC_KEY_SIZE) { key = new byte[] { 0x4 }.Concat(key.ToArray()); } // Obtain our public key parameters by using the provided quotient. ECPoint q = Secp256k1Curve.Parameters.Curve.DecodePoint(key.ToArray()); PublicKey = new ECPublicKeyParameters(ALGORITHM, q, Secp256k1Curve.DomainParameters); } else { // Obtain our private key parameters Org.BouncyCastle.Math.BigInteger keyInt = new Org.BouncyCastle.Math.BigInteger(1, key.ToArray()); PrivateKey = new ECPrivateKeyParameters(ALGORITHM, keyInt, Secp256k1Curve.DomainParameters); // Obtain Q from our private key. ECPoint q = Secp256k1Curve.Parameters.G.Multiply(PrivateKey.D); PublicKey = new ECPublicKeyParameters(ALGORITHM, q, Secp256k1Curve.DomainParameters); } }
/// <summary> /// Initializes an ECDSA instance given a key and the type of key which it is. /// </summary> /// <param name="key">The key data for either a public or private key.</param> /// <param name="keyType">The type of key this provided key is.</param> public static EthereumEcdsa Create(Memory <byte> key, EthereumEcdsaKeyType keyType) { if (UseNativeLib) { return(new EthereumEcdsaNative(key, keyType)); } else { return(new EthereumEcdsaBouncyCastle(key, keyType)); } }