当前位置: 首页>>代码示例>>Python>>正文


Python ecdsa.SigningKey类代码示例

本文整理汇总了Python中ecdsa.SigningKey的典型用法代码示例。如果您正苦于以下问题:Python SigningKey类的具体用法?Python SigningKey怎么用?Python SigningKey使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了SigningKey类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: main

def main(argv):

    """
        Main procedure to generate C array with keys
    """

    parser = argparse.ArgumentParser(description="Generates SQLite database with"
        " keys and serial number.")
    parser.add_argument('config_file', help="project specific configuration file"
        )
    args = parser.parse_args()

    config = ConfigParser.ConfigParser()
    config.read(args.config_file)
    con = sqlite3.connect(config.get('database', 'filename'))

    while 1:
        serialno = uuid.uuid4().bytes
        oem_factory_token = '%s%s' %(serialno, '\xFF')
        customer_factory_token = '%s%s' %(serialno, '\x00\xFF')

        private_key = generate_private_key(config.get('tools', 'private_key_cmd'))
        public_key = generate_public_key(config.get('tools', 'public_key_cmd'), private_key)
        sk = SigningKey.from_der(private_key)
        pk = VerifyingKey.from_der(public_key)

        embedded_private_key = generate_private_key(config.get('tools', 'private_key_cmd'))
        embedded_public_key = generate_public_key(config.get('tools', 'public_key_cmd'), embedded_private_key)
        embedded_sk = SigningKey.from_der(embedded_private_key)
        embedded_pk = VerifyingKey.from_der(embedded_public_key)

        embedded_private_key_sig = embedded_sk.sign(oem_factory_token, hashfunc=sha256)
        assert embedded_pk.verify(embedded_private_key_sig, oem_factory_token, hashfunc=sha256)

        oem_factory_token_sig = sk.sign(oem_factory_token, hashfunc=sha256)
        assert pk.verify(oem_factory_token_sig, oem_factory_token, hashfunc=sha256)

        customer_factory_token_sig = sk.sign(customer_factory_token, hashfunc=sha256)
        assert pk.verify(customer_factory_token_sig, customer_factory_token, hashfunc=sha256)

        debug_token_sig = sk.sign(serialno, hashfunc=sha256)
        assert pk.verify(debug_token_sig, serialno, hashfunc=sha256)

        public_key_compressed = ecc_compress(pk.to_string())

        with con:
            cur = con.cursor()
            cur.execute(config.get('database', 'create'))
            cur.execute(config.get('database', 'insert'),
                        (sqlite3.Binary(private_key),
                         sqlite3.Binary(public_key),
                         sqlite3.Binary(public_key_compressed),
                         sqlite3.Binary(embedded_private_key),
                         sqlite3.Binary(embedded_public_key),
                         sqlite3.Binary(embedded_sk.to_string()),
                         sqlite3.Binary(serialno),
                         sqlite3.Binary(oem_factory_token_sig),
                         sqlite3.Binary(customer_factory_token_sig),
                         sqlite3.Binary(debug_token_sig)))
开发者ID:CurieBSP,项目名称:main,代码行数:59,代码来源:generate_factory_database.py

示例2: load_key

    def load_key(self, filename):
        """
        Load signing key (from pem file)
        """
        default_sk = SigningKey.from_pem(keys_default_pem)

        with open(filename, "r") as sk_file:
            sk_pem = sk_file.read()

        self.sk = SigningKey.from_pem(sk_pem)

        sk_hex = "".join(c.encode('hex') for c in self.sk.to_string())
        return default_sk.to_string() == self.sk.to_string()
开发者ID:Jeoy5460,项目名称:pc-nrfutil,代码行数:13,代码来源:signing.py

示例3: __init__

	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()
开发者ID:El-gitano,项目名称:otr_new,代码行数:13,代码来源:pycrypto.py

示例4: run

def run():
  key = SigningKey.from_string(get_key_from_wif(settings['wif']), SECP256k1, sha256)
  rs = compileASM(REDEEM_SCRIPT)
  txs = parsetxsfile(settings['file'])
  for tx in txs:
    tx.signatures = sign_detached(tx.tx, key, rs)
    print(",".join(tx.signatures))
开发者ID:patricklodder,项目名称:devfundtx,代码行数:7,代码来源:sign.py

示例5: makeTransaction

    def makeTransaction(self, tx, account):
        """Make Transaction"""
        if tx.outputs == None:
            raise ValueError, 'Not correct Address, wrong length.'

        if tx.attributes == None:
            tx.attributes = []

        coins = self.findUnSpentCoins(account.scriptHash)
        tx.inputs, tx.outputs = self.selectInputs(tx.outputs, coins, account, tx.systemFee)

        # Make transaction
        stream = MemoryStream()
        writer = BinaryWriter(stream)
        tx.serializeUnsigned(writer)
        reg_tx = stream.toArray()
        tx.ensureHash()
        txid = tx.hash

        # RedeenScript
        contract = Contract()
        contract.createSignatureContract(account.publicKey)
        Redeem_script = contract.redeemScript

        # Add Signature
        sk = SigningKey.from_string(binascii.unhexlify(account.privateKey), curve=NIST256p, hashfunc=hashlib.sha256)
        signature = binascii.hexlify(sk.sign(binascii.unhexlify(reg_tx),hashfunc=hashlib.sha256))
        regtx = reg_tx + '014140' + signature + '23' + Redeem_script
        # sendRawTransaction
        print regtx
        response = self.node.sendRawTransaction(regtx)
        import json
        print response
        return txid
开发者ID:AntSharesSDK,项目名称:antshares-python,代码行数:34,代码来源:Wallet.py

示例6: sign_subscription

def sign_subscription(signatory, subscription, private_key_string, public_key_string):
    """
    sign a subscription (deep hash of criteria, signatory, signature timestamp, public key)
    param signatory: Name or identifier of the signing party (the caller)
    param subscription: all fields of subscription signed
    param private_key_string: private key used for generating signature
    param public_key_string: hashed and inserted into signature block for later validation
    """
    ecdsa_signing_key = SigningKey.from_pem(private_key_string)
    signature_ts = int(time.time())
    hashed_items = []

    # append criteria for hashing
    hashed_items.append(deep_hash(subscription['criteria']))

    # append sub create timestamp for hashing
    hashed_items.append(subscription['create_ts'])

    hashed_items.append(signatory)
    hashed_items.append(signature_ts)
    hashed_items.append(public_key_string)

    verification_hash = final_hash(hashed_items)

    signature = ecdsa_signing_key.sign(verification_hash)
    digest = signature.encode('base64')

    signature_block = assemble_sig_block(subscription, signatory, public_key_string, digest, verification_hash, signature_ts)

    return signature_block
开发者ID:hanxueming126,项目名称:dragonchain,代码行数:30,代码来源:crypto.py

示例7: __init__

 def __init__(self, secret_exponent, network=BitcoinMainNet,
              *args, **kwargs):
     if not isinstance(secret_exponent, six.integer_types):
         raise ValueError("secret_exponent must be a long")
     super(PrivateKey, self).__init__(network=network, *args, **kwargs)
     self._private_key = SigningKey.from_secret_exponent(
         secret_exponent, curve=SECP256k1)
开发者ID:microfins,项目名称:bitmerchant,代码行数:7,代码来源:keys.py

示例8: recover_key

def recover_key(c1,sig1,c2,sig2,pubkey):
    #using the same variable names as in:
    #http://en.wikipedia.org/wiki/Elliptic_Curve_DSA

    curve_order = pubkey.curve.order

    n = curve_order
    s1 = int(sig1[96:],16)
    print("s1: " + str(s1))
    s2 = int(sig2[96:],16)
    print("s2: " + str(s2))
    r = int(sig1[:-96], 16)
    print("r: " + str(r))
    print("R values match: " + str(int(sig2[:-96],16) == r))

    z1 = string_to_number(sha256(c1))
    z2 = string_to_number(sha256(c2))

    #magical math stuff
    sdiff_inv = inverse_mod(((s1-s2)%n),n)
    k = ( ((z1-z2)%n) * sdiff_inv) % n
    r_inv = inverse_mod(r,n)
    da = (((((s1*k) %n) -z1) %n) * r_inv) % n
    print("Recovered Da: " + hex(da))

    #turn the private key into a signing key
    recovered_private_key_ec = SigningKey.from_secret_exponent(da, curve=NIST384p)
    return recovered_private_key_ec
开发者ID:jonathanluck,项目名称:ctfs,代码行数:28,代码来源:recover_ecdsa_key.py

示例9: create_material

 def create_material(self, bits, d=None, x=None, y=None):
     curve = self.curve_for_bits(bits)
     if d:
         return SigningKey.from_secret_exponent(d, curve)
     if x and y:
         point = ec.Point(curve.curve, x, y, curve.order)
         return VerifyingKey.from_public_point(point, curve)
开发者ID:hdknr,项目名称:jose,代码行数:7,代码来源:ec.py

示例10: test

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)
开发者ID:Javantea,项目名称:Neg9-www-resources,代码行数:25,代码来源:writeup-crypto-300-veritable_buzz_1.py

示例11: build_vectors

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 ""
开发者ID:18600597055,项目名称:hue,代码行数:32,代码来源:generate_secp256k1.py

示例12: recover_key

def recover_key(c1,sig1,c2,sig2,pubkey):
	#using the same variable names as in: 
	#http://en.wikipedia.org/wiki/Elliptic_Curve_DSA

	curve_order = pubkey.curve.order

	n = curve_order
	s1 = string_to_number(sig1[-48:])
	print "s1: " + str(s1)
	s2 = string_to_number(sig2[-48:])
	print "s2: " + str(s2)
	r = string_to_number(sig1[-96:--48])
	print "r: " + str(r)
	print "R values match: " + str(string_to_number(sig2[-96:--48]) == r)

	z1 = string_to_number(sha1(c1))
	z2 = string_to_number(sha1(c2))

	sdiff_inv = inverse_mod(((s1-s2)%n),n)
	k = ( ((z1-z2)%n) * sdiff_inv) % n
	r_inv = inverse_mod(r,n)
	da = (((((s1*k) %n) -z1) %n) * r_inv) % n

	print "Recovered Da: " + hex(da)

	recovered_private_key_ec = SigningKey.from_secret_exponent(da, curve=NIST384p)
	return recovered_private_key_ec.to_pem()
开发者ID:Javantea,项目名称:Neg9-www-resources,代码行数:27,代码来源:writeup-crypto-300-veritable_buzz_1.py

示例13: doAuthenticate

    def doAuthenticate(self, msg):
        if len(msg.args) == 1 and msg.args[0] == '+':
            log.info('%s: Authenticating using SASL.', self.network)

            if self.sasl == 'external':
                authstring = '+'
            elif self.sasl == 'ecdsa-nist256p-challenge':
                authstring = base64.b64encode(
                    self.sasl_username.encode('utf-8')).decode('utf-8')
            elif self.sasl == 'plain':
                authstring = base64.b64encode('\0'.join([
                    self.sasl_username,
                    self.sasl_username,
                    self.sasl_password
                ]).encode('utf-8')).decode('utf-8')

            self.queueMsg(ircmsgs.IrcMsg(command='AUTHENTICATE', args=(authstring,)))
        elif (len(msg.args) == 1 and msg.args[0] != '+' and
                self.sasl == 'ecdsa-nist256p-challenge'):
            try:
                private_key = SigningKey.from_pem(open(self.sasl_ecdsa_key).
                    read())
                authstring = base64.b64encode(
                    private_key.sign(base64.b64decode(msg.args[0].encode()))).decode('utf-8')
            except (BadDigestError, OSError, ValueError) as e:
                authstring = "*"

            self.queueMsg(ircmsgs.IrcMsg(command='AUTHENTICATE', args=(authstring,)))
开发者ID:AssetsIncorporated,项目名称:Limnoria,代码行数:28,代码来源:irclib.py

示例14: load_private_key

    def load_private_key(self):
        if self.private_key is None:
            msg = 'Please, specify the private_key location.'
            raise ValueError(msg)

        with open(self.private_key, 'rb') as key_file:
            return SigningKey.from_pem(key_file.read())
开发者ID:magopian,项目名称:kinto-signer,代码行数:7,代码来源:local_ecdsa.py

示例15: Make_RegisterTransaction

def Make_RegisterTransaction(Prikey, Redeem_script, Name, Issuer, Admin, Inputs, Index, Count, Amount=-0.00000001):
    '''
    Name:发行的资产名
    Issuer:发行者
    Admin:管理员
    Inputs
    Count:inputs
    Amount:发行资产总量,默认无上限-0.00000001
    '''
    Name = '5b7b276c616e67273a277a682d434e272c276e616d65273a27{0}277d5d'.format(name_to_hex(Name))
    Amount = float_2_hex(Amount)
    #不需要找零
    #Antcoin:f252a09a24591e8da31deec970871cc7678cb55023db049551e91f7bac28e27b
    Outputs = big_or_little('f252a09a24591e8da31deec970871cc7678cb55023db049551e91f7bac28e27b') + float_2_hex(Count-100) + Admin if Count > 100 else ''
    #暂时支持1个inputs之后再改,'00'为索引
    RegisterTransaction = '4060' + hex(len(Name)/2)[2:] + Name + Amount + Issuer + Admin + '0001' + big_or_little(str(Inputs)) + '00'
    if Count > 100:
        RegisterTransaction += '0001' + Outputs
    else:
        RegisterTransaction += '0000'
    GetHashForSigning = big_or_little(sha256(binascii.unhexlify(RegisterTransaction)))#txid
    #print GetHashForSigning
    sk = SigningKey.from_string(binascii.unhexlify(Prikey), curve=NIST256p, hashfunc=hashlib.sha256)
    signature = binascii.hexlify(sk.sign(binascii.unhexlify(RegisterTransaction),hashfunc=hashlib.sha256))   
    return RegisterTransaction + '014140' + signature + '23' + Redeem_script
开发者ID:AntSharesSDK,项目名称:antshares-python,代码行数:25,代码来源:Make_RegisterTransaction.py


注:本文中的ecdsa.SigningKey类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。