def __makeEncryptionBlock(self, blocktype, data): padsize = self.keylen - 3 - len(data) if blocktype == self.__PRIVATE: ps = chr(0xFF) * padsize elif blocktype == self.__PUBLIC: ps = cryptrand.random(padsize) while "\000" in ps: clean = string.join(string.split(ps, "\000"), "") clean = clean + cryptrand.random(padsize - len(clean)) else: # PKCS #1 defines a second blocktype for private (0), but # discourages its use raise ValueError, "unsupported block type %d" % blocktype return chr(0) + chr(blocktype) + ps + chr(0) + data
def createKey(self, password, label=''): """Create a key from the password and optional label Return value is a tuple containing: salt, iteration count, hash name, and key """ if label or self.labels: if not label in self.labels: raise ValueError, "invalid label" salt = label + cryptrand.random(self.saltlen) return self._makeKey(password, salt)
def encryptWithPassword(object, pw, bogus=None): """Will create a PasswordEncrypted object This function makes a bunch of choices for you, e.g. hash and cipher. You'll need to roll your own code if you want to do something else. """ from Crypto.Cipher import DES3 kdf = pwcrypt.KeyDerivationFactory(16, 8) # 16-byte key, 8-byte salt salt, iters, hash, key = kdf.createKey(pw) iv = cryptrand.random(8) cipher = DES3.new(key, DES3.CBC, iv) ct = cipher.encrypt(pad(object.sexp().encode_canonical())) c = _3desCipher('CBC', iv, ct) k = Pbes2Hmac(salt, str(iters), hash, str(len(key))) return PasswordEncrypted(object.sexp()[0], # it's name, k, c, (bogus is None and None or "bogus"))
def newRandom(size): t = int(time.time()) randBuf = cryptrand.random(size) return Random(t, randBuf)
def newServerHello(): return ServerHello('0', newRandom(ServerHello.RANDOM_SIZE), cryptrand.random(SESSION_ID_SIZE))