本文整理汇总了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)))
示例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()
示例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()
示例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))
示例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
示例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
示例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)
示例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
示例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)
示例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)
示例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 ""
示例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()
示例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,)))
示例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())
示例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