public byte[] ToDER(bool compressed) { AssertPrivateKey(); MemoryStream baos = new MemoryStream(); // ASN1_SEQUENCE(EC_PRIVATEKEY) = { // ASN1_SIMPLE(EC_PRIVATEKEY, version, LONG), // ASN1_SIMPLE(EC_PRIVATEKEY, privateKey, ASN1_OCTET_STRING), // ASN1_EXP_OPT(EC_PRIVATEKEY, parameters, ECPKPARAMETERS, 0), // ASN1_EXP_OPT(EC_PRIVATEKEY, publicKey, ASN1_BIT_STRING, 1) // } ASN1_SEQUENCE_END(EC_PRIVATEKEY) DerSequenceGenerator seq = new DerSequenceGenerator(baos); seq.AddObject(new DerInteger(1)); // version seq.AddObject(new DerOctetString(PrivateKey.D.ToByteArrayUnsigned())); //Did not managed to generate the same der as brainwallet by using this //seq.AddObject(new DerTaggedObject(0, Secp256k1.ToAsn1Object())); Asn1Object secp256k1Der = null; if(compressed) { secp256k1Der = DerSequence.FromByteArray(HexEncoding.Instance.GetBytes("308182020101302c06072a8648ce3d0101022100fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f300604010004010704210279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798022100fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141020101")); } else { secp256k1Der = DerSequence.FromByteArray(HexEncoding.Instance.GetBytes("3081a2020101302c06072a8648ce3d0101022100fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f300604010004010704410479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8022100fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141020101")); } seq.AddObject(new DerTaggedObject(0, secp256k1Der)); seq.AddObject(new DerTaggedObject(1, new DerBitString(GetPublicKey(compressed).ToBytes()))); seq.Close(); return baos.ToArray(); }
/** * What we get back from the signer are the two components of a signature, r and s. To get a flat byte stream * of the type used by Bitcoin we have to encode them using DER encoding, which is just a way to pack the two * components into a structure. */ public byte[] ToDER() { // Usually 70-72 bytes. MemoryStream bos = new MemoryStream(72); DerSequenceGenerator seq = new DerSequenceGenerator(bos); seq.AddObject(new DerInteger(R)); seq.AddObject(new DerInteger(S)); seq.Close(); return bos.ToArray(); }