예제 #1
0
def build_vectors(fips_vectors):
    vectors = defaultdict(list)
    for vector in fips_vectors:
        vectors[vector['digest_algorithm']].append(vector['message'])

    for digest_algorithm, messages in vectors.items():
        if digest_algorithm not in HASHLIB_HASH_TYPES:
            continue

        yield ""
        yield "[K-256,{0}]".format(digest_algorithm)
        yield ""

        for message in messages:
            # Make a hash context
            hash_func = TruncatedHash(HASHLIB_HASH_TYPES[digest_algorithm]())

            # Sign the message using warner/ecdsa
            secret_key = SigningKey.generate(curve=SECP256k1)
            public_key = secret_key.get_verifying_key()
            signature = secret_key.sign(message, hashfunc=hash_func,
                                        sigencode=sigencode_der)

            r, s = sigdecode_der(signature, None)

            yield "Msg = {0}".format(hexlify(message))
            yield "d = {0:x}".format(secret_key.privkey.secret_multiplier)
            yield "Qx = {0:x}".format(public_key.pubkey.point.x())
            yield "Qy = {0:x}".format(public_key.pubkey.point.y())
            yield "R = {0:x}".format(r)
            yield "S = {0:x}".format(s)
            yield ""
def test():
	priv = SigningKey.generate(curve=NIST384p)
	pub = priv.get_verifying_key()

	print "Private key generated:"
	generatedKey = priv.to_pem()
	print generatedKey

	txt1 = "Dedication"
	txt2 = "Do you have it?"

	#K chosen by a fair roll of a 1d10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 
	sig1 = priv.sign(txt1, k=4444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444)
	print "Signature 1: " + str(sig1.encode('hex'))
	sig2 = priv.sign(txt2, k=4444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444)
	print "Signature 2: " + str(sig2.encode('hex'))

	print "Signature 1 verification: " + str(pub.verify(sig1, txt1))
	print "Signature 2 verification: " + str(pub.verify(sig2, txt2))

	key = recover_key(txt1, sig1, txt2, sig2, pub)
	print "Private key recovered:"
	print key

	print "Equality of generated & recovered keys: " + str(generatedKey == key)
예제 #3
0
    def gen_key(self, filename):
        """
        Generate a new Signing key using NIST P-256 curve
        """
        self.sk = SigningKey.generate(curve=NIST256p)

        with open(filename, "w") as sk_file:
            sk_file.write(self.sk.to_pem())
예제 #4
0
파일: Ecdsa.py 프로젝트: maniara/SeChain
def generate_pri_key():
    seed = get_seed()
    rng1 = PRNG(seed)
    sk = SigningKey.generate(entropy=rng1, curve=NIST256p)
    sk_string = sk.to_string()

    sk_string_hex = binascii.hexlify(sk_string)

    return sk_string_hex, sk
예제 #5
0
def generate(curve):
    if curve not in _policy_.keys():
        return False
    sk = SigningKey.generate(curve=_policy_[curve][0])
    vk = sk.get_verifying_key()

    pubKey = vk.to_der()
    prvKey = sk.to_der()
    return (pubKey, prvKey)
예제 #6
0
    def setUpClass(cls):

        log.info('Generating ECDSA Keypairs for Testing')
        cls.sender_sk = SigningKey.generate(curve=curves.SECP256k1)
        cls.receiver_sk = SigningKey.generate(curve=curves.SECP256k1)

        log.info('Setup IdObj for testid')
        cls.test_id_obj = IdObject()
        cls.test_id_obj.auth_public_key = cls.receiver_sk.get_verifying_key().to_der().encode('hex')
        cls.test_id_obj.id = 'testid'
        cls.test_id_obj.paymentprotocol_only = True

        cls.resolver = PluginManager.get_plugin('RESOLVER', config.resolver_type)
        cls.resolver.save(cls.test_id_obj)
        log.info('Save testid IdObj')

        log.info('Setup Class Identifier')

        cls.identifier = None
예제 #7
0
파일: Miner.py 프로젝트: gyandh/onecoin
 def __init__(self, blockchain, id, penalty=1, selfish=False):
     self.blockchain = blockchain
     self.keypair = SigningKey.generate()
     self.id = id + 1
     self.balances = []
     self.balance = {}
     self.penalty = penalty
     self.selfish = selfish
     if selfish:
         self.selfishchain = Blockchain()
         self.privchainlen = 0
예제 #8
0
def generate_key():
    # 공개키, 개인키 생성
    pri_key = SigningKey.generate(curve=NIST256p)
    pub_key = pri_key.get_verifying_key()

    # 생성된 공인키, 개인키를 파일로 생성
    open(KEY_PATH + "/private.pem", "w",
         encoding='utf-8').write(pri_key.to_pem().decode('utf-8'))
    open(KEY_PATH + "/public.pem", "w",
         encoding='utf-8').write(pub_key.to_pem().decode('utf-8'))
    log.write("New Keys are generated")
def addrs():
	keccak = sha3.keccak_256()
	priv = SigningKey.generate(curve=SECP256k1)
	pub = priv.get_verifying_key().to_string()
	keccak.update(pub)
	address = keccak.hexdigest()[24:]
	RPriv = priv.to_string()
	Fpriv = RPriv.encode('hex')
	#Fpub = '0xdbF03B407c01E7cD3CBea99509d93f8DDDC8C6FB'
	Fpub = checksum_encode(address)
	return Fpub,Fpriv;
예제 #10
0
 def generate_keypair(to_str=True):
     '''
     Generates a keypair for a user.
     By design, this keypair is separate from the node itself, which ensures that multiple users can all use the same node.
     '''
     sk = SigningKey.generate()  # this is the signing/secret key
     vk = sk.get_verifying_key()  # this is the public/verifying key
     if to_str:
         return (sk.to_string(), vk.to_string())
     else:
         return (sk, vk)
예제 #11
0
파일: ecdsakey.py 프로젝트: InfraSIM/idic
    def generate(curve=curves.NIST256p, progress_func=None):
        """
        Generate a new private ECDSA key.  This factory function can be used to
        generate a new host key or authentication key.

        :param function progress_func: Not used for this type of key.
        :returns: A new private key (`.ECDSAKey`) object
        """
        signing_key = SigningKey.generate(curve)
        key = ECDSAKey(vals=(signing_key, signing_key.get_verifying_key()))
        return key
예제 #12
0
def instantwallet():
    sk = SigningKey.generate(curve=SECP256k1)
    vk = sk.get_verifying_key()  #public_key
    public_key = vk.to_string().hex()
    private_key = sk.to_string().hex()
    keys = []
    wallet_id = generate_wallet_from_pkey(public_key)
    keys.append(private_key)
    keys.append(wallet_id)
    keys.append(public_key)
    return keys
예제 #13
0
	def __init__(self):		
		self.privatekey = SigningKey.generate()	
		self.publickey = self.privatekey.get_verifying_key()
		self.blockhead = None
		self.maxnumtrans = 1000
		self.database = [[0] * 2 for i in range(self.maxnumtrans)]
		self.top = 0
		self.currentblock = block.block(None)
		self.blockhead = Treenode()
		self.genesis = Treenode()	# height will be zero for genesis block
		self.leafhead = self.genesis	# head of the list of leaves, points to an empty node initially
예제 #14
0
def main():
    keccak = sha3.keccak_256()
    priv = SigningKey.generate(curve=SECP256k1)
    pub = priv.get_verifying_key().to_string()

    keccak.update(pub)
    address = keccak.hexdigest()[24:]

    save_privkey(binascii.hexlify(priv.to_string()))
    save_pubkey(binascii.hexlify(pub))
    save_address(address)
예제 #15
0
파일: ecdsakey.py 프로젝트: xiar/idic
    def generate(curve=curves.NIST256p, progress_func=None):
        """
        Generate a new private ECDSA key.  This factory function can be used to
        generate a new host key or authentication key.

        :param function progress_func: Not used for this type of key.
        :returns: A new private key (`.ECDSAKey`) object
        """
        signing_key = SigningKey.generate(curve)
        key = ECDSAKey(vals=(signing_key, signing_key.get_verifying_key()))
        return key
예제 #16
0
def test_ecdh_derive_shared_secret_random():

    # Generate random keys for the two participating users
    aliceSecretKey = SigningKey.generate(curve=NIST256p)
    alice = ECDH(curve=NIST256p)
    alice.load_private_key(aliceSecretKey)
    alicePublicKey = alice.get_public_key()

    bobSecretKey = SigningKey.generate(curve=NIST256p)
    bob = ECDH(curve=NIST256p)
    bob.load_private_key(bobSecretKey)
    bobPublicKey = bob.get_public_key()

    # Each user derives the same shared secret, independantly, using the other's public key which is exchanged
    aliceSecret = derive_shared_secret_from_key(aliceSecretKey, bobPublicKey)
    print("Alice secret: ", aliceSecret.hex())
    bobSecret = derive_shared_secret_from_key(bobSecretKey, alicePublicKey)
    print("Bob secret: ", bobSecret.hex())

    assert aliceSecret == bobSecret, "Both parties should generate the same secret"
예제 #17
0
 def __init__(self,
              walletFileLocation,
              initWallet=False,
              walletName='default'):
     if initWallet:
         self.privKey = SigningKey.generate()
         self.pubKey = self.privKey.verifying_key
         self.walletName = walletName
         self.dump_wallet(walletFileLocation)
     else:
         self.load_wallet(walletFileLocation)
예제 #18
0
def generate_eth_wallet():
    from ecdsa import SigningKey, SECP256k1
    privkey = SigningKey.generate(curve=SECP256k1)
    public = privkey.get_verifying_key().to_string()

    import sha3
    keccak = sha3.keccak_256()
    keccak.update(public)
    address = keccak.hexdigest()[24:]

    return {"address": f"0x{address}", "privkey": privkey.to_string().hex()}
예제 #19
0
def create_eth_address():
    keccak = sha3.keccak_256()

    priv = SigningKey.generate(curve=SECP256k1)
    pub = priv.get_verifying_key().to_string()

    keccak.update(pub)
    address = keccak.hexdigest()[24:]

    return {'private_key': priv.to_string().hex(),
            'public_key': pub.hex(),
            'address': checksum_encode(address)}
예제 #20
0
    def setUpClass(cls):

        log.info('Generating ECDSA Keypairs for Testing')
        cls.sender_sk = SigningKey.generate(curve=curves.SECP256k1)
        cls.receiver_sk = SigningKey.generate(curve=curves.SECP256k1)

        log.info('Setup IdObj for testid')
        cls.test_id_obj = IdObject()
        cls.test_id_obj.auth_public_key = cls.receiver_sk.get_verifying_key(
        ).to_der().encode('hex')
        cls.test_id_obj.id = 'testid'
        cls.test_id_obj.paymentprotocol_only = True

        cls.resolver = PluginManager.get_plugin('RESOLVER',
                                                config.resolver_type)
        cls.resolver.save(cls.test_id_obj)
        log.info('Save testid IdObj')

        log.info('Setup Class Identifier')

        cls.identifier = None
예제 #21
0
def genETHAddr():
    keccak = sha3.keccak_256()

    priv = SigningKey.generate(curve=SECP256k1)
    pub = priv.get_verifying_key().to_string()

    keccak.update(pub)
    address = keccak.hexdigest()[24:]

    g_logger.info("Private key: %s" % priv.to_string().hex())
    g_logger.info("Public key: %s"  % pub.hex())
    g_logger.info("Address: 0x%s"  % address)
예제 #22
0
def create_key(dir):
    #Generating Alice's private
    if (os.path.isdir(dir) == False):
        os.mkdir(dir)
    sk = SigningKey.generate(curve=SECP256k1)
    vk = sk.verifying_key
    sha3_key = hashlib.sha3_256()
    sha3_key.update(vk.to_string())
    hash = sha3_key.digest()
    with open(os.path.join(dir, uuid.uuid4().hex), "wb") as f:
        f.write(sk.to_pem())
    return hash, sk
예제 #23
0
파일: wallet.py 프로젝트: cnspica/Openchain
    def __init__(self, private_key: str = None, public_key: str = None):
        if private_key is None:
            self.private_key = SigningKey.generate(curve=SECP256k1)
        else:
            self.private_key = SigningKey.from_string(
                bytes.fromhex(private_key), curve=SECP256k1)

        if public_key is None:
            self.public_key = self.private_key.get_verifying_key()
        else:
            self.public_key = VerifyingKey.from_string(
                bytes.fromhex(public_key), curve=SECP256k1)
예제 #24
0
def generate_key():
    # 공개키, 개인키 생성
    pri_key = SigningKey.generate(curve=NIST256p)
    pub_key = pri_key.get_verifying_key()

    # 생성된 공인키 개인키를 파일로 생성
    open(PRI_KEY_PATH, "w",
         encoding='utf-8').write(pri_key.to_pem().decode('utf-8'))
    open(PUB_KEY_PATH, "w",
         encoding='utf-8').write(pub_key.to_pem().decode('utf-8'))

    return pri_key, pub_key
    def generate_keys():
        try:
            # uses NIST192p as the curve
            private_key = SigningKey.generate()
            public_key = private_key.verifying_key

            private_key_string = private_key.to_string().hex()
            public_key_string = public_key.to_string().hex()

            return private_key_string, public_key_string
        except Exception as e:
            capture_exception(e)
def new_wallet():
    keccak = sha3.keccak_256()
    priv = SigningKey.generate(curve=SECP256k1)
    pub = priv.get_verifying_key().to_string()
    keccak.update(pub)
    address = keccak.hexdigest()[24:]
    privkey = priv.to_string().hex()
    pubkey = pub.hex()
    addr = checksum_encode(address)
    data = [{'privkey': privkey, 'pubkey': pubkey, 'addr': addr}]
    data_string = json.dumps(data)
    return data_string
예제 #27
0
파일: keys.py 프로젝트: wking/openbadgeslib
    def generate_keypair(self):
        """ Generate a ECDSA keypair """

        # Private key generation
        self.priv_key = SigningKey.generate(curve=self._key_curve)
        priv_key_pem = self.priv_key.to_pem()

        # Public Key name is the hash of the public key
        self.pub_key = self.priv_key.get_verifying_key()
        pub_key_pem = self.pub_key.to_pem()

        return priv_key_pem, pub_key_pem
예제 #28
0
def get_new_ring_keys(ring_size: int, j: int):
    keys = []
    # Generate a bunch of keys
    for i in range(ring_size):
        k = SigningKey.generate(curve=ecdsa.SECP256k1)
        if i == j:
            keys.append((k.privkey.secret_multiplier,
                         k.get_verifying_key().pubkey.point))
        else:
            keys.append((None, k.get_verifying_key().pubkey.point))

    return keys
예제 #29
0
    def __init__(self, signing_key=None):
        self.signing_key = signing_key or SigningKey.generate(curve=NIST256p)

        pk_point = self.signing_key.verifying_key.pubkey.point
        self.proof_field = {
            'use': 'sig',
            'alg': 'ES256',
            'kty': 'EC',
            'crv': 'P-256',
            'x': self.__encode_ec_coord(pk_point.x()),
            'y': self.__encode_ec_coord(pk_point.y())
        }
예제 #30
0
def generate_keys():
    """ Gets a new  elliptic curve key pair using the SECP256K1 elliptic curve (the one used by Bitcoin).

    :return: elliptic curve key pair.
    :rtype: list
    """

    # Generate the key pair from a SECP256K1 elliptic curve.
    sk = SigningKey.generate(curve=SECP256k1)
    pk = sk.get_verifying_key()

    return sk, pk
예제 #31
0
def generate_new_key_pair():

    # Private key
    signing_key = SigningKey.generate(
        curve=SECP256k1,
        hashfunc=sha256,
    )

    # Public key
    verifying_key = signing_key.get_verifying_key()

    return signing_key, verifying_key
예제 #32
0
def generate_privateKey() -> bytes:
    '''
    Create a random number(32 bytes) as private key.

    Returns
    -------
    bytes
        The private key in 32 bytes format.
    '''
    while True:
        _a = SigningKey.generate(curve=SECP256k1)
        if _is_valid_private_key(_a.to_string()):
            return _a.to_string()
예제 #33
0
    def generate_key(self):
        """
        create keypair, program_id and jid
        """

        signingkey = SigningKey.generate(curve=NIST256p)
        sk_text = "private-jid0-%s" % my_b32encode(signingkey.to_string())
        verifyingkey = signingkey.get_verifying_key()
        vk_text = "public-jid0-%s" % my_b32encode(verifyingkey.to_string())
        self.jid = vk_to_jid(verifyingkey)
        self.program_id = jid_to_programid(self.jid)
        self.private_key = sk_text
        self.public_key = vk_text
예제 #34
0
def generate_legal_key():
    """
    Ensure that we don't have 0xFFFF in the hash of the public key of
    the generated keypair.

    :return: A key who's SHA256 digest does not contain 0xFFFF
    """
    while True:
        key = SigningKey.generate(curve=NIST256p)
        digest = sha256(key.get_verifying_key().to_string()).digest()[:16]
        if not (any([digest[n:n + 2] == b'\xff\xff'
                     for n in range(0, len(digest), 2)])):
            return key
예제 #35
0
def generate_wallet() -> Dict[str, str]:
    keccak = sha3.keccak_256()
    priv = SigningKey.generate(curve=SECP256k1)
    pub = priv.get_verifying_key().to_string()
    keccak.update(pub)
    address = keccak.hexdigest()[24:]

    wallet = {
        'private': priv.to_string().hex(),
        'public': pub.hex(),
        'address': w3.toChecksumAddress(address),
    }
    return wallet
def get_signing_key():
    if not os.path.exists(private):
        print('Creating private key %r' % private)
        sk0 = SigningKey.generate(curve=curve)
        with open(private, 'w') as f:
            f.write(sk0.to_pem())

        vk = sk0.get_verifying_key()
        with open(public, 'w') as f:
            f.write(vk.to_pem())
    pem = open(private).read()
    sk = SigningKey.from_pem(pem)
    return sk
예제 #37
0
	def __init__(self, key=None):
		
		self.secretKey = self.verifKey = None
		
		# Recuperation
		if key is not None:
			self.secretKey = SigningKey.from_string(key, curve=NIST384p)
		
		# Auto-generation	
		else:
			self.secretKey = SigningKey.generate(curve=NIST384p)
			
		self.verifKey = self.secretKey.get_verifying_key()
예제 #38
0
def generateKeys():
    # SECP256k1 is the Bitcoin elliptic curve
    private_key = SigningKey.generate(curve=SECP256k1)
    public_key = private_key.get_verifying_key()

    file_out = open("private.pem", "wb")
    file_out.write(private_key.to_pem())

    file_out = open("public.pem", "wb")
    file_out.write(public_key.to_pem())

    print(base64.b64encode(private_key.to_string()))
    print(str(base64.b64encode(public_key.to_string()), "utf-8"))
예제 #39
0
def generate_edsca_hexkeypair() -> HexKeyPair:
    """
    Generates an EDSCA public private key pair.
    The values are returned as strings for easy
    serialization.

    :return: A HexKeyPair tuple
    """
    private = SigningKey.generate(curve=ECDSA_CURVE)
    public = private.get_verifying_key()
    private_string = (private.to_string()).hex()
    public_string = (public.to_string()).hex()
    return _hexkeypair(public_string, private_string)
    def __init__(self, signing_key=None, signing_policy=None):
        self.signing_key = signing_key or SigningKey.generate(curve=NIST256p)
        self.signing_policy = signing_policy or DEFAULT_SIGNING_POLICY

        pk_point = self.signing_key.verifying_key.pubkey.point
        self.proof_field = {
            "use": "sig",
            "alg": self.signing_policy.supported_algorithms[0],
            "kty": "EC",
            "crv": "P-256",
            "x": self.__encode_ec_coord(pk_point.x()),
            "y": self.__encode_ec_coord(pk_point.y()),
        }
예제 #41
0
    def generate(curve=curves.NIST256p, progress_func=None):
        """
        Generate a new private RSA key.  This factory function can be used to
        generate a new host key or authentication key.

        :param function progress_func:
            an optional function to call at key points in key generation (used
            by ``pyCrypto.PublicKey``).
        :returns: A new private key (`.RSAKey`) object
        """
        signing_key = SigningKey.generate(curve)
        key = ECDSAKey(vals=(signing_key, signing_key.get_verifying_key()))
        return key
예제 #42
0
파일: encryptator.py 프로젝트: magarcia/C
def generate_ECC_key(args):
    '''
    Generate an ECC keypair in PEM format
    '''
    from ecdsa import SigningKey

    curve = getattr(__import__('ecdsa'), args.curve)
    private_key = SigningKey.generate(curve=curve)
    public_key = private_key.get_verifying_key()

    with open('privateEC.pem', 'wb') as key_file:
        key_file.write(private_key.to_pem())

    with open('publicEC.pem', 'wb') as key_file:
        key_file.write(public_key.to_pem())
예제 #43
0
	def generate_key(self):
		"""
		create keypair, program_id and jid
		"""
		from ecdsa import SigningKey, NIST256p
		from cuddlefish.preflight import vk_to_jid, jid_to_programid, my_b32encode

		sk = SigningKey.generate(curve=NIST256p)
		sk_text = "private-jid0-%s" % my_b32encode(sk.to_string())
		vk = sk.get_verifying_key()
		vk_text = "public-jid0-%s" % my_b32encode(vk.to_string())
		self.jid = vk_to_jid(vk)
		self.program_id = jid_to_programid(self.jid)
		self.private_key = sk_text
		self.public_key = vk_text
예제 #44
0
 def generateMN(self, nums): 
     global_list = {}
     for i in range(nums):
         utxoamount = 123
         hashrate = 11.23
         externalip = '192.168.1.7' + str(i)
         g_ListIP[i] = externalip
         #privkey = '121A23AFF0B9440C3BA4C7CA6E424DB7BD85FEC5F33010DDD96BEE45B4DBF482'
         if USE_ECDSA == 1:
             privkey = SigningKey.generate()
         else:
             privkey = get_random_str(64)    # modi by zheng            
         txid = ''.join(random.choice('0123456789abcdef') for _ in range(32))
         uptime = time.time() - random.randint(0, 100000)
         global_list[txid] = ListNode(utxoamount, hashrate, externalip, privkey, txid, uptime)
     return global_list
예제 #45
0
def generate_new_key_pair():
    """
    Generate a new key pair.

    Returns:
        tuple(:py:class:`ecdsa.keys.SigningKey`,
              :py:class:`ecdsa.keys.VerifyingKey`):
        key pair (private, public).
    """

    private_key = SigningKey.generate(
        curve=SECP256k1,
        hashfunc=sha256,
    )

    return private_key, private_key.get_verifying_key()
예제 #46
0
def main(args):
    message = "Hello, P2PSP!" * 1024
    sk = SigningKey.generate()
    vk = sk.get_verifying_key()
    # measure the sign time
    start_time = time.time()
    for _ in xrange(N):
        sig = sign(message, sk)
    print "key.sign x{0} times: {1}s".format(N, time.time() - start_time)

    #measure the verify time
    sig = sign(message, sk)
    start_time = time.time()
    for _ in xrange(N):
        r = check(message, vk, sig)
    print "key.verify x{0} times: {1}s".format(N, time.time() - start_time)
예제 #47
0
    def generate(curve=curves.NIST256p, progress_func=None):
        """
        Generate a new private RSA key.  This factory function can be used to
        generate a new host key or authentication key.

        @param bits: number of bits the generated key should be.
        @type bits: int
        @param progress_func: an optional function to call at key points in
            key generation (used by C{pyCrypto.PublicKey}).
        @type progress_func: function
        @return: new private key
        @rtype: L{RSAKey}
        """
        signing_key = SigningKey.generate(curve)
        key = ECDSAKey(vals=(signing_key, signing_key.get_verifying_key()))
        return key
예제 #48
0
 def new(cls, string=None):
     """Returns a new Address object.
     If a string is passed, the Address object will be
     created using that string and will be deterministic.
     If no string is passed, the Address object will
     be generated randomly.
     """
     # Generates warner ECDSA objects
     if string:
         # deterministic private key
         ecdsaPrivkey = SigningKey.from_string(
             string=string, curve=SECP256k1)
     else:
         # random private key
         ecdsaPrivkey = SigningKey.generate(
             curve=SECP256k1, entropy=None)
     return cls.fromPrivkey(ecdsaPrivkey)
예제 #49
0
def create_key(keydir, name):
    # return jid
    from ecdsa import SigningKey, NIST256p
    sk = SigningKey.generate(curve=NIST256p)
    sk_text = "private-jid0-%s" % my_b32encode(sk.to_string())
    vk = sk.get_verifying_key()
    vk_text = "public-jid0-%s" % my_b32encode(vk.to_string())
    jid = vk_to_jid(vk)
    program_id = jid + "@jetpack"
    # save privkey to ~/.jetpack-keys/$jid
    f = open(os.path.join(keydir, jid), "w")
    f.write("private-key: %s\n" % sk_text)
    f.write("public-key: %s\n" % vk_text)
    f.write("jid: %s\n" % jid)
    f.write("program-id: %s\n" % program_id)
    f.write("name: %s\n" % name)
    f.close()
    return jid
예제 #50
0
    def __init__(self, public_key=None, private_key=None):
        self.id = 0
        if public_key is not None:
            public_key = "#" + public_key

        if private_key is not None:
            private_key = "#" + private_key

        self.public_key = auto_bytes(public_key)
        self.private_key = private_key
        self.addr_version = None
        self.use_compression = 1
        if private_key == "":
            private_key = None

        #Generate key pairs.
        if self.public_key == None and private_key == None:
            self.sign_key = SigningKey.generate(curve=SECP256k1)
            self.verify_key = self.sign_key.get_verifying_key()
            self.private_key = self.sign_key.to_string()
            self.public_key = self.verify_key.to_string()
            return

        #Init public key.
        self.old_verify_str = None
        if self.public_key != None:
            self.public_key = self.parse_public_key(self.public_key)
            self.verify_key = VerifyingKey.from_string(self.public_key, SECP256k1)
            self.sign_key = None
            self.old_verify_str = self.verify_key.to_string()

        #Init private key.
        if self.private_key != None:
            #Construct keys from private key.
            self.private_key = self.parse_private_key(private_key)
            self.sign_key = SigningKey.from_string(self.private_key, SECP256k1) 
            self.verify_key = self.sign_key.get_verifying_key()

            #Check private key corrosponds to public key.
            if self.old_verify_str != None:
                if self.old_verify_str != self.verify_key.to_string():
                    raise Exception("Private key doesn't corrospond to stored public key.")
예제 #51
0
    def setUp(self):

        # Generate a signing key used for refund output retrieval in get_refund_addresses()
        self.receiver_sk = SigningKey.generate(curve=curves.SECP256k1)

        log.info('Setup IdObj for testid')
        self.test_id_obj = IdObject()
        self.test_id_obj.id = 'testid'
        self.test_id_obj.bip70_enabled = True
        self.test_id_obj.wallet_address = '1MSK1PMnDZN4SLDQ6gB4c6GKRExfGD6Gb3'
        self.test_id_obj.x509_cert = TEST_CERT
        self.test_id_obj.private_key = TEST_CERT_PRIVKEY
        self.test_id_obj.auth_public_key = self.receiver_sk.get_verifying_key().to_string().encode('hex')

        self.resolver = PluginManager.get_plugin('RESOLVER', config.resolver_type)
        self.resolver.save(self.test_id_obj)
        log.info('Save testid IdObj')

        # Keep track of PaymentRequest meta data stored in Redis so it can be cleaned up later
        self.redis_pr_store_cleanup = []
예제 #52
0
def generate(currency='btc', secret=None, compressed=False):
    """Generate address pair for currency. (Default: BTC)

    :currency: string, 3 letter currency code
    :secret: string, seed for private address
    :compressed: bool, if key pair is on compresses format or not
    :returns: tuple, (private_key, public_key) containing representation in hex and base58 format.

    """
    from ecdsa import SigningKey, SECP256k1

    if secret:
        h = hashlib.sha256(secret).hexdigest()
        secret_exp = int(h, 16)
        sk = SigningKey.from_secret_exponent(secret_exp, curve=SECP256k1)
    else:
        sk = SigningKey.generate(curve=SECP256k1)

    priv = sk.to_string()
    pub = sk.get_verifying_key()

    if compressed:
        priv = priv + '\x01'
        if pub.pubkey.point.y() % 2:
            prefix = '\x03'
        else:
            prefix = '\x02'
        pub = prefix + pub.to_string()[0:32]
    else:
        pub = '\x04' + pub.to_string()

    priv_hex = priv.encode('hex')
    priv_b58 = from_hash160(priv_hex, typ='priv', currency=currency)

    pub_hex = sha256hash160(pub).encode('hex')
    pub_b58 = from_hash160(pub_hex, currency=currency)

    return Key(hex=priv_hex, b58=priv_b58), Key(hex=pub_hex, b58=pub_b58)
예제 #53
0
def identityCreation():
    print art
    print "\nIdentity Creation Script - Block SSL\n"
    keybaseCheck()
    ans1 = raw_input("Do you own a Keybase.io account? [Y]es [N]o, default: [Y]\n")
    if ans1 == "Y" or ans1 == "y" or ans1 == "" or ans1 == " ":
        os.system("keybase version") #check for keybase version
        print "Checking for Updates...\n"
        os.system("echo 3 | keybase update check >/dev/null 2>&1") #check for keybase updates without terminal output
        os.system("keybase login") #login to keybase through terminal
    else:
        os.system("keybase version")
        print "Checking for Updates...\n"
        os.system('echo 3 | keybase update check >/dev/null 2>&1')
        os.system("keybase signup") #signup to keybase through terminal
    keccak = sha3.keccak_256()
    ex = raw_input("Do you already own an Ethereum address that you want to use? [Y]es [N]o, default: [Y]")
    if ex == "Y" or ex == "y" or ex == "" or ex == " ":
        gen_priv = raw_input("Which is your private key? (in hexadecimal format)\n")  #Private Key of the owner
        gen_priv = BitcoinPrivateKey(gen_priv)
        print "Saving to Generation_Private.pem file..."
        open("Generation_Private.pem", "w").write(gen_priv.to_pem())  #Saving to file
        print "Generating \"Generation\" Public Key..."
        gen_pub = gen_priv.get_verifying_key()  #Generate the "Generation" public key from gen_priv
        print "Saving to Generation_Public.pem file..."
        open("Generation_Public.pem", "w").write(gen_pub.to_pem())  #Saving to file
        print "Public/Private key pair creation:"
        print "Warning: This is a pseudo-random generation."
        print "Warning: If you want complete randomness consider other ways of Public/Private key pair generation."
        gen_pub = gen_pub.to_string()
        keccak.update(gen_pub)
        gen_address = keccak.hexdigest()[24:]
        open("Gen_Address.txt", "w").write("0x" + gen_address)

    else:
        print "Public/Private key pair creation:"
        print "Warning: This is a pseudo-random generation."
        print "Warning: If you want complete randomness consider other ways of Public/Private key pair generation.\n"

        print "Generating \"Generation\" Private Key..."
        gen_priv = SigningKey.generate(curve=SECP256k1)  #Generate the "Generation" private key
        print "Saving to Generation_Private.pem file..."
        open("Generation_Private.pem", "w").write(gen_priv.to_pem())  #Saving to file
        print "Generating \"Generation\" Public Key..."
        gen_pub = gen_priv.get_verifying_key()  #Generate the "Generation" public key from gen_priv
        print "Saving to Generation_Public.pem file..."
        open("Generation_Public.pem", "w").write(gen_pub.to_pem())  #Saving to file
        gen_pub = gen_pub.to_string()
        keccak.update(gen_pub)
        gen_address = keccak.hexdigest()[24:]
        open("Gen_Address.txt", "w").write("0x" + gen_address)

    print "Generating \"Certificate\" Private Key..."
    cert_priv = SigningKey.generate(curve=SECP256k1)  #Generate the "Certificate" private key
    print "Saving to Certificate_Private.pem file..."
    open("Certificate_Private.pem", "w").write(cert_priv.to_pem())  #Saving to file
    print "Generating \"Certificate\" Public Key..."
    cert_pub = cert_priv.get_verifying_key()  #Generate the "Certificate" public key from cert_priv
    print "Saving to Certificate_Public.pem file..."
    open("Certificate_Public.pem", "w").write(cert_pub.to_pem())  #Saving to file
    cert_pub = cert_pub.to_string()
    keccak.update(cert_pub)
    cert_address = keccak.hexdigest()[24:]
    open("Cert_Address.txt", "w").write("0x" + cert_address)

    print "Generating \"Revocation\" Private Key..."
    rev_priv = SigningKey.generate(curve=SECP256k1)  #Generate the "Revocation" private key
    print "Saving to Revocation_Private.pem file..."
    open("Revocation_Private.pem", "w").write(rev_priv.to_pem())  #Saving to file
    print "Generating \"Revocation\" Public Key..."
    rev_pub = rev_priv.get_verifying_key()  #Generate the "Revocation" public key from rev_priv
    print "Saving to Revocation_Public.pem file..."
    open("Revocation_Public.pem", "w").write(rev_pub.to_pem())  #Saving to file
    rev_pub = rev_pub.to_string()
    keccak.update(rev_pub)
    rev_address = keccak.hexdigest()[24:]
    open("Rev_Address.txt", "w").write("0x" + rev_address)

    print "\nYour addresses are:"
    print "\nGeneration Address: 0x" + gen_address
    print "\nCertificate Address: 0x" + cert_address
    print "\nRevocation Address: 0x" + rev_address
    os.system("echo 3 | keybase currency add --force " + cert_address + " >/dev/null 2>&1") #add cert address to keybase account - (todo)
    print "\nCertificate address added to your keybase.io account.\n"
    print "\nPlease load your Generation and Revocation addresses with some ether."
    print "\nWarning: Please keep your Revocation address secret!"
    ans = raw_input("Do you want to encrypt your private key files? [Y]es [N]o, default: [Y]")
    if ans == "Y" or ans == "y" or ans == "" or ans == " ":
        password = getpass.getpass("Give a strong password: "******"Generation_Private.pem")
        os.remove("Generation_Private.pem")
        encrypt_file(key, "Certificate_Private.pem")
        os.remove("Certificate_Private.pem")
        encrypt_file(key, "Revocation_Private.pem")
        os.remove("Revocation_Private.pem")
        sys.exit()
    else:
        sys.exit()
from ecdsa import SigningKey, NIST384p, VerifyingKey, BadSignatureError
from ecdsa.util import randrange_from_seed__trytryagain, PRNG
import os


# sk = SigningKey.generate() -> uses NIST192p
sk = SigningKey.generate(curve=NIST384p)
vk = sk.get_verifying_key()
signature = sk.sign(b"MANAN PAL")
print(vk.verify(signature, b"MANAN PAL"))
print(sk.to_string())
sk_pem = sk.to_pem()
vk_pem = vk.to_pem()


'''
def make_key(seed):
    secexp = randrange_from_seed__trytryagain(seed, NIST384p.order)
    return SigningKey.from_secret_exponent(secexp, curve=NIST384p)

seed = os.urandom(NIST384p.baselen) # or other starting point
sk1a = make_key(seed)
sk1b = make_key(seed)
# note: sk1a and sk1b are the same key
sk2 = make_key(b"2-"+seed)  # different key
'''

'''
#entropy (produces a strong pseudo-random stream)
rng1 = PRNG("seed")
sk1 = SigningKey.generate(entropy=rng1)
예제 #55
0
def gen_private_ecdsa():
    from ecdsa import SigningKey
    sk = SigningKey.generate()
    return sk.to_pem()
예제 #56
0
파일: profiling_2.py 프로젝트: CeON/pmpi
def test():
    initialise_database('test_database_file')

    private_keys = [SigningKey.generate() for _ in range(3)]
    public_keys = [PublicKey.from_signing_key(private_key) for private_key in private_keys]
    uuids = [uuid4() for _ in range(3)]

    # BUILD    
    # blocks = add_blocks()
    #
    # for block in blocks:
    #     block.put()
    #
    # block_chain = BlockChain()
    #
    # block_chain_records_pattern = [
    #     BlockChain.Record(1, b'\x00'*32, [blocks[1].id]),
    #     BlockChain.Record(2, blocks[0].id, [blocks[2].id]),
    #     BlockChain.Record(3, blocks[1].id, sorted([blocks[3].id, blocks[4].id])),
    #     BlockChain.Record(4, blocks[2].id, [blocks[5].id]),
    #     BlockChain.Record(4, blocks[2].id, [blocks[6].id]),
    #     BlockChain.Record(5, blocks[3].id, []),
    #     BlockChain.Record(5, blocks[4].id, [])
    # ]
    #
    # for i in range(6):
    #     assertEqual(block_chain.get(blocks[i].id), block_chain_records_pattern[i])

    # UPDATE BLOCKS
    # blocks = add_blocks()
    # bc = get_blockchain()
    #
    # with patch.object(BlockChain, '_get_new_blocks', return_value=blocks):
    #     bc.update_blocks()
    #
    # assertEqual(bc.max_depth, 5)
    # assertEqual(bc.head, blocks[5].id)
    #
    # for block in blocks:
    #     assertEqual(bc.get(block.id).previous_id, block.previous_block_rev.id)

    # MULTIPLE UPDATE BLOCKS
    # blocks = add_blocks()
    # bc = get_blockchain()
    #
    # def patched_update_blocks(block_list):
    #     with patch.object(BlockChain, '_get_new_blocks', return_value=block_list):
    #         bc.update_blocks()
    #
    # for blocks_to_add, max_depth, head in (
    #         (blocks[0:2], 2, blocks[1].id),
    #         (blocks[2:3], 3, blocks[2].id),
    #         (blocks[4:5], 4, blocks[4].id),
    #         (blocks[3:4], 4, blocks[4].id),
    #         (blocks[5:6], 5, blocks[5].id),
    #         (blocks[6:7], 5, blocks[5].id)
    # ):
    #     patched_update_blocks(blocks_to_add)
    #     assertEqual(bc.max_depth, max_depth)
    #     assertEqual(bc.head, head)

    # DELETE

    blocks = add_blocks(uuids, private_keys, public_keys)
    bc = get_blockchain()

    with patch.object(BlockChain, '_get_new_blocks', return_value=blocks):
        bc.update_blocks()

    try:
        blocks[4].remove()
        raise AssertionError
    except Block.ChainOperationBlockedError:
        pass

    assert bc.max_depth == 5
    assert bc.head == blocks[5].id

    for block_to_remove, max_depth, heads in (
            (blocks[5], 5, [blocks[6].id]),
            (blocks[6], 4, [blocks[3].id, blocks[4].id]),
            (blocks[4], 4, [blocks[3].id]),
            (blocks[3], 3, [blocks[2].id]),
            (blocks[2], 2, [blocks[1].id]),
            (blocks[1], 1, [blocks[0].id]),
            (blocks[0], 0, [BlockRev().id])
    ):
        block_to_remove.remove()
        assert bc.max_depth == max_depth
        assert bc.head in heads

    with patch.object(BlockChain, '_get_new_blocks', return_value=blocks):
        bc.update_blocks()

    assert bc.max_depth == 5
    assert bc.head == blocks[5].id

    assert sorted([op.uuid for op in blocks[0].operations + blocks[2].operations[1:2]]) == sorted(
        Identifier.get_uuid_list())

    close_database()
    os.remove('test_database_file')
예제 #57
0
파일: keys.py 프로젝트: A-Paul/RIOT
 def generate():
     return ECDSA256P1(SigningKey.generate(curve=NIST256p))
예제 #58
0
 def generate_keypair(cls):
     sk = SigningKey.generate(curve=NIST384p)
     vk = sk.get_verifying_key()
     return sk.to_pem(), vk.to_pem()
예제 #59
0
#coding:utf-8

import sha3
import binascii
from ecdsa import SigningKey, SECP256k1

priv = SigningKey.generate(curve=SECP256k1) #生成私钥
pub = priv.get_verifying_key() #生成公钥

keccak = sha3.keccak_256()
keccak.update( pub.to_string()) #keccak_256哈希运算
address = "0x" + keccak.hexdigest()[24:]

priv_key = binascii.hexlify( priv.to_string())
pub_key = binascii.hexlify( pub.to_string())

print("Private key: " + priv_key.decode() )
print("Public key:  " + pub_key.decode() )
print("Address:     " + address)

print "#############################"

_openssl_pub_key = "04d061e9c5891f579fd548cfd22ff29f5c642714cc7e7a9215f0071ef5a5723f691757b28e31be71f09f24673eed52348e58d53bcfd26f4d96ec6bf1489eab429d"

_pub_key = _openssl_pub_key[2:]
_pub_hex = binascii.unhexlify(_pub_key)

keccak = sha3.keccak_256()
keccak.update(_pub_hex)

address = "0x" + keccak.hexdigest()[24:]