def RSAcryptor(publickey=None, privatekey=None, content=None): ''' Performs Public Key Encryption using RSA. `publickey`: the Public Key. `privatekey`: the Private Key. `content`: the content to be encrypted/decrypted * When `publickey` is left `None`, a Public key and a Private key are returned as tuple * When `publickey` and `content` are given but NO `privatekey` the encrypted `content` is returned * When all are given, the decrypted content is returned * Else, returns `None` ''' if not publickey: # we want to generate a public key cryptor = RSA.generate(1024, Random.new().read) publickey = cryptor.publickey().exportKey() privatekey = cryptor.exportKey() return publickey, privatekey elif publickey and not privatekey and content: # we are supposed to encrypt and send back cryptor = RSA.importKey(publickey) return cryptor.encrypt(content, 23) elif publickey and privatekey and content: # we want to decrypt the data cryptor = RSA.importKey(publickey) cryptor=RSA.importKey(privatekey) return cryptor.decrypt(content) else: return None
def __call__(self, parser, namespace, values, option_string=None): pub_key_file, priv_key_file, input_file, output_file = values pub_key = RSA.importKey(open(pub_key_file, 'r').read().rstrip('\n')) priv_key = RSA.importKey(open(priv_key_file, 'r').read().rstrip('\n')) plaintext = open(input_file, 'r').read().rstrip('\n') output_f = open(output_file, 'w') # Create a random session key and initialization vector session_key = Random.new().read( 32 ) iv = Random.new().read( 16 ) # Encrypt session key using PKCS1 OAEP public key crypto cipher = PKCS1_OAEP.new(pub_key) encrypted_session_key = cipher.encrypt(session_key + iv) output_f.write(base64.b64encode(encrypted_session_key) + '\n') # Encrypt plaintext using AES symmetric encryption plaintext = pad(plaintext) cipher = AES.new(session_key, AES.MODE_CBC, iv) ciphertext = base64.b64encode(cipher.encrypt(plaintext)) output_f.write(ciphertext + '\n') # Sign the message signature_msg = Random.new().read( 64 ) signer = PKCS1_v1_5.new(priv_key) signature = signer.sign(SHA256.new(signature_msg)) output_f.write(base64.b64encode(signature_msg) + '\n') output_f.write(base64.b64encode(signature)) print "Message encrypted!"
def Encrypt(public_file, private_file, input_file, output_file): publicContents = readfile(public_file) privateContents = readfile(private_file) pub_key = RSA.importKey(publicContents) pri_key = RSA.importKey(privateContents) msg = readfile(input_file) signature, encoded_msg, encoded_key = make_encryption(msg, pri_key, pub_key) print "Writing %s" % output_file f_msg = open(output_file, 'wb') f_msg.write(encoded_msg) f_msg.close() print "Writing %s.session" % output_file f_session = open(output_file + '.session', 'wb') f_session.write(encoded_key[0]) # Returned as a () array of one element string f_session.close() print "Writing %s.sig" % output_file f_sig = open(output_file + '.sig', 'wb') f_sig.write(str(signature[0])) # Returned as a () array of one element long f_sig.close()
def __init__(self, secret='~/.ssh/id_rsa', algorithm='rsa-sha256', allow_agent=False): assert algorithm in ALGORITHMS, "Unknown algorithm" self._agent_key = False self._rsa = False self._hash = None self.sign_algorithm, self.hash_algorithm = algorithm.split('-') if allow_agent: try: import paramiko as ssh except ImportError: import ssh keys = ssh.Agent().get_keys() self._keys = filter(is_rsa, keys) if self._keys: self._agent_key = self._keys[0] self._keys = self._keys[1:] self.sign_algorithm, self.hash_algorithm = ('rsa', 'sha1') if not self._agent_key and self.sign_algorithm == 'rsa': with open(expanduser(secret)) as fh: k = fh.read() try: rsa_key = RSA.importKey(k) except ValueError: pw = getpass('RSA SSH Key Password: '******'hmac': self._hash = HMAC.new(secret, digestmod=HASHES[self.hash_algorithm])
def certify(): if(len(sys.argv)!=2): return privf=sys.argv[1] f=open(privf,'rb') privkey=RSA.importKey(f.read()) f.close() f=urllib.urlopen('http://verify.wujianguo.org/publickey') pubkey=RSA.importKey(f.read()) f.close() text=MD5.new(Crypto.Random.get_random_bytes(128)).digest() # print(text) info='*****@*****.**'+text # info='*****@*****.**'+text signature=privkey.sign(text,'') encinfo=pubkey.encrypt(info,32) # print(signature) # print(encinfo) para=urllib.urlencode({'info':encinfo,'text':signature}) f=urllib.urlopen('http://verify.wujianguo.org/doverify',para) # print(f.read()) s=f.read() # print(s) if MD5.new(text).digest()==privkey.decrypt(eval(s)): print "OK" else: print "ERROR" f.close()
def _cipher(self): ''' Obtain a usable cipher object based on the text representation of the key loaded from the file. Allows defering the possible passphrase prompting until the key (and resulting cipher) is actually used. Downside is that if there is a more fundamental format issue with the key data, we encounter it here. ''' if not PKCS1_OAEP: raise PKCSError('PKCS1_OAEP cipher unavailable in this version of PyCrypto') if self.cipher_object: return self.cipher_object if not self.rsakey: # Construct the key object from the source - may need to prompt for passphrase try: try: self.rsakey = RSA.importKey(self.keydata, self.default_passphrase) except ValueError: if self.default_passphrase: # No need to interactively prompt - we failed raise passphrase = getpass.getpass('Enter passphrase for [%s]: ' % self.keyfile) self.rsakey = RSA.importKey(self.keydata, passphrase) except Exception as e: raise PKCSError('Unable to load key - %s' % str(e)) self.cipher_object = PKCS1_OAEP.new(self.rsakey) return self.cipher_object
def load_keyfile(self, keyfile): with open(keyfile) as handle: keydata = handle.read() try: return RSA.importKey(keydata) except ValueError: return RSA.importKey(self.load_encrypted_keydata(keydata))
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 leftclick(event): name = None select = None s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = socket.gethostname() port = 9999 s.connect((host, port)) name = listbox1.get("active") select =("SELECT name FROM public.people WHERE age = 19 ") print (select) key = RSA.importKey(open('../public.der').read()) cipher = PKCS1_OAEP.new(key) select = cipher.encrypt(select.encode('utf-8')) print("select is " ) print(select) s.send(select) names = s.recv(1024) print(names) keya = RSA.importKey(open('../private.der').read()) cipher = PKCS1_OAEP.new(keya) message = str_to_list(cipher.decrypt(names).decode('utf-8')) print(message[0][0]) s.close() text1.insert(1.0, "ваыа") name = None names=None
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 encrypt_for_master(data): # Encrypt the file so it can only be read by the bot master # 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(data) # Encrypt message using public key cipher = PKCS1_cipher.new(public_key) ciphertext = cipher.encrypt(data+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 __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 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 test_send_message(private_key, public_key): message = "Hello there" ####### encrypt message ########### key = "".join(Random.random.sample(POPULATION, 16)) iv = Random.new().read(AES.block_size) #print "iv ", iv cipher = AES.new(key, AES.MODE_CFB, iv) print "cipher: ", cipher encrypted_message = cipher.encrypt(message) print "encrypted_message: ", encrypted_message h = MD5.new() h.update(message) #print "Digest: ", h.hexdigest() #convert digest into integers H = s2n(h.hexdigest()) d = RSA.generate(2048) d = RSA.importKey(private_key) H_raised_to_d = d.decrypt(H) #print integer_d #H = H**private_key #H is the digest raised to the private key #print "H**d: ",H_raised_to_d d = RSA.importKey(public_key)
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 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 from_string(key_pem, is_x509_cert): """Construct a Verified instance from a string. Args: key_pem: string, public key in PEM format. is_x509_cert: bool, True if key_pem is an X509 cert, otherwise it is expected to be an RSA key in PEM format. Returns: Verifier instance. Raises: NotImplementedError if is_x509_cert is true. """ if is_x509_cert: from Crypto.Util.asn1 import DerSequence from Crypto.PublicKey import RSA from binascii import a2b_base64 # Convert from PEM to DER lines = key_pem.replace(" ",'').split() der = a2b_base64(''.join(lines[1:-1])) # Extract subjectPublicKeyInfo field from X.509 certificate (see RFC3280) cert = DerSequence() cert.decode(der) tbsCertificate = DerSequence() tbsCertificate.decode(cert[0]) subjectPublicKeyInfo = tbsCertificate[6] pubkey = RSA.importKey(subjectPublicKeyInfo) else: pubkey = RSA.importKey(key_pem) return PyCryptoVerifier(pubkey)
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 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 __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 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 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 decrypt(receiverPrivateKeyFile, senderPublicKeyFile, encrypted, base64Decode=False): if base64Decode: encrypted = base64.b64decode(encrypted) # base64 decode the object First signature = encrypted[:128] signed_body = encrypted[128:] encrypted_aes_key = encrypted[128:256] aes_encrypted_message = encrypted[256:] # Verifies the signed hash senderPublicKeyObj = RSA.importKey(open(senderPublicKeyFile).read()) sha1_hash = SHA256.new(signed_body) verifier = PKCS1_v1_5.new(senderPublicKeyObj) if not verifier.verify(sha1_hash, signature): return None # decrypt to get the AES key # --------------------------------------------------- receiverPrivateKeyObj = RSA.importKey(open(receiverPrivateKeyFile).read()) cipher = PKCS1_OAEP.new(receiverPrivateKeyObj) aes_key_and_iv = cipher.decrypt(encrypted_aes_key) aes_key = aes_key_and_iv[:16] iv = aes_key_and_iv[16:] # decrypt the message with AES key and iv # --------------------------------------------------- message = aes.decrypt(aes_key, iv, aes_encrypted_message) return message
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 encrypt(senderPrivateKeyFile, receiverPublicKeyFile, message, base64Encode=False): # encrypt message with AES # --------------------------------------------------- (aes_key, iv, aes_encrypted_message) = aes.encrypt(message) # print 'aes-key:' + asHex(aes_key) # print 'iv:', asHex(iv) # print 'aes_encrypted_message-' + str(len(aes_encrypted_message)) + ':', asHex(aes_encrypted_message) # sign the aes key and IV with public key of receiver # --------------------------------------------------- receiverPubKeyObj = RSA.importKey(open(receiverPublicKeyFile).read()) cipher = PKCS1_OAEP.new(receiverPubKeyObj) encrypted_aes_key = cipher.encrypt(aes_key + iv) # hash the combined encrypted aes_key and encrypted message # --------------------------------------------------- combined_aes_key_and_message = b''.join([encrypted_aes_key, aes_encrypted_message]) sha1_hash = SHA256.new(combined_aes_key_and_message) # sign the hash with private key of sender # --------------------------------------------------- senderPrivateKeyObj = RSA.importKey(open(senderPrivateKeyFile).read()) signer = PKCS1_v1_5.new(senderPrivateKeyObj) signed_hash = signer.sign(sha1_hash) # returned the whole blob # --------------------------------------------------- encrypted = b''.join([signed_hash, combined_aes_key_and_message]) if base64Encode: encrypted = base64.b64encode(encrypted) return encrypted
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 _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 __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 read_key(path, passphrase=None): with open(path, "rb") as kd: data = kd.read() if passphrase is not None: key = RSA.importKey(data, passphrase=passphrase) else: key = RSA.importKey(data) return key
def __init__(self, bits): self.check = True pkey = crypto.PKey() pkey.generate_key(crypto.TYPE_RSA, bits) open('PrivateKey.pem', 'w').write(crypto.dump_privatekey(crypto.FILETYPE_PEM,pkey)) open('PublicKey.pem', 'w').write(crypto.dump_publickey(crypto.FILETYPE_PEM, pkey)) self.priKey = RSA.importKey(open('PublicKey.pem').read()) self.pubKey = RSA.importKey(open('PrivateKey.pem').read())
def sign(self, transaction): private_key = RSA.importKey(binascii.unhexlify(self.private_key)) signer = PKCS1_v1_5.new(private_key) h = SHA.new(str(transaction).encode('utf8')) return binascii.hexlify(signer.sign(h)).decode('ascii')
def Decrypt(prikey, data): rsaKey = RSA.importKey(prikey) cipher = PKCS1_v1_5.new(rsaKey) decodeData = base64.b64decode(data) text = cipher.decrypt(decodeData, key) return text
from Crypto.PublicKey import RSA # import the private key f = open('rsakey', 'r') key = RSA.importKey(f.read()) f.close() # get public key publickey = key.publickey() # Encrypt with public key cyphertext = publickey.encrypt('Hello, Crypto', 0) # Decrypt with private key print key.decrypt(cyphertext)
import socket import struct import sys import time keya_text = b'4p\xf8ipfD(\x99\xbb\x1d\xa2k\xeb\xaf\x05\xf0\x16\xdfGK\xb8V\xd4\xf3\x17?]S\xa0{B' keya = AESGCM(keya_text) keys_text = b'\xe5Q\x92r\xe2\xfc\xde!\xa5|\x19\xb5\x99\x00\xc0\\\xe8\x0fN\xff:\xefi\x0bg\xb7\xe3\x87M\xf1`\xb1' keys = AESGCM(keys_text) keyb_text = b'}fd>@\xb21y\xd4\x88\xe0C\x9a\xab]\xd5cEL\xc5\xbc\xd9-YG\xc8\x8d\x08^r\xb9\xad' keyb = AESGCM(keyb_text) pubkey = '-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAu5CGUJIk41oMpDYzZpIS\n1YV+zWje9JhP71pYmFc6bnXysYQ5L25FVQv4NJoBmXWFWMr+gadokWmKZBUoqlTZ\ngrh/42pY8Pz+WJXrNJa5wyE6rv9HoS9MGq5sS4nvt48uKzMoHfn7zrwFSifXKYZP\nvv+Fq6+fCRZh28s5Kkv2PM1xbu1zjheC0GzPwEltqJP54/axI2W4CvWraG3SLiwy\nYT3aVpSLWRInoqhHDfMQfRSsDHaUKTT01vrSPif55FCUrGbP+4rX7c/n6huG/DJN\nsBkMGnJG9A1JO0fz8YWisgdmNI8+8rIcgYRGmCLhoZq868Sn9TAX5FgdjY/3SYbD\nBQIDAQAB\n-----END PUBLIC KEY-----' asymmetrickeya = RSA.importKey(pubkey) pubkey = '-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjggW52Zpc3rQY1sQUmju\nOqKkmkQkPFdftVj1z3yspbtC2VjrOmu8MY99tR25aPU+t7TjIlVCyJbq9f6Gpt8w\n13tBqk/zi3igc+pfjs4pqyNSWcQlV2a+3l68Zp8UGWaSIKoabs6jnM+8/u0EzlAq\nwpG/jHrc/js/PuCO4ge+6oMZ9zcn/iEc1WAGHI649VeqK/yUOpPfzqsfZE52WkrH\nBLr6sxp8E/uXA8uAeF1+p0qiL7EjrF2lvDEmA7JrTLaqnwFCfRyY4IhGNYf8dAB1\n3gKbzoeE5KBLZgVEFeWuuJIuPligdlCiKwJwHm7DSS/ujoKmwx2Z3O1DgSv+65K6\nZQIDAQAB\n-----END PUBLIC KEY-----' asymmetrickeys = RSA.importKey(pubkey) pubkey = '-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAruJ2zpbGhjr+LS1eiz2f\nMvBcOcv55vWfND+/Alz9bpuDD2xMMDVvKO9LTRjEwMzyJi6i5GBpcsDblDbu3LmN\nc2iGWW9FDmOBYDAWBQtr3UO61KMBIT2iT7NcQqhPZYFy+lQgAYH6WjASlYLq/4GP\n2qKXw1MDA8NAntFq3W3aHNWlIN2wddRWGUa6d/fl1lLKT4L6DsFftuY7GQfzrBOt\nzPBxCVv8w4mU2r+Ixergy6Qjz96GXPiQvze2ZaRxW5+Ob+P8TW+JOufyEzQB3r4w\nddjUjoHiwzj72w80oDMUS3BtiVuJg0GVkJlVmKD9SuBZdIkhAQqF9WKAhy9ouJxD\nIwIDAQAB\n-----END PUBLIC KEY-----' asymmetrickeyb = RSA.importKey(pubkey) ecdhe_cb = X25519PrivateKey.generate() ecdhe_cs = X25519PrivateKey.generate() ecdhe_ca = X25519PrivateKey.generate() sockfd = socket.socket(socket.AF_INET6, socket.SOCK_RAW, socket.IPPROTO_RAW) sockfd.setsockopt(socket.IPPROTO_IPV6, socket.IP_HDRINCL, True) initial_time = 0
def read(book, options): bookname = shash(book) bookpath = join(LOCKER_PATH, bookname) # get password first pwd = getpass('Enter password for notebook "' + book + '": ') # load private RSA key, create decryptor private_key = RSA.importKey(open(join(bookpath, PRIVATE), 'r').read(), passphrase=pwd) rsa_cipher = PKCS1_OAEP.new(private_key) # load the list of dates which have entries ledger_file = open(join(bookpath, 'ledger'), 'r') dates = [] for line in ledger_file: date = base64.b64decode(line[:-1]) dates.append(rsa_cipher.decrypt(date)) dates = uniquify(dates) # The '-F' option prints from the [F]ront of the file if 'F' in options: dates = reversed(dates) # The '-a' option prints all notes. The default behavior prints all notes # from the last day. More options to be added later. if 'a' not in options: dates = dates[-1:] messages = [] while dates: # load the note page from the last day date = dates.pop(0) filename = shash(bookname + date) note_file = open(join(bookpath, filename), 'r') messages.append((date, None)) # decompose file into messages for line in note_file: k64, m64 = line.split(' - ') # decrypt aes key aes_key = rsa_cipher.decrypt(base64.b64decode(k64)) # decode message ciphertext enc = base64.b64decode(m64) iv = enc[:BLOCK_SIZE] ciphertext = enc[BLOCK_SIZE:] # create AES decryptor aes_cipher = AES.new(aes_key, AES.MODE_CBC, iv) # decrypt msg = unpad(aes_cipher.decrypt(ciphertext)) # pull off timestamp time = msg.split('\n')[0] msg = '\n'.join(msg.split('\n')[1:]) messages.append((time, msg)) for time, msg in messages: if len(time) > 9: print bcolors.SKYBLUE + time + bcolors.ENDC else: if 'v' in options: print bcolors.GRAY + time + ':' + bcolors.ENDC, print msg
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 rsa_load_key(self, pem): key = RSA.importKey(pem) return PKCS1_v1_5.new(key)
def readkeyfile(publickeyfilename): # read the public key file. rawkey = open(publickeyfilename, mode='rb').read() # import as an RSA key key = RSA.importKey(rawkey) return key
def importKey(externKey): return RSA.importKey(externKey)
def readPEM(): h = open("/mykey.pem",'r') key = RSA.importKey(h.read()) h.close() return key
# David Chaum 1983 提出加密技术运用于现金 from Crypto.Signature import pss from Crypto.Hash import SHA256 from Crypto.PublicKey import RSA from Crypto import Random # sender can create the signatue of a message using their private key message = b"To be signed" key = RSA.importKey( open("../01blockchain explained by picture/i4PyCryptodome/d3private.pem"). read()) h = SHA256.new(message) signature = pss.new(key).sign(h) print(signature, type(signature)) print("-" * 20) key = RSA.importKey( open("../01blockchain explained by picture/i4PyCryptodome/d3public.pem"). read()) h = SHA256.new(message) verifier = pss.new(key) try: verifier.verify(h, signature) print("The signature is authentic.") except (ValueError, TypeError): print("The signature is not authentic.")
if args.signature_path is not None: 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 bin_output = subprocess.check_output(['arm-none-eabi-objcopy', '-O', 'binary', elf_file_name, bin_file_name]) with open(bin_file_name, 'rb') as in_file: input_file = in_file.read() BOOT_BLOCK_MARKER = 0xBB0110BB IMAGE_HEADER_MARKER = 0x98447902 IMAGE_HEADER_APP_CORE = 0x02794498 IMAGE_HEADER_ESCORE = IMAGE_HEADER_MARKER SSBL_OR_LEGACY_ADDRESS = 0x00000000 SSBL_STATED_SIZE = 0x3000 ZB_TARGET_ADDRESS = SSBL_STATED_SIZE * 2
"Specify both a modulus and exponent on the command line. See --help for info." ) print( RSA.construct( (args.n, args.e)).publickey().exportKey().decode("utf-8")) quit() # if dumpkey mode dump the key components then quit if args.dumpkey: if args.key is None: raise Exception( "Specify a key file to dump with --key. See --help for info.") key_data = open(args.key, 'rb').read() key = RSA.importKey(key_data) print("[*] n: " + str(key.n)) print("[*] e: " + str(key.e)) if key.has_private(): print("[*] d: " + str(key.d)) print("[*] p: " + str(key.p)) print("[*] q: " + str(key.q)) quit() if sageworks(): args.sageworks = True else: args.sageworks = False tmpfile = None if args.publickey is None and args.e is not None and args.n is not None:
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')
def decryptRSA(ciphertext, private_key): rsa_key = RSA.importKey(private_key) cipher = PKCS1_OAEP.new(rsa_key, hashAlgo=SHA256) decrypted = cipher.decrypt(base64.b64decode(ciphertext)) return decrypted
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 testImportKey6(self): """Verifies that the imported key is still a valid RSA pair""" key = RSA.importKey(self.rsaKeyDER) idem = key.encrypt(key.decrypt(b("Test")), 0) self.assertEqual(idem[0], b("Test"))
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 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)
"""Tests for letsencrypt.acme.messages2.""" import datetime import os import pkg_resources import unittest import mock import pytz from Crypto.PublicKey import RSA from letsencrypt.acme import challenges from letsencrypt.acme import jose KEY = jose.util.HashableRSAKey(RSA.importKey(pkg_resources.resource_string( 'letsencrypt.acme.jose', os.path.join('testdata', 'rsa512_key.pem')))) class ErrorTest(unittest.TestCase): """Tests for letsencrypt.acme.messages2.Error.""" def setUp(self): from letsencrypt.acme.messages2 import Error self.error = Error(detail='foo', typ='malformed') def test_typ_prefix(self): self.assertEqual('malformed', self.error.typ) self.assertEqual( 'urn:acme:error:malformed', self.error.to_partial_json()['type']) self.assertEqual( 'malformed', self.error.from_json(self.error.to_partial_json()).typ)
def save(self, recipient=None, parent=None, auto_moderators=[]): """ Save as many messages as there are recipients. Additional actions: - If it's a reply, build a conversation - Call auto-moderators - Notify parties if needed Return False if one of the messages is rejected. """ recipients = self.cleaned_data.get('recipients', []) if parent and not parent.thread_id: # at the very first reply, make it a conversation parent.thread = parent parent.save() # but delay the setting of parent.replied_at to the moderation step if parent: self.instance.parent = parent self.instance.thread_id = parent.thread_id initial_moderation = self.instance.get_moderation() initial_dates = self.instance.get_dates() initial_status = self.instance.moderation_status if recipient: if isinstance(recipient, get_user_model()) and recipient in recipients: recipients.remove(recipient) recipients.insert(0, recipient) is_successful = True for r in recipients: if isinstance(r, get_user_model()): self.instance.recipient = r else: self.instance.recipient = None self.instance.email = r #################################################################################################################################### #################################################################################################################################### #################################################################################################################################### #################################################################################################################################### #################################################################################################################################### #################################################################################################################################### #################################################################################################################################### #################################################################################################################################### #################################################################################################################################### #################################################################################################################################### #################################################################################################################################### #################################################################################################################################### #################################################################################################################################### # THIS IS WHERE I AM ADDING THINGS ------------------------------------------------------------------------------------------------------------------------------------------- Enc = gencd self.instance.encd = Enc if (Enc): pubkey = UserAttributes.objects.get( user_name=r.get_username()).publicKey pubKeyObj = RSA.importKey(pubkey) thebody = self.instance.body str1 = ''.join( random.choice(string.ascii_uppercase) for i in range(12)) self.instance.skk = ( pubKeyObj.encrypt(str1.encode(), 32)[0] ) #.decode("cp037")#(secret_string("12345", pubKeyObj)[0]) self.instance.symky = "1" #(pubKeyObj.encrypt('abcd'.encode(), 32)[0]).decode("cp437") self.instance.body = encrypt_body(thebody, str1.encode()) #------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ #################################################################################################################################### #################################################################################################################################### #################################################################################################################################### #################################################################################################################################### #################################################################################################################################### #################################################################################################################################### #################################################################################################################################### #################################################################################################################################### #################################################################################################################################### #################################################################################################################################### self.instance.pk = None # force_insert=True is not accessible from here self.instance.auto_moderate(auto_moderators) self.instance.clean_moderation(initial_status) self.instance.clean_for_visitor() m = super(BaseWriteForm, self).save() if self.instance.is_rejected(): is_successful = False self.instance.update_parent(initial_status) self.instance.notify_users(initial_status, self.site) # some resets for next reuse if not isinstance(r, get_user_model()): self.instance.email = '' self.instance.set_moderation(*initial_moderation) self.instance.set_dates(*initial_dates) return is_successful
def get_key_public(self): data = self.get_key_data_public() public_key = RSA.importKey(data) return public_key
def signature(mac, key): k = RSA.importKey(key) sig = pow(mac, k.e, k.n) sig = sig % k.n return sig
def test_encrypt_decrypt_password(self, password, mock_rsa_key): assert decrypt_password( encrypt_password(password, RSA.importKey(WEAK_KEY)), RSA.importKey(WEAK_KEY), ) == password
def Encrypt(pubkey, data): rsaKey = RSA.importKey(pubkey) cipher = PKCS1_v1_5.new(rsaKey) return base64.b64encode(cipher.encrypt(data))
def import_key_pair(self, key_data, pass_phrase): """ """ self._private_key = RSA.importKey(key_data, pass_phrase) self._public_key = self._private_key.publickey() self._signer = PKCS1_v1_5.new(self._private_key)
import base64 import urllib import urllib2 import time import json ''' 生成公钥私钥对过程: 生成私钥: openssl genrsa -out rsa_private_key.pem 1024 根据私钥生成公钥: openssl rsa -in rsa_private_key.pem -out rsa_public_key.pem -pubout 这时候的私钥还不能直接被使用,需要进行PKCS#8编码: openssl pkcs8 -topk8 -in rsa_private_key.pem -out pkcs8_rsa_private_key.pem -nocrypt 命令中指明了输入私钥文件为rsa_private_key.pem,输出私钥文件为pkcs8_rsa_private_key.pem,不采用任何二次加密(-nocrypt) ''' publickey = RSA.importKey(open('public.pem', 'r').read()) privatekey = RSA.importKey(open('pkcs8_private.pem', 'r').read()) encryptkey = '1234567890123456' class SHttp: ''' post请求 url: 参数URL values: 字典类型的参数 ''' def doPost(self, url, values): req = urllib2.Request(url) data = urllib.urlencode(values) res = urllib2.urlopen(req, data) ret = res.read()
def verify(self, transaction): public_key = RSA.importKey(binascii.unhexlify(transaction.sender)) verifier = PKCS1_v1_5.new(public_key) h = SHA.new(str(transaction).encode('utf8')) return verifier.verify(h, binascii.unhexlify(transaction.signature))
#!/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 encrypt(message, pub_key): cipher = PKCS1_OAEP.new(pub_key) return cipher.encrypt(message) ######################################Reading the image import numpy as np from PIL import Image img = Image.open('steg.png') x = np.array(img) #print(x) #######################################Getting private Key fi = open('privatekey2.pem', 'r') privateKey = RSA.importKey(fi.read()) #print(privateKey) ######################################Decoding the image into data import numpy as np decr = np.array(img) decr.resize(4096, ) #print(decr) for x in range(4096): decr[x] = decr[x] & 1 token = bytearray([]) for ex in range(512): bok = "" for why in range(8): bok = bok + str(decr[8 * ex + why]) bokk = int(bok, 2)