def _createIV(): """Create a 16-byte initialization vector. @return: a C{str} initialization vector. """ try: return randpool.RandomPool(512).get_bytes(16) except AssertionError: # An AssertionError can come from Crypto/Random/_UserFriendlyRNG.py, # which produces an error "PID check failed. RNG must be re-initialized # after fork(). Hint: Try Random.atfork()". This seems to only happen # when running locally (in development mode). atfork() return randpool.RandomPool(512).get_bytes(16)
def createKey(keySize=32): """Create a random key. @param keySize: a positive C{int} key length. @return: a random string of length C{keySize}. """ try: return randpool.RandomPool(512).get_bytes(keySize) except AssertionError: # An AssertionError can come from Crypto/Random/_UserFriendlyRNG.py, # which produces an error "PID check failed. RNG must be re-initialized # after fork(). Hint: Try Random.atfork()". This seems to only happen # when running locally (in development mode). atfork() return randpool.RandomPool(512).get_bytes(keySize)
def mbi_crypt(self, nonce): WINCRYPT_CRYPT_MODE_CBC = 1 WINCRYPT_CALC_3DES = 0x6603 WINCRYPT_CALC_SHA1 = 0x8004 # Read key and generate two derived keys key1 = base64.b64decode(self.proof_token) key2 = self._derive_key(key1, "WS-SecureConversationSESSION KEY HASH") key3 = self._derive_key(key1, "WS-SecureConversationSESSION KEY ENCRYPTION") # Create a HMAC-SHA-1 hash of nonce using key2 hash = HMAC.new(key2, nonce, SHA).digest() # # Encrypt nonce with DES3 using key3 # # IV (Initialization Vector): 8 bytes of random data iv = randpool.RandomPool().get_bytes(8) obj = DES3.new(key3, DES3.MODE_CBC, iv) # XXX: win32's Crypt API seems to pad the input with 0x08 bytes # to align on 72/36/18/9 boundary ciph = obj.encrypt(nonce + "\x08\x08\x08\x08\x08\x08\x08\x08") blob = struct.pack("<LLLLLLL", 28, WINCRYPT_CRYPT_MODE_CBC, WINCRYPT_CALC_3DES, WINCRYPT_CALC_SHA1, len(iv), len(hash), len(ciph)) blob += iv + hash + ciph return base64.b64encode(blob)
def create_cryptoken(aes_key, data): if len(aes_key) >= 32: aes_key = aes_key[:32] elif len(aes_key) >= 16: aes_key = aes_key[:16] elif len(aes_key) >= 8: aes_key = aes_key[:8] else: raise AuthorizationFailure() if crypto_version.startswith('2.0'): prng = randpool.RandomPool() iv = prng.get_bytes(256) cipher = AES.new(aes_key, AES.MODE_CFB) tmpbuf = cipher.encrypt(iv) tmpbuf += cipher.encrypt(data) return base64.b64encode(tmpbuf) else: prng = Random.new() iv = prng.read(16) cipher = AES.new(aes_key, AES.MODE_CFB, iv) return base64.b64encode(iv + cipher.encrypt(data))
def sign_DSA(msg, key_tuple, k=None): """Create a DSA signature. :Parameters: - `msg`: string of data signature applies to - `key_tuple`: tuple of DSA integers (y, g, p, q, x) (see `DSA tuple`_) - `k`: random integer 2 < k < q (automatically generated by default) :Returns: tuple (integer, integer) DSA signature values (r, s) .. _DSA tuple: DSA tuple: - `y`: integer DSA public key - `g`: integer DSA group - `p`: integer DSA prime - `q`: integer DSA order - `x`: integer DSA secret value """ import Crypto.PublicKey.DSA as DSA if k is None: # generate our own k value (2 < k < q) import Crypto.Util.number as NUM import Crypto.Util.randpool as RND rnd = RND.RandomPool() q = key_tuple[3] while 1: k = NUM.getRandomNumber(8*len(STN.int2str(q)), rnd.get_bytes) if 2 < k < q: break dsa = DSA.construct(key_tuple) # note change in ordering return dsa.sign(msg, k)
def makepuzzle(t): # Init PyCrypto RNG rnd = randpool.RandomPool() # Generate 512-bit primes p = number.getPrime(512, rnd.get_bytes) q = number.getPrime(512, rnd.get_bytes) n = p * q phi = (p - 1) * (q - 1) # AES key --- this is what we will encode into the puzzle solution key = number.getRandomNumber(128, rnd.get_bytes) # Need a random starting value for the puzzle, between 1 and n a = number.getRandomNumber(4096, rnd.get_bytes) a = a % n # *** puzzle shortcut *** # fast way to compute (a^2)^t (if you know phi) e = pow(2, t, phi) b = pow(a, e, n) # So b = (a^2)^t, and we encode the key into this solution ck = (key + b) % n return (key, (n, a, t, ck))
def make_uuid(): uuid_size = 32 + random.randint(1, 16) uuid_bytes = randpool.RandomPool(512).get_bytes(uuid_size) s = [] for x in uuid_bytes: s.append(ord(x)) print "uuid " + str(s) return base64.urlsafe_b64encode(str(uuid_bytes))
def generate_pwd(): if crypto_version.startswith('2.0'): prng = randpool.RandomPool() iv = prng.get_bytes(256) else: prng = Random.new() iv = prng.read(16) return base64.b64encode(iv)
def encrypt(plain_text,key_bytes): assert len(key_bytes) == key_size mode = AES.MODE_CBC pad = block_size - len(plain_text) % block_size data = plain_text + pad * chr(pad) iv_bytes = randpool.RandomPool(512).get_bytes(block_size) encrypted_bytes = iv_bytes + AES.new(key_bytes, mode, iv_bytes).encrypt(data) return encrypted_bytes
def rand_rsa_key(key_lenght=CRYPTO.KEY_LENGHT.RSA): """ Return a random key with lenght received :param key_lenght: Lenght of Key in bits (minimum: 1024) """ random_pool = randpool.RandomPool() rsa_key = RSA.generate(key_lenght, random_pool.get_bytes) return rsa_key.exportKey() # Return private key
def evaluateSubject(self, obj_py): """Generates an RSA keypair, and spews it out as plain text. Has the limitation that it will *only* ever let you generate one key pair (per iteration), in order to work around a bug.""" if self.do: randfunc, self.do = randpool.RandomPool(int(obj_py)), 0 RSAKey = RSA.generate(int(obj_py), randfunc.get_bytes) TextKey = keyToQuo(RSAKey) if TextKey != 'N.': return TextKey
def encrypt(plaintext, password): salt = crandom.RandomPool(SALT_SIZE) salt = salt.get_bytes(SALT_SIZE) key = generate_key(password, salt, NUMBER_OF_ITERATIONS) cipher = AES.new(key, AES.MODE_ECB) padded_plaintext = pad_text(plaintext, AES_MULTIPLE) ciphertext = cipher.encrypt(padded_plaintext) ciphertext_with_salt = salt + ciphertext return ciphertext_with_salt
def enc_rsa(message): # rsa_pub_key = rsa.publickey() rsa = RSA.generate(1024, RANDOM.RandomPool().get_bytes) rsa_pub_key = rsa.publickey() rsa_pub_key.n = 145471325565137272885782581039688149428232444669081670130562887504720589945224856535922663715912109010927552603613192335809372301855527754295948685977606233230830293484559809494872642754838525110340427705495371805952848626596076943737994354649406602042592969617559716470638070888599314074058154791892769802391 rsa_pub_key.e = 65537 print('rsa_pub_key.n') print(rsa_pub_key.n) encrypto = rsa_pub_key.encrypt(message, "") return encrypto
def generateRSAclefagent(self): """ Function generate clef RSA to file """ pool = randpool.RandomPool() # In real life, you use a *much* longer key self.allkey = RSA.generate(1024, pool.get_bytes) self.publickey = self.allkey.publickey() pickle.dump(self.allkey, open(self.fileallkey, 'w')) pickle.dump(self.publickey, open(self.filekeypublic, 'w')) return self.allkey
def _inventkey(self, key_size): # TBD: Not a very secure algorithm. Eventually, I'd like to use JHy's # kernelrand module import time from Crypto.Util import randpool # TBD: key_size * 2 to work around possible bug in RandomPool? pool = randpool.RandomPool(key_size * 2) while key_size > pool.entropy: pool.add_event() # we now have enough entropy in the pool to get a key_size'd key return pool.get_bytes(key_size)
def _randnum(self, size): # TBD: Not a very secure algorithm. # TBD: size * 2 to work around possible bug in RandomPool from Crypto.Util import randpool import time pool = randpool.RandomPool(size * 2) while size > pool.entropy: pass # we now have enough entropy in the pool to get size bytes of random # data... well, probably return pool.get_bytes(size)
def encrypt_string(plain_text, key_string): block_size = 16 mode = AES.MODE_CBC plain_data = base64.urlsafe_b64decode(plain_text) pad = block_size - len(plain_data) % block_size print "pad = " + str(pad) data = plain_data + (pad * chr(pad)) iv_bytes = randpool.RandomPool(512).get_bytes(block_size) key_bytes = base64.urlsafe_b64decode(key_string) encrypted_bytes = iv_bytes + AES.new(key_bytes, mode, iv_bytes).encrypt(data) encrypted_string = base64.urlsafe_b64encode(str(encrypted_bytes)) return encrypted_string
def dec_rsa(encrypto): rsa = RSA.generate(1024, RANDOM.RandomPool().get_bytes ) rsa.n=145471325565137272885782581039688149428232444669081670130562887504720589945224856535922663715912109010927552603613192335809372301855527754295948685977606233230830293484559809494872642754838525110340427705495371805952848626596076943737994354649406602042592969617559716470638070888599314074058154791892769802391 rsa.e=65537 rsa.d=21517601202808195726914206335333276173112674040955150681991495360952765596975903066347777622748248848008479102482968193590430674186909471750994500234476930448082061706047301016136608755418669760263728418550774979347859116947293576480638933146421447506419194772797598857419375571888971551074154487277961921937 rsa.p=11444448290025606916724702822518266092555354869033384100260512949484030906682203805655960827455078445407498725745812188968143376548796960389934850463502557 rsa.q=12711082428667409467280738736266707221075884674685463640039196795888245510768877737928973598498601428894094815378094110994961553740257214655445784230120963 rsa.u=12213696054552591246008243178713852307335582484378605284341118185114591281487593461839382892684071842018263062496886067580686240642833174841748501441564395 rsa_private_key = RSA.construct((rsa.n, rsa.e, rsa.d)) decrypto = rsa_private_key.decrypt( encrypto ) # print('rsa.n') # print(rsa.n) return decrypto
def rsa(message): message = message.encode('utf-8') #鍵オブジェクト( 鍵を16ByteまでOKとする ) rsa = RSA.generate(1024, RANDOM.RandomPool().get_bytes) #公開鍵 rsa_pub_key = rsa.publickey() #秘密鍵 rsa_private_key = RSA.construct((rsa.n, rsa.e, rsa.d)) #messagez #message = "This is enc Test".encode('utf-8') #暗号化 encrypto = rsa_pub_key.encrypt(message, "") return encrypto
def encrypt(self, data_json): from Crypto.Util import randpool # add expiration date in UTC timestamp from Epoch if not 'expires' in data_json: # add expires in 1 hour data_json['expires'] = int(time.time()) + 3600 # dump JSON data to string add padding if needed raw = self._pad(json.dumps(data_json)) # generate IV iv = randpool.RandomPool(self.bs).get_bytes(self.bs) # encrypt data and prepend IV res = base64.b64encode(iv + AES.new(self.key, self.mode, iv).encrypt(raw)) # quote data to use as an url parameter and return return urllib.quote(res)
def gen_random(numbytes, poolsize=None): """Retrieve random bytes. :Parameters: - `numbytes`: integer number of random bytes to retrieve - `poolsize`: integer size of random pool to choose bytes from (default 256) :Returns: string of random bytes """ import Crypto.Util.randpool as RND if None == poolsize: if numbytes > 256: poolsize = numbytes else: poolsize = 256 rnd = RND.RandomPool(poolsize) return rnd.get_bytes(numbytes)
def rsadecyptaes(hostt): host = hostt port = 50002 blah = randpool.RandomPool() RSAKey = RSA.generate(1024, blah.get_bytes) RSAPubKey = RSAKey.publickey() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((host, port)) s.listen(1) clientsock, clientaddr = s.accept() clientsock.send(pickle.dumps(RSAPubKey)) rcstring = '' buf = clientsock.recv(1024) rcstring += buf clientsock.close() encmessage = pickle.loads(rcstring) key = RSAKey.decrypt(encmessage) s.close() return key
def encrypt_integrity(algorithm, key, msg): """Encrypt a message with integrity protection. :Parameters: - `msg`: string cleartext - `algorithm`: integer cipher constant - `key`: string encryption key :Returns: `OpenPGP.packet.SymmetricallyEncryptedIntegrityProtectedData.SymmetricallyEncryptedIntegrityProtectedData` instance :note: It is up to the caller to make sure that `msg` is a valid message string (compressed properly, etc.). :note: Integrity check via SHA-1 is hardcoded. """ import Crypto.Util.randpool as RND from openpgp.sap.pkt.Packet import create_Packet bs = _import_cipher(algorithm).block_size rnd = RND.RandomPool(bs) prefix = rnd.get_bytes(bs) clearstream = StringIO() cipherstream = StringIO() clearstream.write(prefix) clearstream.write(prefix[-2:]) clearstream.write(msg) clearstream.write('\xd3\x14') clearstream.write(sha.new(clearstream.getvalue()).digest()) # hash previous clearstream.seek(0) # again, magic .read() should handle this in crypt_CFB() cipherstream.write('\x01') cipherstream.seek(0, 2) clearstream.seek(0) crypt_CFB(clearstream, cipherstream, algorithm, key, None, 'encrypt') cipherstream.seek(0) ciphertext = cipherstream.read() return create_Packet(PKT_SYMENCINTDATA, ciphertext)
def make_root(cls, user: User, magicnumber: str = None) -> 'Block': """ Make root block The root block has no any messages and closed from the creating. The first closer is the administrator of the chain. >>> rootuser = User.generate() >>> root = Block.make_root(rootuser) >>> child = Block(root) >>> root.is_closed() True >>> root.verify() True >>> child.is_closed() False >>> root.messages [] Index of the root block is 0. >>> root.index 0 >>> child.index 1 """ result = cls(None, magicnumber) result.timestamp = int(time.time() * 1000) result.key = randpool.RandomPool().get_bytes(32) result.closer = user result.signature = user.sign_raw( result.timestamp.to_bytes(8, 'big') + result.key) return result
def CreateKeyPair(size=1024): return RSA.generate(size, randpool.RandomPool().get_bytes)
from __future__ import generators from pprint import pprint import struct import operator from binascii import hexlify import types import sha import Queue from Crypto.Util import randpool from Crypto.Util.number import bytes_to_long, long_to_bytes import IPAddress RandomPool = randpool.RandomPool() class Memoize: """Memoize(fn) - an instance which acts like fn but memoizes its arguments Will only work on functions with non-mutable arguments """ def __init__(self, fn): self.fn = fn self.memo = {} def __call__(self, *args): if not self.memo.has_key(args): self.memo[args] = self.fn(*args) return self.memo[args] ##try:
def setup (self): self.pool = randpool.RandomPool(160, hash=SHA)
def dec_rsa(rsa,encrypto): rsa_private_key = RSA.construct((rsa.n, rsa.e, rsa.d)) decrypto = rsa_private_key.decrypt( encrypto ) return decrypto print('Starting the server at', datetime.now()) print('Waiting for a client to call.') server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(address) server.listen(5) client, addr = server.accept() rsa = RSA.generate(1024, RANDOM.RandomPool().get_bytes ) rsa_pub_key = rsa.publickey() rsa_pub_key_send = rsa_pub_key.exportKey() print('rsa_pub_key_send') print(rsa_pub_key_send) client.send(rsa_pub_key_send) num = client.recv(max_size) client.send(num) allsize=unpack('H',num) print(allsize) #復号して書き込み f=open('text1.jpg', 'ab') # 書き込みモードで開く
from Crypto.Util import number, randpool from copy import deepcopy from Crypto.Cipher import AES import sys import time import socket import numpy as np rnd = randpool.RandomPool() SECOND = 1 MINUTE = 60 HOUR = MINUTE * 60 DAY = HOUR * 24 MONTH = DAY * 31 YEAR = DAY * 365 MOD_BITS = 512 # 2048 # for time-lock puzzle N AES_BITS = 24 # 192 FLD_BITS = 192 # for finite field p def calibrate_speed(): p = number.getPrime(MOD_BITS, rnd.get_bytes) q = number.getPrime(MOD_BITS, rnd.get_bytes) N = p * q bignum = number.getRandomNumber(MOD_BITS, rnd.get_bytes) #big number start = time.time() trials = 1000 for i in range(0, trials): bignum = pow(bignum, 2, N)
def sign_ElGamal(msg, key_tuple, k=None): """Create an ElGamal signature. :Parameters: - `msg`: string of data signature applies to - `key_tuple`: tuple ElGamal key integers (p, g, x) (see `ElGamal key tuple`_) - `k`: integer (must be relatively prime to p-1) :Returns: tuple (integer, integer) ElGamal signature values (a, b) .. _ElGamal key tuple: ElGamal key tuple: - `p`: integer ElGamal prime - `g`: integer ElGamal random "g" value - `x`: integer ElGamal private key """ import Crypto.PublicKey.ElGamal as ELG if k is None: # generate our own prime k value (k relatively prime to p-1) import Crypto.Util.number as NUM import Crypto.Util.randpool as RND rnd = RND.RandomPool() q = key_tuple[0] # no restrictions on bit length for k, good enough? k = NUM.getPrime(8*len(STN.int2str(q)), rnd.get_bytes) elg = ELG.construct((key_tuple[0], key_tuple[1], 0, key_tuple[2])) return elg.sign(msg, k)