def __init__(self, algorithm, mode, key_size): self.algorithm = algorithm self.mode = mode self.key_size = key_size self._session_key = RNG.new().read(self.key_size) self._iv = RNG.new().read(self.block_size) self._cipher = Cipher.AES.new(self._session_key, mode, self._iv)
def changepassword(self): """ Creates a new key. The key itself is actually stored in the database in crypted form. This key is encrypted using the password that the user provides. This makes it easy to change the password for the database. If oldKeyCrypted is none, then a new password is generated.""" if self._callback is None: raise CryptoNoCallbackException("No call back class has been \ specified") if self._keycrypted is None: # Generate a new key, 32 bits in length, if that's # too long for the Cipher, _getCipherReal will sort it out random = OSRNG.new() key = str(random.read(32)).encode('base64') else: password = self._callback.getsecret("Please enter your current \ password") cipher = self._getcipher_real(password, self._algo) plainkey = cipher.decrypt(str(self._keycrypted).decode('base64')) key = self._retrievedata(plainkey) newpassword1 = self._callback.getsecret("Please enter your new \ password") newpassword2 = self._callback.getsecret("Please enter your new \ password again") while newpassword1 != newpassword2: print "Passwords do not match!" newpassword1 = self._callback.getsecret("Please enter your new \ password") newpassword2 = self._callback.getsecret("Please enter your new \ password again") # if (newpassword1 != newpassword2): # raise CryptoPasswordMismatchException("Passwords do not match") newcipher = self._getcipher_real(newpassword1, self._algo) self._keycrypted = str(newcipher.encrypt( self._preparedata(key, newcipher.block_size) )).encode('base64') # newpassword1, newpassword2 are not needed any more so we erase # them zerome(newpassword1) zerome(newpassword2) # we also want to create the cipher if there isn't one already # so this CryptoEngine can be used from now on if self._cipher is None: self._cipher = self._getcipher_real(str(key).decode('base64'), self._algo) CryptoEngine._timeoutcount = time.time() return self._keycrypted
def reinit(self): # re-open the OSRNG as its file descriptor might have been closed after forking try: self._osrng.close() except IOError: pass self._osrng = OSRNG.new() # Add 256 bits to each of the 32 pools, twice. (For a total of 16384 # bits collected from the operating system.) for i in range(2): block = self._osrng.read(32*32) for p in range(32): self._osrng_es.feed(block[p*32:(p+1)*32]) block = None self._osrng.flush()
def encrypt(key, mes, extrapaddingmax = 0): k = _genkey(key, 16) iv = OSRNG.new().read(AES.block_size) aes = AES.new(k, AES.MODE_CBC, iv) #message m = mes #length m = _numToNonNillString(len(m)) + chr(0) + m #pad extrapadding = random.randint(extrapaddingmax/2,extrapaddingmax) m += "".join(map(lambda a:chr(random.randint(0,255)),xrange((16 * (extrapadding + int(ceil(len(m)/16.0)))-len(m))))) #encrypt m = aes.encrypt(m) #iv m = iv + m #mac m = _mac(m, 16) + m return m
def _get_keycrypted(self): if self._keycrypted is None: # Generate a new key, 32 byts in length, if that's # too long for the Cipher, _getCipherReal will sort it out random = OSRNG.new() randombytes = random.read(32) if sys.version_info.major > 2: key = base64.b64encode(randombytes)+b'\n' else: key = base64.b64encode(str(randombytes))+'\n' else: password = self._getsecret("Please enter your current password") cipher = self._getcipher_real(password, self._algo) plainkey = cipher.decrypt(base64.b64decode(self._keycrypted)) # python2 only ... # plainkey = cipher.decrypt(str(self._keycrypted).decode('base64')) key = self._retrievedata(plainkey) return key
def __init__(self, accumulator): self._nsrc = 255 self._srcs = OrderedDict() self._osrng = OSRNG.new() self._rng_lock = threading.Lock() self._src_lock = threading.Lock() self.add_source('osrng', accumulator) self.add_source('time', accumulator) self.add_source('clock', accumulator) self._counters = {} if os.uname()[0] in ['NetBSD', 'Linux']: # noinspection PyUnresolvedReferences from cryptoe.Random import DRBG for x in xrange(0, 32): ctr = 'ctr_drbg' + str(x) self._counters[ctr] = DRBG.new() self.add_source(ctr, accumulator) try: # noinspection PyUnresolvedReferences from cryptoe.Hardware import RDRAND self._rdrand = RDRAND except ImportError: """Nothing yet."""
def __init__(self, accumulator): self._osrng = OSRNG.new() self._osrng_es = _EntropySource(accumulator, 255) self._time_es = _EntropySource(accumulator, 254) self._clock_es = _EntropySource(accumulator, 253)
def gen_key(key_size=32): try: return OSRNG.posix.new().read(key_size) except: return OSRNG.new().read(key_size)
def gen_init_vector(block_size=16): try: return OSRNG.posix.new().read(block_size) except: return OSRNG.new().read(block_size)
from Crypto.Random import OSRNG from Crypto.Cipher import PKCS1_OAEP from Crypto.PublicKey import RSA from Crypto.Cipher import AES # The message to encrypt msg = "Although I'd never dream of stealing copyrighted content, I'd like to send the following advice to Senator Brandis without my ISP Fnding out: Why can't you be cool like Sweden and just allow piracy? Spend the money you're investing to fight piracy on universities instead because you won't be able to stop all forms of piracy. People can always simply use a VPN or a Proxy to route / encypt the pirated data and avoid any blocking methods you could ever implement." blockSize = 16 # Attempt to pad message bytesNeeded = blockSize - len(msg) % blockSize if bytesNeeded > 0: msg = msg + chr(bytesNeeded)*bytesNeeded # Generate a 128-bit AES key AESkey using OSRNG r = OSRNG.new() AESkey = r.read(blockSize) # Load pubkey f = open('pubkey.pem', 'r') pubkey = RSA.importKey(f.read()) f.close() RSAOAEPCipher = PKCS1_OAEP.new(pubkey) # Encrypt AESkey with the public key PK you found in the Setup Task, using RSA with PKCS1-OAEP padding RSACT = RSAOAEPCipher.encrypt(AESkey) # Write the resulting encrypted value into a file called EncryptedAESKey f = open('EncryptedAESKey', 'w') f.write(RSACT) f.close()