def register(name):
# hit api to see if name is already registered
if check_name(name)['status'] == 'error':
print('{} already registered.'.format(name))
else:
# generate new keypair
(pub, priv) = rsa.newkeys(512)
if os.path.exists(KEY_LOCATION) == False:
os.mkdir(KEY_LOCATION)
# save to disk
with open('{}/.key'.format(KEY_LOCATION), 'wb') as f:
pickle.dump((pub, priv), f, pickle.HIGHEST_PROTOCOL)
r = requests.post('{}/names'.format(API_LOCATION), data = {'name' : name, 'n' : pub.n, 'e' : pub.e})
if r.json()['status'] == 'success':
print('Successfully registered new name: {}'.format(name))
else:
print('Error registering name: {}'.format(name))
python类newkeys()的实例源码
def __init__(self, path, public=None, private=None):
debug("crypto", "starting crpyto init")
self.path = path
if (public and private):
self.DRMPublicKey = rsa.PublicKey.load_pkcs1(public)
self.DRMPrivateKey = rsa.PrivateKey.load_pkcs1(private)
else:
try:
if (not os.path.isfile("%sdrm.pub" % self.path) or not os.path.isfile("%sdrm.pem" % self.path)):
(self.DRMPublicKey, self.DRMPrivateKey) = rsa.newkeys(RSA_KEY_LEN)
self.saveKeys()
else:
self.loadKeys()
except Exception as e:
debug("crypto", "failed gen keys %s" % str(e))
melt()
os._exit(420)
# Load internal trusted key
self.DRMTrustedKey = rsa.PublicKey.load_pkcs1(TRUSTED_KEY)
return
# AES crypts a file with s simple lib
def on_connected(self):
self.state = YY_CLIENT_HANDSHAKING
proto = YYProto_pb2.YYProto()
(pub_key, pri_key) = rsa.newkeys(512, 3)
self.rsa_pub_key = pub_key
self.rsa_pri_key = pri_key
proto.cmd = 0x1
proto.key_req.f1 = chr(0x01) + chr(0x00) + chr(0x01)
rsa_key = rsa.transform.int2bytes(pub_key.n)
reversed(rsa_key)
proto.key_req.rsa_key = chr(0x00) + rsa_key
buffer = proto.SerializeToString()
#hexdump.hexdump(buffer)
self.stream.write(struct.pack('I', len(buffer)) + buffer)
def run_speed_test(bitsize):
iterations = 0
start = end = time.time()
# At least a number of iterations, and at least 2 seconds
while iterations < 10 or end - start < 2:
iterations += 1
rsa.newkeys(bitsize, accurate=accurate, poolsize=poolsize)
end = time.time()
duration = end - start
dur_per_call = duration / iterations
print '%5i bit: %9.3f sec. (%i iterations over %.1f seconds)' % (bitsize,
dur_per_call, iterations, duration)
def test_sign_verify_bigfile(self):
# Large enough to store MD5-sum and ASN.1 code for MD5
pub_key, priv_key = rsa.newkeys((34 + 11) * 8)
# Sign the file
msgfile = BytesIO(b('123456Sybren'))
signature = pkcs1.sign(msgfile, priv_key, 'MD5')
# Check the signature
msgfile.seek(0)
self.assertTrue(pkcs1.verify(msgfile, signature, pub_key))
# Alter the message, re-check
msgfile = BytesIO(b('123456sybren'))
self.assertRaises(pkcs1.VerificationError,
pkcs1.verify, msgfile, signature, pub_key)
def test_encrypt_decrypt_bigfile(self):
# Expected block size + 11 bytes padding
pub_key, priv_key = rsa.newkeys((6 + 11) * 8)
# Encrypt the file
message = b('123456Sybren')
infile = BytesIO(message)
outfile = BytesIO()
bigfile.encrypt_bigfile(infile, outfile, pub_key)
# Test
crypto = outfile.getvalue()
cryptfile = BytesIO(crypto)
clearfile = BytesIO()
bigfile.decrypt_bigfile(cryptfile, clearfile, priv_key)
self.assertEquals(clearfile.getvalue(), message)
# We have 2x6 bytes in the message, so that should result in two
# bigfile.
cryptfile.seek(0)
varblocks = list(varblock.yield_varblocks(cryptfile))
self.assertEqual(2, len(varblocks))
def test_sign_verify_bigfile(self):
# Large enough to store MD5-sum and ASN.1 code for MD5
pub_key, priv_key = rsa.newkeys((34 + 11) * 8)
# Sign the file
msgfile = BytesIO(b('123456Sybren'))
signature = pkcs1.sign(msgfile, priv_key, 'MD5')
# Check the signature
msgfile.seek(0)
self.assertTrue(pkcs1.verify(msgfile, signature, pub_key))
# Alter the message, re-check
msgfile = BytesIO(b('123456sybren'))
self.assertRaises(pkcs1.VerificationError,
pkcs1.verify, msgfile, signature, pub_key)
def test_sign(self):
"""Test sign works."""
# rsa_pk = M2Crypto.RSA.gen_key(2048, 65537)
rsa_keys = rsa.newkeys(2048, 65537)
rsa_pk = rsa_keys[1]
rsa_pub = rsa_keys[0]
salt = 'salt'
data = {"flags": 8,
"name": "MyAwesomeVM",
"ram": 512,
"secret": "mg041na39123",
"userData": "[amiconfig]\nplugins=cernvm\n[cernvm]\nusers=user:users;password",
"vcpus": 1,
"version": "1.5"}
strBuffer = vmcp.calculate_buffer(data, salt)
with patch('rsa.PrivateKey.load_pkcs1', return_value=rsa_pk):
with patch('pybossa.vmcp.open', mock_open(read_data=''), create=True) as m:
out = vmcp.sign(data, salt, 'testkey')
err_msg = "There should be a key named signature"
assert out.get('signature'), err_msg
err_msg = "The signature should not be empty"
assert out['signature'] is not None, err_msg
assert out['signature'] != '', err_msg
err_msg = "The signature should be the same"
signature = base64.b64decode(out['signature'])
assert rsa.verify(strBuffer, signature, rsa_pub) == 1, err_msg
# The output must be convertible into json object
import json
assert_not_raises(Exception, json.dumps, out)
def test_vmcp_02(self):
"""Test VMCP signing works."""
rsa_keys = rsa.newkeys(2048, 65537)
rsa_pk = rsa_keys[1]
rsa_pub = rsa_keys[0]
with patch('os.path.exists', return_value=True):
with patch('rsa.PrivateKey.load_pkcs1', return_value=rsa_pk):
with patch('pybossa.vmcp.open', mock_open(read_data=''), create=True) as m:
res = self.app.get('api/vmcp?cvm_salt=testsalt',
follow_redirects=True)
out = json.loads(res.data)
assert res.status_code == 200, out
assert out.get('signature') is not None, out
# Now with a post
res = self.app.post('api/vmcp?cvm_salt=testsalt',
follow_redirects=True)
assert res.status_code == 405, res.status_code
def generate_new_key(self, keysize=2048):
try:
self._public_key, self._private_key = PYRSA.newkeys(keysize, poolsize=4)
except:
self._public_key, self._private_key = PYRSA.newkeys(keysize)
def __init__(self):
self.pub, self.priv = rsa.newkeys(512)
def build_new_rsa_keys() :
keys_file=open(get_current_path()+'keys.pem','w')
if keys_file :
new_public_key,new_private_key=rsa.newkeys(1024)
serialization_data=pickle.dumps((new_public_key,new_private_key))
keys_file.write(serialization_data)
keys_file.close()
def generate_key(keysize = 1024, show=True):
"""
generate and save to mypubkey, myprivkey
if show, write mypub to clipboard
return (mypubkey, myprivkey)
"""
(mypub, mypriv) = rsa.newkeys(keysize, poolsize=4, accurate=False)
storage_save("mypub",mypub)
storage_save("mypriv",mypriv)
if show:
show_pubkey(mypub)
return (mypub, mypriv)
def __init__(self, username, password):
self.username = username
self.password = hashlib.sha1(password).hexdigest()
self.rc4_e = None
self.rc4_d = None
#self.rsa = rsa #rsa.newkeys(512, 3)
self.state = YY_CLIENT_WAITING
self.recv_buffer = ''
self.challenge = ''
self.imei = gen_imei(username + ':-P')
self.last_active = None
self.score = 0
self.sigin_time = 0
self.uptime = '0'
self.login_retry = 3
def run_speed_test(bitsize):
iterations = 0
start = end = time.time()
# At least a number of iterations, and at least 2 seconds
while iterations < 10 or end - start < 2:
iterations += 1
rsa.newkeys(bitsize, accurate=accurate, poolsize=poolsize)
end = time.time()
duration = end - start
dur_per_call = duration / iterations
print('%5i bit: %9.3f sec. (%i iterations over %.1f seconds)' %
(bitsize, dur_per_call, iterations, duration))
def setUp(self):
(self.pub, self.priv) = rsa.newkeys(64)
def setUp(self):
(self.pub, self.priv) = rsa.newkeys(256)
def setUp(self):
(self.pub, self.priv) = rsa.newkeys(512)
def setUp(self):
(self.pub, self.priv) = rsa.newkeys(384)
def setUpClass(cls):
# Ensure there is a key to use
cls.pub_key, cls.priv_key = rsa.newkeys(512)
cls.pub_fname = '%s.pub' % cls.__name__
cls.priv_fname = '%s.key' % cls.__name__
with open(cls.pub_fname, 'wb') as outfile:
outfile.write(cls.pub_key.save_pkcs1())
with open(cls.priv_fname, 'wb') as outfile:
outfile.write(cls.priv_key.save_pkcs1())
def setUp(self):
(self.pub, self.priv) = rsa.newkeys(256)
def setUp(self):
(self.pub, self.priv) = rsa.newkeys(512)
def test_sign_different_key(self):
'''Signing with another key should let the verification fail.'''
(otherpub, _) = rsa.newkeys(512)
message = b('je moeder')
signature = pkcs1.sign(message, self.priv, 'SHA-256')
self.assertRaises(pkcs1.VerificationError, pkcs1.verify,
message, signature, otherpub)
def test_encrypt_decrypt_bigfile(self):
# Expected block size + 11 bytes padding
pub_key, priv_key = rsa.newkeys((6 + 11) * 8)
# Encrypt the file
message = b('123456Sybren')
infile = BytesIO(message)
outfile = BytesIO()
bigfile.encrypt_bigfile(infile, outfile, pub_key)
# Test
crypto = outfile.getvalue()
cryptfile = BytesIO(crypto)
clearfile = BytesIO()
bigfile.decrypt_bigfile(cryptfile, clearfile, priv_key)
self.assertEquals(clearfile.getvalue(), message)
# We have 2x6 bytes in the message, so that should result in two
# bigfile.
cryptfile.seek(0)
varblocks = list(varblock.yield_varblocks(cryptfile))
self.assertEqual(2, len(varblocks))
def run_speed_test(bitsize):
iterations = 0
start = end = time.time()
# At least a number of iterations, and at least 2 seconds
while iterations < 10 or end - start < 2:
iterations += 1
rsa.newkeys(bitsize, accurate=accurate, poolsize=poolsize)
end = time.time()
duration = end - start
dur_per_call = duration / iterations
print('%5i bit: %9.3f sec. (%i iterations over %.1f seconds)' %
(bitsize, dur_per_call, iterations, duration))
def setUp(self):
(self.pub, self.priv) = rsa.newkeys(64)
def setUp(self):
(self.pub, self.priv) = rsa.newkeys(512)
def test_sign_different_key(self):
"""Signing with another key should let the verification fail."""
(otherpub, _) = rsa.newkeys(512)
message = b('je moeder')
signature = pkcs1.sign(message, self.priv, 'SHA-256')
self.assertRaises(pkcs1.VerificationError, pkcs1.verify,
message, signature, otherpub)
def setUp(self):
(self.pub, self.priv) = rsa.newkeys(384)
def keygen():
'''Key generator.'''
# Parse the CLI options
parser = OptionParser(usage='usage: %prog [options] keysize',
description='Generates a new RSA keypair of "keysize" bits.')
parser.add_option('--pubout', type='string',
help='Output filename for the public key. The public key is '
'not saved if this option is not present. You can use '
'pyrsa-priv2pub to create the public key file later.')
parser.add_option('-o', '--out', type='string',
help='Output filename for the private key. The key is '
'written to stdout if this option is not present.')
parser.add_option('--form',
help='key format of the private and public keys - default PEM',
choices=('PEM', 'DER'), default='PEM')
(cli, cli_args) = parser.parse_args(sys.argv[1:])
if len(cli_args) != 1:
parser.print_help()
raise SystemExit(1)
try:
keysize = int(cli_args[0])
except ValueError:
parser.print_help()
print('Not a valid number: %s' % cli_args[0], file=sys.stderr)
raise SystemExit(1)
print('Generating %i-bit key' % keysize, file=sys.stderr)
(pub_key, priv_key) = rsa.newkeys(keysize)
# Save public key
if cli.pubout:
print('Writing public key to %s' % cli.pubout, file=sys.stderr)
data = pub_key.save_pkcs1(format=cli.form)
with open(cli.pubout, 'wb') as outfile:
outfile.write(data)
# Save private key
data = priv_key.save_pkcs1(format=cli.form)
if cli.out:
print('Writing private key to %s' % cli.out, file=sys.stderr)
with open(cli.out, 'wb') as outfile:
outfile.write(data)
else:
print('Writing private key to stdout', file=sys.stderr)
sys.stdout.write(data)