def generate_key():
"""
Generate private key and public key
Save as PEMs for management
:return: ECDSA Key Object - pri_key, pub_key
"""
key_path = os.path.dirname(os.path.dirname(__file__)) + '\NodeManager' + '\\'
pri_key = SigningKey.generate(curve=NIST256p)
pub_key = pri_key.get_verifying_key()
open(key_path + "private.pem", "w").write(pri_key.to_pem())
open(key_path + "public.pem", "w").write(pub_key.to_pem())
return pri_key, pub_key
python类NIST256p()的实例源码
def VerifySignature(message, signature, public_key):
Crypto.SetupSignatureCurve()
if type(public_key) is EllipticCurve.ECPoint:
pubkey_x = public_key.x.value.to_bytes(32, 'big')
pubkey_y = public_key.y.value.to_bytes(32, 'big')
public_key = pubkey_x + pubkey_y
m = message
try:
m = binascii.unhexlify(message)
except Exception as e:
logger.error("could not get m: %s" % e)
if len(public_key) == 33:
public_key = bitcoin.decompress(public_key)
public_key = public_key[1:]
try:
vk = VerifyingKey.from_string(public_key, curve=NIST256p, hashfunc=hashlib.sha256)
res = vk.verify(signature, m, hashfunc=hashlib.sha256)
return res
except Exception as e:
pass
return False
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
Make_RegisterTransaction.py 文件源码
项目:antshares-python
作者: AntSharesSDK
项目源码
文件源码
阅读 23
收藏 0
点赞 0
评论 0
def Make_IssueTransaction(Prikey, Redeem_script, Outputs, Txid):
Nonce = random.randint(268435456, 4294967295)
Nonce = hex(Nonce)[2:-1]
if len(Nonce)%2==1:
Nonce = '0'+Nonce
value = 1
if len(Outputs)> 16777215 or 'L' in Nonce:
#???,L??????
assert False
IssueTransaction = '01'+ big_or_little(Nonce) + hex(len(Outputs))[2:].zfill(6)
for o in Outputs:
IssueTransaction = IssueTransaction + big_or_little(Txid) + float_2_hex(o['value']) + big_or_little(o['scripthash'])
sk = SigningKey.from_string(binascii.unhexlify(Prikey), curve=NIST256p, hashfunc=hashlib.sha256)
signature = binascii.hexlify(sk.sign(binascii.unhexlify(IssueTransaction),hashfunc=hashlib.sha256))
return IssueTransaction + '014140' + signature + '23' + Redeem_script
Make_RegisterTransaction.py 文件源码
项目:antshares-python
作者: AntSharesSDK
项目源码
文件源码
阅读 18
收藏 0
点赞 0
评论 0
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
#RT = Make_RegisterTransaction(Prikey, Redeem_script, Name, Issuer, Admin, Inputs, Index, Count)
#print sendrawtransaction(RT)
#scripthash = '1d3871d26978d71d147ad7366e674114eeb4179c'
def Make_IssueTransaction(Prikey, Redeem_script, Outputs, Txid):
Nonce = random.randint(268435456, 4294967295)
Nonce = hex(Nonce)[2:-1]
if len(Nonce)%2==1:
Nonce = '0'+Nonce
value = 1
if len(Outputs)> 16777215 or 'L' in Nonce:
#???,L??????
assert False
IssueTransaction = '01'+ big_or_little(Nonce) + hex(len(Outputs))[2:].zfill(6)
for o in Outputs:
IssueTransaction = IssueTransaction + big_or_little(Txid) + float_2_hex(o['value']) + big_or_little(o['scripthash'])
sk = SigningKey.from_string(binascii.unhexlify(Prikey), curve=NIST256p, hashfunc=hashlib.sha256)
signature = binascii.hexlify(sk.sign(binascii.unhexlify(IssueTransaction),hashfunc=hashlib.sha256))
return IssueTransaction + '014140' + signature + '23' + Redeem_script
def verify_signature(public_key_str, signature, message):
pub_key_decode = public_key_str.decode('string_escape')
sig_decode = signature.decode('string_escape')
public_key = VerifyingKey.from_string(pub_key_decode, curve=NIST256p)
result = public_key.verify(sig_decode, message)
return result
def createECDSAKey(curve=ecdsa.NIST256p):
# Create ECDSA key
sk = ecdsa.SigningKey.generate(curve=curve)
return sk
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
def get_signer(curve):
if curve == NIST256p:
return NIST256pSigner
elif curve == NIST384p:
return NIST384pSigner
elif curve == SECP256k1:
return SECP256k1Signer
else:
raise Exception("Unknown curve: %s" % str(curve))
def __init__(self):
sign_key = SigningKey.generate(curve=NIST256p, hashfunc=sha256)
h = sha256()
h.update(sign_key.get_verifying_key().to_string())
dig = h.hexdigest().upper()[:48]
kid = ""
for i in range(0, len(dig) // 4):
kid += dig[i * 4:i * 4 + 4]
kid += ":"
kid = kid[:-1]
x = sign_key.verifying_key.pubkey.point.x()
y = sign_key.verifying_key.pubkey.point.y()
order = sign_key.verifying_key.pubkey.order
x_str = _encode(
number_to_string(x, order))
y_str = _encode(
number_to_string(y, order))
self.key = sign_key
if isinstance(x_str, six.binary_type):
x_str = x_str.decode()
self.x = x_str
if isinstance(y_str, six.binary_type):
y_str = y_str.decode()
self.y = y_str
self.kid = kid
def test_validate_invalid_vapid_key_sets_status(self, start_recording):
start_recording.is_callable().times_called(0)
other_signing_key = ecdsa.SigningKey.generate(curve=ecdsa.NIST256p)
signed_token = jws.sign(self.pa.vapid_key_token,
other_signing_key,
algorithm='ES256')
self.pa.validate_vapid_key(signed_token)
self.assertEqual(u'invalid', self.pa.vapid_key_status)
def gen_keys():
signing_key = ecdsa.SigningKey.generate(curve=ecdsa.NIST256p)
verifying_key = signing_key.get_verifying_key()
vapid_key = urlsafe_b64encode(verifying_key.to_string())
return (signing_key, verifying_key, vapid_key)
def validate_vapid_key(self, signed_token):
try:
key_data = urlsafe_b64decode(str(fix_padding(self.vapid_key)))
key_string = extract_public_key(key_data)
verifying_key = ecdsa.VerifyingKey.from_string(
key_string,
curve=ecdsa.NIST256p
)
signed_token = str(fix_padding(signed_token))
try:
submitted_claims_json = jws.verify(
signed_token, verifying_key, algorithms=['ES256']
)
submitted_claims = json.loads(submitted_claims_json)
self_claims = json.loads(self.vapid_key_token)
if submitted_claims['aud'] == self_claims['aud']:
self.vapid_key_status = 'valid'
self.validated = timezone.now()
self.save()
self.start_recording()
except JWSError:
self.vapid_key_status = 'invalid'
self.save()
except ecdsa.BadSignatureError:
self.vapid_key_status = 'invalid'
self.save()
def _get_verifying_key(self, host_key_blob):
# Parse the received data from the host_key_blob
index, host_key_type = parse_string(host_key_blob, 0)
index, curve_name = parse_string(host_key_blob, index)
index, host_public_key = parse_string(host_key_blob, index)
# Find the expected host key in ~/.ssh/known_hosts
expected_host_key_type = None
expected_host_public_key = None
known_hosts_filename = os.path.expanduser('~/.ssh/known_hosts')
for line in open(known_hosts_filename, 'r'):
if len(line.strip()) > 0:
current_hostname, current_key_type, current_key = line.split(' ')
if current_hostname == self.hostname:
expected_host_key_type = current_key_type
expected_host_public_key = current_key.decode('base64')
break
# If we *did* find the host key (i.e. we've already connected to this server), check that
# everything matches
if expected_host_key_type is not None:
assert host_key_type == expected_host_key_type, 'Unexpected host key type: %s' % host_key_type
assert curve_name == 'nistp256', 'Unknown curve name: %s' % curve_name
assert host_key_blob == expected_host_public_key, \
'Unexpected host public key: %s' % repr(host_key_blob)
# Otherwise, if we haven't seen the host key before, prompt the user to see if they're okay with
# that
else:
assert host_key_type == 'ecdsa-sha2-nistp256', 'Unknown host key type: %s' % host_key_type
key_fingerprint = hashlib.sha256(host_key_blob).digest().encode('base64')
# Remove the base64-added new lines, and the padding '=' characters
key_fingerprint = key_fingerprint.replace('\n', '').rstrip('=')
print "The authenticity of host '%s' can't be established." % self.hostname
print "ECDSA key fingerprint is SHA256:%s." % key_fingerprint
answer = raw_input("Are you sure you want to continue connecting (yes/no)?\n").strip()
while answer not in ['yes', 'no', '']:
answer = raw_input("Please type 'yes' or 'no': ").strip()
# Add key to ~/.ssh/known_hosts
if answer == 'yes':
with open(known_hosts_filename, 'a') as known_hosts_file:
host_key_base64 = host_key_blob.encode('base64').replace('\n', '')
known_hosts_file.write('%s %s %s\n' % (self.hostname, host_key_type, host_key_base64))
else:
assert False, 'Host key verification failed.'
# NFI why we need to skip a byte here - I can't find this format documented anywhere. I assume
# this is some kind of type indicator.
assert host_public_key[0] == '\x04'
return ecdsa.VerifyingKey.from_string(host_public_key[1:], curve=ecdsa.NIST256p)