def encrypt(seed, passphrase): """ Encrypt the Electrum seed """ #1. Decode the seed value to the original number seed = mn_decode(seed.split()) #2. Take a hash of the decoded seed to act as a scrypt salt salt = hashlib.sha256(hashlib.sha256(seed).digest()).digest()[:4] #3. Derive a key from the passphrase using scrypt key = scrypt.hash(passphrase, salt, 16384, 8, 8) #4. Split the key into half 1 and half 2 derivedhalf1 = key[0:32] derivedhalf2 = key[32:64] #5. Do AES256Encrypt(seedhalf1 xor derivedhalf1[0...15], derivedhalf2), call the 16-byte result encryptedhalf1 # (Electrum may change the number of words in a seed so we should future proof by just using the halfs rather than hardcoded lengths) Aes = aes.Aes(derivedhalf2) encryptedhalf1 = Aes.enc(enc.sxor(seed[:int(math.floor(len(seed)/2))], derivedhalf1[:16])) #6. Do AES256Encrypt(seedhalf2 xor derivedhalf1[16...31], derivedhalf2), call the 16-byte result encryptedhalf2 encryptedhalf2 = Aes.enc(enc.sxor(seed[int(math.floor(len(seed)/2)):len(seed)], derivedhalf1[16:32])) #7. The encrypted private key is the Base58Check-encoded concatenation of the following # \x4E\xE3\x13\x35 + salt + encryptedhalf1 + encryptedhalf2 # (\x4E\xE3\x13\x35) gives the 'SeedE' prefix) encSeed = '\x4E\xE3\x13\x35' + salt + encryptedhalf1 + encryptedhalf2 check = hashlib.sha256(hashlib.sha256(encSeed).digest()).digest()[:4] return enc.b58encode(encSeed + check)
def confirmationcode(flagbyte, addresshash, ownerentropy, factorb, derivedhalf1, derivedhalf2): """ The party generating the Bitcoin address has the option to return a confirmation code back to owner which allows owner to independently verify that he has been given a Bitcoin address that actually depends on his passphrase, and to confirm the lot and sequence numbers (if applicable). This protects owner from being given a Bitcoin address by the second party that is unrelated to the key derivation and possibly spendable by the second party. If a Bitcoin address given to owner can be successfully regenerated through the confirmation process, owner can be reasonably assured that any spending without the passphrase is infeasible. This confirmation code is 75 characters starting with "cfrm38". To generate it, we need flagbyte, addresshash, ownerentropy, factorb, derivedhalf1 and derivedhalf2 from the original encryption operation. """ #1. ECMultiply factorb by G, call the result pointb. The result is 33 bytes (compressed key format). pub = elip.base10_multiply(elip.G, enc.decode(factorb, 256)) pointb = ('0' + str(2 + (pub[1] % 2)) + enc.encode(pub[0], 16, 64))[:33] #2. The first byte is 0x02 or 0x03. XOR it by (derivedhalf2[31] & 0x01), call the resulting byte pointbprefix. pointbprefix = enc.sxor(pointb[:1], str(derivedhalf2[31]) + '\x01') #3. Do AES256Encrypt(pointb[1...16] xor derivedhalf1[0...15], derivedhalf2) and call the result pointbx1. Aes = aes.Aes(derivedhalf2) pointbx1 = Aes.enc(enc.sxor(pointb[1:17], derivedhalf1[0:16])) #4. Do AES256Encrypt(pointb[17...32] xor derivedhalf1[16...31], derivedhalf2) and call the result pointbx2. pointbx2 = Aes.enc(enc.sxor(pointb[17:33], derivedhalf1[16:32])) #5. Concatenate pointbprefix + pointbx1 + pointbx2 (total 33 bytes) and call the result encryptedpointb. encryptedpointb = pointbprefix + pointbx1 + pointbx2 #6. The result is a Base58Check-encoded concatenation of the following: #0x64 0x3B 0xF6 0xA8 0x9A + flagbyte + addresshash + ownerentropy + encryptedpointb inp_fmtd = '\x64\x3B\xF6\xA8\x9A' + flagbyte + addresshash + ownerentropy + encryptedpointb check = hashlib.sha256(hashlib.sha256(inp_fmtd).digest()).digest()[:4] return enc.b58encode(inp_fmtd + check)
def encrypt(privK, Baddress, Saddress, passphrase): """ BIP0038 private key encryption, Non-EC """ # 1. take the first four bytes of SHA256(SHA256(address)) of it. Let's call this "addresshash". addresshash = hashlib.sha256(hashlib.sha256(Baddress + Saddress).digest()).digest()[:4] #2. Derive a key from the passphrase using scrypt # a. Parameters: passphrase is the passphrase itself encoded in UTF-8. # addresshash came from the earlier step, n=16384, r=8, p=8, length=64 # (n, r, p are provisional and subject to consensus) key = scrypt.hash(passphrase, addresshash, 16384, 8, 8) #Let's split the resulting 64 bytes in half, and call them derivedhalf1 and derivedhalf2. derivedhalf1 = key[0:32] derivedhalf2 = key[32:64] #3. Do AES256Encrypt(bitcoinprivkey[0...15] xor derivedhalf1[0...15], derivedhalf2), call the 16-byte result encryptedhalf1 Aes = aes.Aes(derivedhalf2) encryptedhalf1 = Aes.enc(enc.sxor(privK[:16], derivedhalf1[:16])) #4. Do AES256Encrypt(bitcoinprivkey[16...31] xor derivedhalf1[16...31], derivedhalf2), call the 16-byte result encryptedhalf2 encryptedhalf2 = Aes.enc(enc.sxor(privK[16:32], derivedhalf1[16:32])) #5. The encrypted private key is the Base58Check-encoded concatenation of the following, which totals 39 bytes without Base58 checksum: # 0x01 0x42 + flagbyte + salt + encryptedhalf1 + encryptedhalf2 flagbyte = chr(0b11100000) # 11 no-ec 1 compressed-pub 00 future 0 ec only 00 future privkey = ('\x01\x42' + flagbyte + addresshash + encryptedhalf1 + encryptedhalf2) check = hashlib.sha256(hashlib.sha256(privkey).digest()).digest()[:4] return enc.b58encode(privkey + check)
def encrypt(pub_address, passphrase): """ Encrypt the public address """ #1 base 58 decode the public address address = enc.b58decode(pub_address) #2. Take a hash of the decoded address to act as a scrypt salt salt = hashlib.sha256(hashlib.sha256(address).digest()).digest()[:4] #2. Derive a key from the passphrase using scrypt key = scrypt.hash(passphrase, salt, 16384, 8, 8) #3. Split the key into half 1 and half 2 derivedhalf1 = key[0:32] derivedhalf2 = key[32:64] #4 AES encrypt address halves as per bip38 halflength = int(math.floor(len(address) / 2)) Aes = aes.Aes(derivedhalf2) #for Aes encryption, string needs to have length = 16 xorhalf1 = enc.sxor(address[:halflength], derivedhalf1[:16]).ljust(16, '0') xorhalf2 = enc.sxor(address[halflength:], derivedhalf1[16:32]).ljust(16, '0') encryptedhalf1 = Aes.enc(xorhalf1) encryptedhalf2 = Aes.enc(xorhalf2) #5. The encrypted private key is the Base58Check-encoded concatenation of the following # \x78\x8e\xa3\x69\xb6 + address_length + salt + encryptedhalf1 + encryptedhalf2 encAddress = '\x78\x8e\xa3\x69\xb6' + chr(len(address)) + salt + encryptedhalf1 + encryptedhalf2 check = hashlib.sha256(hashlib.sha256(encAddress).digest()).digest()[:4] return enc.b58encode(encAddress + check)
def encrypt(pub_address, passphrase): """ Encrypt the public address """ #1 base 58 decode the public address address = enc.b58decode(pub_address) #2. Take a hash of the decoded address to act as a scrypt salt salt = hashlib.sha256(hashlib.sha256(address).digest()).digest()[:4] #2. Derive a key from the passphrase using scrypt key = scrypt.hash(passphrase, salt, 16384, 8, 8) #3. Split the key into half 1 and half 2 derivedhalf1 = key[0:32] derivedhalf2 = key[32:64] #4 AES encrypt address halves as per bip38 halflength = int(math.floor(len(address) / 2)) Aes = aes.Aes(derivedhalf2) #for Aes encryption, string needs to have length = 16 xorhalf1 = enc.sxor(address[:halflength], derivedhalf1[:16]).ljust(16, '0') xorhalf2 = enc.sxor(address[halflength:], derivedhalf1[16:32]).ljust(16, '0') encryptedhalf1 = Aes.enc(xorhalf1) encryptedhalf2 = Aes.enc(xorhalf2) #5. The encrypted private key is the Base58Check-encoded concatenation of the following # \x78\x8e\xa3\x69\xb6 + address_length + salt + encryptedhalf1 + encryptedhalf2 encAddress = '\x78\x8e\xa3\x69\xb6' + chr( len(address)) + salt + encryptedhalf1 + encryptedhalf2 check = hashlib.sha256(hashlib.sha256(encAddress).digest()).digest()[:4] return enc.b58encode(encAddress + check)
def intermediate2privK(intermediate_passphrase_string): """ Steps to create new encrypted private keys given intermediate_passphrase_string from owner (so we have ownerentropy, and passpoint, but we do not have passfactor or the passphrase): """ #get ownerentropy and passpoint from the intermediate key leadingzbytes = len(re.match('^1*',intermediate_passphrase_string).group(0)) data = '\x00' * leadingzbytes + enc.encode(enc.decode(intermediate_passphrase_string,58),256) assert hashlib.sha256(hashlib.sha256(data[:-4]).digest()).digest().encode('hex')[:4] == data[-4:] decodedstring = data[1:-4] ownerentropy = decodedstring[7:15] passpoint = decodedstring[-33:] #1. Set flagbyte. #Turn on bit 0x20 if the Bitcoin address will be formed by hashing the compressed public key (optional, saves space, but many Bitcoin implementations aren't compatible with it) #Turn on bit 0x04 if ownerentropy contains a value for lotsequence. #(While it has no effect on the keypair generation process, the decryption process needs this flag to know how to process ownerentropy) flagbyte = chr(0b00100100) # 00 EC 1 compressed 00 future 1 has lotsequence 00 future #2. Generate 24 random bytes, call this seedb. Take SHA256(SHA256(seedb)) to yield 32 bytes, call this factorb. seedb = os.urandom(24) factorb = hashlib.sha256(hashlib.sha256(seedb).digest()).digest() #3. ECMultiply passpoint by factorb. pub = elip.base10_multiply(enc.decode(factorb, 256), enc.decode(passpoint, 256)) #4. Use the resulting EC point as a public key and hash it into a Bitcoin address using either compressed or uncompressed public key methodology # (specify which methodology is used inside flagbyte). # This is the generated Bitcoin address, call it generatedaddress. publicKey = ('0' + str(2 + (pub[1] % 2)) + enc.encode(pub[0], 16, 64)) generatedaddress = address.publicKey2Address(publicKey) ## Remember to add in the currency details here #5. Take the first four bytes of SHA256(SHA256(generatedaddress)) and call it addresshash. addresshash = hashlib.sha256(hashlib.sha256(generatedaddress).digest()).digest()[:4] #6. Now we will encrypt seedb. Derive a second key from passpoint using scrypt #Parameters: passphrase is passpoint provided from the first party (expressed in binary as 33 bytes). # salt is addresshash + ownerentropy, n=1024, r=1, p=1, length=64. The "+" operator is concatenation. encseedb = scrypt.hash(passpoint, addresshash + ownerentropy, 1024, 1, 1, 64) #7. Split the result into two 32-byte halves and call them derivedhalf1 and derivedhalf2. derivedhalf1 = encseedb[0:32] derivedhalf2 = encseedb[32:64] #8. Do AES256Encrypt(seedb[0...15] xor derivedhalf1[0...15], derivedhalf2), call the 16-byte result encryptedpart1 Aes = aes.Aes(derivedhalf2) encryptedpart1 = Aes.enc(enc.sxor(seedb[:16], derivedhalf1[:16])) #9. Do AES256Encrypt((encryptedpart1[8...15] + seedb[16...23]) xor derivedhalf1[16...31], derivedhalf2), call the 16-byte result encryptedpart2. # The "+" operator is concatenation. encryptedpart2 = Aes.enc(enc.sxor(encryptedpart1[8:16] + seedb[16:24], derivedhalf1[16:32])) #10. The encrypted private key is the Base58Check-encoded concatenation of the following, which totals 39 bytes without Base58 checksum: #0x01 0x43 + flagbyte + addresshash + ownerentropy + encryptedpart1[0...7] + encryptedpart2 inp_fmtd = '\x01\x43' + flagbyte + addresshash + ownerentropy + encryptedpart1[0:8] + encryptedpart2 check = hashlib.sha256(hashlib.sha256(inp_fmtd).digest()).digest()[:4] BIPKey = enc.b58encode(inp_fmtd + check) cnfrmcode = confirmationcode(flagbyte, addresshash, ownerentropy, factorb, derivedhalf1, derivedhalf2) return BIPKey, generatedaddress, cnfrmcode
def decrypt(encSeed, passphrase): """ Decrypt an Electrum seed encrypted with the above method """ #1. Base 58 decrypt the encrypted key # get the two encrypted halves, the check and the salt decSeed = enc.b58decode(encSeed) check = decSeed[-4:] #check that it's not been tampered with if check != hashlib.sha256(hashlib.sha256( decSeed[:-4]).digest()).digest()[:4]: return False, 'checksum' salt = decSeed[4:8] encryptedhalfs = decSeed[8:len(decSeed) - 4] encryptedhalf1 = encryptedhalfs[0:int(math.floor(len(encryptedhalfs) / 2))] encryptedhalf2 = encryptedhalfs[int(math.floor(len(encryptedhalfs) / 2)):] #2. Derive the decryption key using scrypt key = scrypt.hash(passphrase, salt, 16384, 8, 8) derivedhalf1 = key[0:32] derivedhalf2 = key[32:64] #3. Decrypt the encrypted halves Aes = aes.Aes(derivedhalf2) decryptedhalf1 = Aes.dec(encryptedhalf1) decryptedhalf2 = Aes.dec(encryptedhalf2) #4 . xor them with the two halves of derivedhalf1 to get the original values half1 = enc.sxor(decryptedhalf1, derivedhalf1[:16]) half2 = enc.sxor(decryptedhalf2, derivedhalf1[16:32]) #5. build the seed and check it against the check hash seed = half1 + half2 if salt != hashlib.sha256(hashlib.sha256(seed).digest()).digest()[:4]: return False, 'salt' #6. encode the seed as an Electrum Mnemonic list mn = mn_encode(str(seed)) #6 . return the mnemonic as a single string seed = '' for word in mn: seed += word + ' ' return True, seed
def decrypt(encSeed, passphrase): """ Decrypt an Electrum seed encrypted with the above method """ #1. Base 58 decrypt the encrypted key # get the two encrypted halves, the check and the salt decSeed = enc.b58decode(encSeed) check = decSeed[-4:] #check that it's not been tampered with if check != hashlib.sha256(hashlib.sha256(decSeed[:-4]).digest()).digest()[:4]: return False, 'checksum' salt = decSeed[4:8] encryptedhalfs = decSeed[8:len(decSeed)-4] encryptedhalf1 = encryptedhalfs[0:int(math.floor(len(encryptedhalfs) / 2))] encryptedhalf2 = encryptedhalfs[int(math.floor(len(encryptedhalfs) / 2)):] #2. Derive the decryption key using scrypt key = scrypt.hash(passphrase, salt, 16384, 8, 8) derivedhalf1 = key[0:32] derivedhalf2 = key[32:64] #3. Decrypt the encrypted halves Aes = aes.Aes(derivedhalf2) decryptedhalf1 = Aes.dec(encryptedhalf1) decryptedhalf2 = Aes.dec(encryptedhalf2) #4 . xor them with the two halves of derivedhalf1 to get the original values half1 = enc.sxor(decryptedhalf1, derivedhalf1[:16]) half2 = enc.sxor(decryptedhalf2, derivedhalf1[16:32]) #5. build the seed and check it against the check hash seed = half1 + half2 if salt != hashlib.sha256(hashlib.sha256(seed).digest()).digest()[:4]: return False, 'salt' #6. encode the seed as an Electrum Mnemonic list mn = mn_encode(str(seed)) #6 . return the mnemonic as a single string seed = '' for word in mn: seed += word + ' ' return True, seed
def decrypt(enc_address, passphrase): """ Decrypt an Public Address encrypted with the above method """ #1. Base 58 decrypt the encrypted key # get the two encrypted halves, the check and the salt dec_address = enc.b58decode(enc_address) check = dec_address[-4:] #check that it's not been tampered with if check != hashlib.sha256(hashlib.sha256( dec_address[:-4]).digest()).digest()[:4]: return False, 'checksum' length = ord(dec_address[5:6]) halflength = int(math.floor(length / 2)) salt = dec_address[6:10] encryptedhalfs = dec_address[10:len(dec_address) - 4] encryptedhalf1 = encryptedhalfs[:16] encryptedhalf2 = encryptedhalfs[16:] #2. Derive the decryption key using scrypt key = scrypt.hash(passphrase, salt, 16384, 8, 8) derivedhalf1 = key[0:32] derivedhalf2 = key[32:64] #3. Aes decrypt the encrypted halves Aes = aes.Aes(derivedhalf2) xorhalf1 = Aes.dec(encryptedhalf1) xorhalf2 = Aes.dec(encryptedhalf2) #4 . xor them with the two halves of derivedhalf1 to get the original values half1 = enc.sxor(xorhalf1[:halflength], derivedhalf1[:16]) half2 = enc.sxor(xorhalf2[:(length - halflength)], derivedhalf1[16:32]) #5. build the address and check it against the check hash pub_address = half1 + half2 if salt != hashlib.sha256( hashlib.sha256(pub_address).digest()).digest()[:4]: return False, 'salt' #6. return the address as a single string return True, enc.b58encode(pub_address)
def decrypt(enc_address, passphrase): """ Decrypt an Public Address encrypted with the above method """ #1. Base 58 decrypt the encrypted key # get the two encrypted halves, the check and the salt dec_address = enc.b58decode(enc_address) check = dec_address[-4:] #check that it's not been tampered with if check != hashlib.sha256(hashlib.sha256(dec_address[:-4]).digest()).digest()[:4]: return False, 'checksum' length = ord(dec_address[5:6]) halflength = int(math.floor(length / 2)) salt = dec_address[6:10] encryptedhalfs = dec_address[10:len(dec_address) - 4] encryptedhalf1 = encryptedhalfs[:16] encryptedhalf2 = encryptedhalfs[16:] #2. Derive the decryption key using scrypt key = scrypt.hash(passphrase, salt, 16384, 8, 8) derivedhalf1 = key[0:32] derivedhalf2 = key[32:64] #3. Aes decrypt the encrypted halves Aes = aes.Aes(derivedhalf2) xorhalf1 = Aes.dec(encryptedhalf1) xorhalf2 = Aes.dec(encryptedhalf2) #4 . xor them with the two halves of derivedhalf1 to get the original values half1 = enc.sxor(xorhalf1[:halflength], derivedhalf1[:16]) half2 = enc.sxor(xorhalf2[:(length - halflength)], derivedhalf1[16:32]) #5. build the address and check it against the check hash pub_address = half1 + half2 if salt != hashlib.sha256(hashlib.sha256(pub_address).digest()).digest()[:4]: return False, 'salt' #6. return the address as a single string return True, enc.b58encode(pub_address)
def entropy(entropy): """ 512 bit random number from mouse co-ords and timer """ hashes = clockrnd() x = [] y = [] for coord in entropy: hashes ^= clockrnd() for char in str(coord[0]): x.append(char) for char in str(coord[1]): y.append(char) hashes ^= clockrnd() mouse = enc.sxor(x,y) return hashes ^ int(hashlib.sha512(str(mouse)*8).hexdigest(), 16)
def entropy(entropy): """ 512 bit random number from mouse co-ords and timer """ hashes = clockrnd() x = [] y = [] for coord in entropy: hashes ^= clockrnd() for char in str(coord[0]): x.append(char) for char in str(coord[1]): y.append(char) hashes ^= clockrnd() mouse = enc.sxor(x, y) return hashes ^ int(hashlib.sha512(str(mouse) * 8).hexdigest(), 16)
def intermediate2privK(intermediate_passphrase_string): """ Steps to create new encrypted private keys given intermediate_passphrase_string from owner (so we have ownerentropy, and passpoint, but we do not have passfactor or the passphrase): """ #get ownerentropy and passpoint from the intermediate key #check the checksum en route decstring = enc.b58decode(intermediate_passphrase_string) checksum = decstring[-4:] if checksum != hashlib.sha256(hashlib.sha256( decstring[:-4]).digest()).digest()[:4]: return False, 'checksum' decodedstring = decstring[:-4] ownerentropy = decodedstring[8:16] passpoint = decodedstring[-33:] print(passpoint) #1. Set flagbyte. #Turn on bit 0x20 if the Bitcoin address will be formed by hashing the compressed public key (optional, saves space, but many Bitcoin implementations aren't compatible with it) #Turn on bit 0x04 if ownerentropy contains a value for lotsequence. #(While it has no effect on the keypair generation process, the decryption process needs this flag to know how to process ownerentropy) flagbyte = chr( 0b00100000 ) # 00 EC 1 compressed 00 future 0 has no lotsequence 00 future #2. Generate 24 random bytes, call this seedb. Take SHA256(SHA256(seedb)) to yield 32 bytes, call this factorb. seedb = os.urandom(24) seedb = b'ABCDEFGHIJKLMNOPQRSTUVWX' #seedb = bytearray(b'ABCDEFGHIJKLMNOPQRSTUVWX') #for c in seedb: print(c) factorb = hashlib.sha256(hashlib.sha256(seedb).digest()).digest() #3. ECMultiply passpoint by factorb. pub = elip.base10_multiply(enc.decode(passpoint, 256), enc.decode(factorb, 256)) #4. Use the resulting EC point as a public key and hash it into a Bitcoin address using either compressed or uncompressed public key methodology # (specify which methodology is used inside flagbyte). # This is the generated Bitcoin address, call it generatedaddress. publicKey = ('0' + str(2 + (pub[1] % 2)) + enc.encode(pub[0], 16, 64)) generatedaddress = address.publicKey2Address( publicKey) ## TODO Remember to add in the currency details here #5. Take the first four bytes of SHA256(SHA256(generatedaddress)) and call it addresshash. addresshash = hashlib.sha256( hashlib.sha256(generatedaddress).digest()).digest()[:4] #6. Now we will encrypt seedb. Derive a second key from passpoint using scrypt #Parameters: passphrase is passpoint provided from the first party (expressed in binary as 33 bytes). # salt is addresshash + ownerentropy, n=1024, r=1, p=1, length=64. The "+" operator is concatenation. encseedb = scrypt.hash(passpoint, addresshash + ownerentropy, 1024, 1, 1, 64) #7. Split the result into two 32-byte halves and call them derivedhalf1 and derivedhalf2. derivedhalf1 = encseedb[0:32] derivedhalf2 = encseedb[32:64] #8. Do AES256Encrypt(seedb[0...15] xor derivedhalf1[0...15], derivedhalf2), call the 16-byte result encryptedpart1 Aes = aes.Aes(derivedhalf2) encryptedpart1 = Aes.enc(enc.sxor(seedb[:16], derivedhalf1[:16])) #9. Do AES256Encrypt((encryptedpart1[8...15] + seedb[16...23]) xor derivedhalf1[16...31], derivedhalf2), call the 16-byte result encryptedpart2. # The "+" operator is concatenation. encryptedpart2 = Aes.enc( enc.sxor(encryptedpart1[8:16] + seedb[16:24], derivedhalf1[16:32])) #10. The encrypted private key is the Base58Check-encoded concatenation of the following, which totals 39 bytes without Base58 checksum: #0x01 0x43 + flagbyte + addresshash + ownerentropy + encryptedpart1[0...7] + encryptedpart2 input = '\x01\x43' + flagbyte + addresshash + ownerentropy + encryptedpart1[ 0:8] + encryptedpart2 checksum = hashlib.sha256(hashlib.sha256(input).digest()).digest()[:4] BIPKey = enc.b58encode(input + checksum) cnfrmcode = confirmationcode(flagbyte, addresshash, ownerentropy, factorb, derivedhalf1, derivedhalf2) return BIPKey, generatedaddress, cnfrmcode