def CreatePKey(self, filename): """This function accepts the filename of the key file to write to. ........It write the private key to the specified file name without ciphering it.""" self.keypair = RSA.gen_key(self.rsakey['KeyLength'], self.rsakey['PubExponent'], self.rsakey['keygen_callback']) RSA.new_pub_key(self.keypair.pub()) self.keypair.save_key(filename, cipher=None) self.pkey = EVP.PKey(md='sha1') self.pkey.assign_rsa(self.keypair)
def get_public_key_digest(key): bio = BIO.MemoryBuffer() pub = RSA.new_pub_key(key.pub()) pub.save_key_der_bio(bio) asn1 = bio.read() bio.close() return hashlib.sha256(asn1).digest()
def construct_public_key(public_exponent, modulus, key_size): # N_PREFIX depends on key length #key_size = math.trunc(math.log(modulus, 2)) + 1 if key_size == 256: N_PREFIX = '\x00\x00\x00\x00' elif key_size == 512: N_PREFIX = '\x00\x00\x00A\x00' elif key_size == 1024: N_PREFIX = '\x00\x00\x00\x81\x00' elif (key_size == 2048) | (key_size == 2047): N_PREFIX = '\x00\x00\x01\x01\x00' elif key_size == 4096: N_PREFIX = '\x00\x00\x02\x01\x00' else: N_PREFIX = '\x00\x00\x00\x00' # E_PREFIX depends on E value if public_exponent == 65537: E_PREFIX = '\x00\x00\x00\x03' elif public_exponent == 3: E_PREFIX = '\x00\x00\x00\x01' else: E_PREFIX = '\x00\x00\x00\x00' e = E_PREFIX + big_endian(public_exponent) n = N_PREFIX + big_endian(modulus) key = RSA.new_pub_key((e, n)) return key
def _dnskey_to_rsa(key): try: # get the exponent length e_len = key[0] except IndexError: return None # python3/python2 dual compatibility if not isinstance(e_len, int): e_len = ord(e_len) offset = 1 if e_len == 0: e_len, = struct.unpack(b'!H', key[1:3]) offset = 3 # get the exponent e = bn_to_mpi(hex_to_bn(binascii.hexlify(key[offset:offset + e_len]))) offset += e_len # get the modulus n = bn_to_mpi(hex_to_bn(binascii.hexlify(key[offset:]))) # create the RSA public key rsa = RSA.new_pub_key((e, n)) pubkey = EVP.PKey() pubkey.assign_rsa(rsa) return pubkey
def _dnskey_to_rsa(key): try: # get the exponent length e_len, = struct.unpack(b'B',key[0]) except IndexError: return None offset = 1 if e_len == 0: e_len, = struct.unpack(b'!H',key[1:3]) offset = 3 # get the exponent e = b'' for c in key[offset:offset+e_len]: e += b'%02x' % struct.unpack(b'B',c)[0] e = bn_to_mpi(hex_to_bn(e)) offset += e_len # get the modulus n = b'' for c in key[offset:]: n += b'%02x' % struct.unpack(b'B',c)[0] n = bn_to_mpi(hex_to_bn(n)) # create the RSA public key rsa = RSA.new_pub_key((e,n)) pubkey = EVP.PKey() pubkey.assign_rsa(rsa) return pubkey
def _dnskey_to_rsa(key): try: # get the exponent length e_len, = struct.unpack(b'B', key[0]) except IndexError: return None offset = 1 if e_len == 0: e_len, = struct.unpack(b'!H', key[1:3]) offset = 3 # get the exponent e = b'' for c in key[offset:offset + e_len]: e += b'%02x' % struct.unpack(b'B', c)[0] e = bn_to_mpi(hex_to_bn(e)) offset += e_len # get the modulus n = b'' for c in key[offset:]: n += b'%02x' % struct.unpack(b'B', c)[0] n = bn_to_mpi(hex_to_bn(n)) # create the RSA public key rsa = RSA.new_pub_key((e, n)) pubkey = EVP.PKey() pubkey.assign_rsa(rsa) return pubkey
def construct_public_key(public_exponent, modulus, key_size): # N_PREFIX depends on key length #key_size = math.trunc(math.log(modulus, 2)) + 1 if key_size == 256 : N_PREFIX = '\x00\x00\x00\x00' elif key_size == 512 : N_PREFIX = '\x00\x00\x00A\x00' elif key_size == 1024 : N_PREFIX = '\x00\x00\x00\x81\x00' elif (key_size == 2048) | (key_size == 2047) : N_PREFIX = '\x00\x00\x01\x01\x00' elif key_size == 4096 : N_PREFIX = '\x00\x00\x02\x01\x00' else : N_PREFIX = '\x00\x00\x00\x00' # E_PREFIX depends on E value if public_exponent == 65537 : E_PREFIX = '\x00\x00\x00\x03' elif public_exponent == 3 : E_PREFIX = '\x00\x00\x00\x01' else : E_PREFIX = '\x00\x00\x00\x00' e = E_PREFIX + big_endian(public_exponent) n = N_PREFIX + big_endian(modulus) key = RSA.new_pub_key((e,n)) return key
def test_newpub(self): old = RSA.load_pub_key(self.pubkey) new = RSA.new_pub_key(old.pub()) self.assertTrue(new.check_key()) self.assertEqual(len(new), 1024) # aka 65537 aka 0xf4 self.assertEqual(new.e, b'\000\000\000\003\001\000\001')
def get_pubkey(key_file, get_pass_phrase): try: from M2Crypto import RSA except ImportError: sys.exit("Requires M2Crypto & OpenSSL") private_key = get_privatekey(key_file, get_pass_phrase) return RSA.new_pub_key(private_key.pub()).as_pem()
def __init__(self, certObj): self.hash_alg = 'sha256' self.fingerprint = certObj.get_fingerprint(self.hash_alg) self.pubkey = certObj.get_pubkey().get_rsa() # The following prevents a nasty segfault in M2Crypto # versions < .19 # TODO: Ban M2Cryto versions < 0.19 and remove this if not isinstance(self.pubkey, RSA.RSA_pub): self.pubkey = RSA.new_pub_key((self.pubkey.e, self.pubkey.n))
def test_newpub(self): old = RSA.load_pub_key(self.pubkey) log.debug('old = %s', old) log.debug('old.pub = %s', old.pub()) new = RSA.new_pub_key(old.pub()) log.debug('new = %s', new) self.assertTrue(new.check_key()) self.assertEqual(len(new), 1024) # aka 65537 aka 0xf4 self.assertEqual(new.e, '\000\000\000\003\001\000\001')
def _verify_RS(self, alg, header, sbs, signature, testKey=None): #rsa.verify(sbs, pubic_key) ## fetch the public key if testKey: pub = testKey else: pub = fetch_rsa_pub_key(header) rsa = RSA.new_pub_key((pub.get('e'), pub.get('n'))) digest = self._get_sha(alg[2:])(sbs).digest() return rsa.verify_rsassa_pss(digest, base64.urlsafe_b64decode(signature))
def load_public_key(from_url=False, e=None, n=None, url=None): if url and from_url: try: key_str = urlopen(url).read() bio = BIO.MemoryBuffer(key_str) key = RSA.load_pub_key_bio(bio) except IOError: key = None elif e and n: key = RSA.new_pub_key((e, n)) else: key = None return key
def validate_sshRSAAuthKey_key(encoded_key): decoded_key = base64.b64decode(encoded_key) if base64.b64encode(decoded_key).rstrip() != encoded_key: raise ValidationError('key has incorrect base64 encoding') # OpenSSH public keys of type 'ssh-rsa' have three parts, where each # part is encoded in OpenSSL MPINT format (4-byte big-endian bit-count # followed by the appropriate number of bits). try: # part 1: key type hardcoded value ('ssh-rsa') x = struct.unpack('>I', decoded_key[:4])[0] key_type, decoded_key = decoded_key[4:x+4], decoded_key[x+4:] except: raise ValidationError('unable to extract type from key') if key_type != 'ssh-rsa': raise ValidationError('key is not an ssh-rsa key') try: # part 2: public exponent x = struct.unpack('>I', decoded_key[:4])[0] e, decoded_key = decoded_key[:x+4], decoded_key[x+4:] except: raise ValidationError('unable to extract public exponent from key') try: # part 3: large prime x = struct.unpack('>I', decoded_key[:4])[0] n, decoded_key = decoded_key[:x+4], decoded_key[x+4:] except: raise ValidationError('unable to extract large prime from key') try: # creating a new RSA key created_key = RSA.new_pub_key((e, n)) except: raise ValidationError('unable to create key using values extracted from provided key') if encoded_key != base64.b64encode('\0\0\0\7ssh-rsa%s%s' % created_key.pub()): raise ValidationError('newly created key and provided key do not match') key_size = len(created_key) if key_size not in [1024, 2048, 4096]: raise ValidationError('key must have size 1024, 2048 or 4096 bits') fingerprint = hashlib.md5(encoded_key).hexdigest()[12:] for line in file('/usr/share/ssh/blacklist.RSA-%d' % (key_size)): if fingerprint == line.rstrip(): raise ValidationError('key is weak (debian openssl fiasco)')
def loadPublicKey(rsaNumbers): """ Loads the public key with given e and n @type rsaNumbers: tuple @param rsaNumbers: e and n @rtype: object @returns: key instance """ # try to load key try: publicKey = RSA.new_pub_key(rsaNumbers) except Exception: return False return publicKey
def gen_keys(count=10): conn = sqlite3.connect(DB_FILE) c = conn.cursor() try: for i in xrange(count): if exit.is_set(): logging.info("Interrupted!") break priv = RSA.gen_key(STRENGTH,EXPONENT) priv_pem = priv.as_pem(cipher=None) pub_pem = RSA.new_pub_key(priv.pub()).as_pem(cipher=None) c.execute('insert into device_keys (public_key,private_key) values (?,?)',(pub_pem,priv_pem)) conn.commit() logging.info("Generated %d %d-bit RSA key pairs to %s", i+1, STRENGTH, DB_FILE) except: logging.exception("Error while generating keys!") conn.rollback() finally: c.close() conn.close()
def from_string(cls, key): """ Loads an RFC 4716 formatted public key. """ pubkey = cls() if key.startswith('ssh-'): pubkey.hashed = key.split()[1] else: pubkey.hashed = key pubkey.key_type, remainder = unpack_string(pubkey.blob) if pubkey.key_type == 'ssh-rsa': e, n = get_packed_mp_ints(remainder, 2) pubkey.instance = RSA.new_pub_key((e, n)) elif pubkey.key_type == 'ssh-dss': p, q, g, y = get_packed_mp_ints(remainder, 4) pubkey.instance = DSA.set_params(p, q, g) return pubkey
def test_newpub(self): old = RSA.load_pub_key(self.pubkey) new = RSA.new_pub_key(old.pub()) assert new.check_key() assert len(new) == 1024 assert new.e == '\000\000\000\003\001\000\001' # aka 65537 aka 0xf4
from M2Crypto import RSA import base64, hashlib from kalite import settings private_key_path = settings.PROJECT_PATH + "/private_key.pem" try: private_key = RSA.load_key(private_key_path) except IOError: private_key = RSA.gen_key(2048, 65537, callback=lambda x,y,z: None) private_key.save_key(private_key_path, None) public_key = RSA.new_pub_key(private_key.pub()) def sign(message, key=None): if not key: key = private_key return key.sign(hashed(message, base64encode=False), algo="sha1") def hashed(message, base64encode=False): sha1sum = hashlib.sha1(message).digest() if base64encode: return encode_base64(sha1sum) else: return sha1sum def verify(message, signature, key=None): if not key: key = public_key try: return key.verify(hashed(message, base64encode=False), signature, algo="sha1") == 1
def deserialize_public_key(key_str): return RSA.new_pub_key(decode_base64(q) for q in key_str.split(":"))
from M2Crypto import RSA import base64, hashlib from kalite import settings private_key_path = settings.PROJECT_PATH + "/private_key.pem" try: private_key = RSA.load_key(private_key_path) except IOError: private_key = RSA.gen_key(2048, 65537, callback=lambda x, y, z: None) private_key.save_key(private_key_path, None) public_key = RSA.new_pub_key(private_key.pub()) def sign(message, key=None): if not key: key = private_key return key.sign(hashed(message, base64encode=False), algo="sha1") def hashed(message, base64encode=False): sha1sum = hashlib.sha1(message).digest() if base64encode: return encode_base64(sha1sum) else: return sha1sum def verify(message, signature, key=None): if not key: