Ejemplo n.º 1
0
def create_demo_users():
    """create demo users"""
    try:
        store = JsonStore(default_path)
        for name in demo_user_names:
            # RSA keys
            key = RSA.generate(default_key_size)
            rsa_prikey = key.exportKey('PEM')
            rsa_pubkey = key.publickey().exportKey('PEM')
            readable_rsa_prikey = rsa_prikey.decode('utf-8')
            readable_rsa_pubkey = rsa_pubkey.decode('utf-8')
            # ECC keys
            h = hash256(rsa_prikey)
            ecc_prikey = PrivateKey(bytes(bytearray.fromhex(h)))
            ecc_pubkey = ecc_prikey.pubkey
            readable_ecc_prikey = ecc_prikey.serialize()
            readable_ecc_pubkey = binascii.hexlify(
                ecc_pubkey.serialize()).decode('utf-8')
            # AES key & iv
            h = hash256(binascii.unhexlify(ecc_prikey.serialize()))
            aes_key = h[0:32]
            aes_iv = h[32:]
            # address
            address = pubkey2address(readable_ecc_pubkey)
            # save keys
            store.put(name,
                      address=address,
                      rsa_prikey=readable_rsa_prikey,
                      rsa_pubkey=readable_rsa_pubkey,
                      ecc_prikey=readable_ecc_prikey,
                      ecc_pubkey=readable_ecc_pubkey,
                      aes_key=aes_key,
                      aes_iv=aes_iv)
    except Exception as e:
        print(str(e))
Ejemplo n.º 2
0
    def get(self, request):
        private_key = PrivateKey()
        private_key_hex = private_key.serialize()
        public_key_hex = private_key.pubkey.serialize().hex()

        result = {
            'private_key': private_key_hex,
            'public_key': public_key_hex,
        }
        return JsonResponse(result)
Ejemplo n.º 3
0
def test_new_character_creation(fx_test_client, fx_session):
    privkey = PrivateKey()
    fx_test_client.post('/login',
                        data={
                            'private_key': privkey.serialize(),
                        },
                        follow_redirects=True)

    assert fx_session.query(Move).filter_by(
        user_address=get_address(privkey.pubkey),
        user_public_key=privkey.pubkey.serialize(compressed=True),
        name='create_novice').first()
Ejemplo n.º 4
0
def getDeployedSecret(dongle, masterPrivate, targetid):
	testMaster = PrivateKey(bytes(masterPrivate))
	testMasterPublic = bytearray(testMaster.pubkey.serialize(compressed=False))
	targetid = bytearray(struct.pack('>I', targetid))

	# identify
	apdu = bytearray([0xe0, 0x04, 0x00, 0x00]) + bytearray([len(targetid)]) + targetid
	dongle.exchange(apdu)

	# walk the chain 
	batch_info = bytearray(dongle.exchange(bytearray.fromhex('E050000000')))
	cardKey = batch_info[5:5 + batch_info[4]]

	# if not found, get another pair
	#if cardKey <> testMasterPublic:
	#	raise Exception("Invalid batch public key")

	# provide the ephemeral certificate
	ephemeralPrivate = PrivateKey()
	ephemeralPublic = bytearray(ephemeralPrivate.pubkey.serialize(compressed=False))
	print "Using ephemeral key " + str(ephemeralPublic).encode('hex')
	signature = testMaster.ecdsa_sign(bytes(ephemeralPublic))
	signature = testMaster.ecdsa_serialize(signature)
	certificate = bytearray([len(ephemeralPublic)]) + ephemeralPublic + bytearray([len(signature)]) + signature
	apdu = bytearray([0xE0, 0x51, 0x00, 0x00]) + bytearray([len(certificate)]) + certificate
	dongle.exchange(apdu)

	# walk the device certificates to retrieve the public key to use for authentication
	index = 0
	last_pub_key = PublicKey(bytes(testMasterPublic), raw=True)
	while True:
		certificate = bytearray(dongle.exchange(bytearray.fromhex('E052000000')))
		if len(certificate) == 0:
			break
		certificatePublic = certificate[1 : 1 + certificate[0]]
		certificateSignature = last_pub_key.ecdsa_deserialize(bytes(certificate[2 + certificate[0] :]))		
		if not last_pub_key.ecdsa_verify(bytes(certificatePublic), certificateSignature):
			if index == 0:
				# Not an error if loading from user key
				print "Broken certificate chain - loading from user key"
			else:
				raise Exception("Broken certificate chain")
		last_pub_key = PublicKey(bytes(certificatePublic), raw=True)
		index = index + 1

	# Commit device ECDH channel
	dongle.exchange(bytearray.fromhex('E053000000'))
	secret = last_pub_key.ecdh(bytes(ephemeralPrivate.serialize().decode('hex')))
	return str(secret[0:16])
Ejemplo n.º 5
0
def mk_signer_keys_addr():
    if len(sys.argv) == 2:
        path = sys.argv[1]
    else:
        path = os.path.join(sys.argv[1], "node" + sys.argv[2])
    dump_path = os.path.join(path, "signer_privkey")
    privkey = PrivateKey()
    sec_key = privkey.serialize()
    f = open(dump_path, "w")
    f.write(sec_key)
    f.close()
    auth_path = os.path.join(sys.argv[1], "signer_authorities")
    authority = encode_hex(privtopub(decode_hex(sec_key)))[2:]
    auth_file = open(auth_path, "a")
    auth_file.write(authority + "\n")
    auth_file.close()
Ejemplo n.º 6
0
def proxyDeleteApp(dongle, args):
    args.targetId = auto_int(args.targetId)
    if args.appName == None:
        raise Exception("Missing appName")
    if args.targetId == None:
        args.targetId = 0x31000002
    if args.rootPrivateKey == None:
        privateKey = PrivateKey()
        publicKey = str(
            privateKey.pubkey.serialize(compressed=False)).encode('hex')
        print "Generated random root public key : " + publicKey
        args.rootPrivateKey = privateKey.serialize().encode('ascii')

    if args.deployLegacy:
        secret = getDeployedSecretV1(dongle,
                                     bytearray.fromhex(args.rootPrivateKey),
                                     args.targetId)
    else:
        secret = getDeployedSecretV2(dongle,
                                     bytearray.fromhex(args.rootPrivateKey),
                                     args.targetId)
    loader = HexLoader(dongle, 0xe0, True, secret)
    loader.deleteApp(args.appName)
Ejemplo n.º 7
0
def main():
	# Generate keypair which we will use for signing block header
	privkey = PrivateKey()
	pubkey = privkey.pubkey

	print('Private key: {}'.format(privkey.serialize()))
	print('Public key: {}'.format(pubkey.serialize().hex()))

	# Execure Proof-of-Work for block header
	# For sake of simplicity this example uses sha256d as PoW function
	raw_header, signature = miner({
		'version': 1,
		'prev_block': "0000000000000000000000000000000000000000000000000000000000000000",
		'merkle_root': "4e9a7450cf706f05c9f7cf6b6f4c4c267e911c0d8d5066df1da4deb318637fd3",
		'timestamp': 1568015489,
		'bits': 524287999,
		'nonce': 0,
		'miner_pubkey': pubkey.serialize().hex()
	}, privkey)

	mined_hash = sha256d(raw_header + signature)
	mined_header = header_deserialize(raw_header)

	print('Block hash:', mined_hash[::-1].hex())
	print('Block nonce:', mined_header['nonce'])

	# Validate Proof-of-Work
	pow_validation = validate_target(mined_hash, mined_header['bits'])
	print('PoW validation: {}'.format(pow_validation))

	# Validate header signature
	sighash = ripemd160(raw_header)
	miner_pubkey = bytes(bytearray.fromhex(mined_header['miner_pubkey']))
	header_signature = signature[::-1]
	signature_validation = validate_signature(sighash, header_signature, miner_pubkey)
	print('Signature validation: {}'.format(signature_validation))
Ejemplo n.º 8
0
import threading
from server import Endpoint, PingMsg, CrawlServer
from secp256k1 import PrivateKey

logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)

#read threadcount from args
threadcount = 1
if len(sys.argv) == 2:
	threadcount = int(sys.argv[1])

#generate private key
k = PrivateKey(None)
with open("priv_key", 'w') as f:
	f.write(k.serialize())

#init queue and fill it with bootstraps
q = queue.Queue()
qset = queue.Queue()
q.put(Endpoint(u'52.16.188.185', 30303, 30303, bytes.fromhex("a979fb575495b8d6db44f750317d0f4622bf4c2aa3365d6af7c284339968eef29b69ad0dce72a4d8db5ebb4968de0e3bec910127f134779fbcb0cb6d3331163c"))) #geth
q.put(Endpoint(u'13.93.211.84', 30303, 30303, bytes.fromhex("3f1d12044546b76342d59d4a05532c14b85aa669704bfe1f864fe079415aa2c02d743e03218e57a33fb94523adb54032871a6c51b2cc5514cb7c7e35b3ed0a99")))
q.put(Endpoint(u'191.235.84.50', 30303, 30303, bytes.fromhex("78de8a0916848093c73790ead81d1928bec737d565119932b98c6b100d944b7a95e94f847f689fc723399d2e31129d182f7ef3863f2b4c820abbf3ab2722344d")))
q.put(Endpoint(u'13.75.154.138', 30303, 30303, bytes.fromhex("158f8aab45f6d19c6cbf4a089c2670541a8da11978a2f90dbf6a502a4a3bab80d288afdbeb7ec0ef6d92de563767f3b1ea9e8e334ca711e9f8e2df5a0385e8e6")))
q.put(Endpoint(u'174.112.32.157', 30303, 30303, bytes.fromhex("e809c4a2fec7daed400e5e28564e23693b23b2cc5a019b612505631bbe7b9ccf709c1796d2a3d29ef2b045f210caf51e3c4f5b6d3587d43ad5d6397526fa6179"))) #parity
q.put(Endpoint(u'144.76.62.101', 30303, 30303, bytes.fromhex("2676755dd8477ad3beea32b4e5a144fa10444b70dfa3e05effb0fdfa75683ebd4f75709e1f8126cb5317c5a35cae823d503744e790a3a038ae5dd60f51ee9101"))) #pyethapp
#fill queue set also
for point in list(q.queue):
	qset.put(point)

out = queue.Queue()
Ejemplo n.º 9
0
from secp256k1 import PrivateKey, PublicKey
import binascii
import sha3

N_ADDRESS_BYTES = 20
N_PUB_KEY_BYTES = 64
address = 0x6e5ab887860e199b91b92d81f418c95d9ffd32cb
key = "40dad29726f7e1b56359d2f1cc5a5365cb105b410e1108b3da65c1d97bfe6f8e"
# b = long_to_bytes(key)
privkey = PrivateKey(bytes(bytearray.fromhex(key)), raw=True)
privkey_der = privkey.serialize()
assert privkey.deserialize(privkey_der) == privkey.private_key
print "privkey", privkey.serialize()
pubkey = privkey.pubkey
pub = pubkey.serialize(compressed=False)
print "pubkey", binascii.hexlify(pub[1:])
print "pubkey", sha3.keccak_256(pub[1:]).hexdigest()[-2 * N_ADDRESS_BYTES:]
Ejemplo n.º 10
0
from ledgerblue.deployed import getDeployedSecret
from ledgerblue.hexLoader import HexLoader
import argparse

def auto_int(x):
    return int(x, 0)

parser = argparse.ArgumentParser()
parser.add_argument("--targetId", help="Set the chip target ID", type=auto_int)
parser.add_argument("--appName", help="Set the application name")
parser.add_argument("--rootPrivateKey", help="Set the root private key")
parser.add_argument("--apdu", help="Display APDU log", action='store_true')

args = parser.parse_args()

if args.appName == None:
	raise Exception("Missing appName")
if args.targetId == None:
	args.targetId = 0x31000001
if args.rootPrivateKey == None:
	privateKey = PrivateKey()
	publicKey = str(privateKey.pubkey.serialize(compressed=False)).encode('hex')
	print "Generated random root public key : " + publicKey
	args.rootPrivateKey = privateKey.serialize().encode('ascii')

dongle = getDongle(args.apdu)

secret = getDeployedSecret(dongle, bytearray.fromhex(args.rootPrivateKey), args.targetId)
loader = HexLoader(dongle, 0xe0, True, secret)
loader.deleteApp(args.appName)
Ejemplo n.º 11
0
from secp256k1 import PrivateKey
k = PrivateKey(None)
f = open("priv_key", 'w')
f.write(k.serialize())
f.close()