我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用Crypto.Cipher.DES.MODE_CBC。
def encrypt(self, data): """Encrypt sensitive data by KIK. For (3)DES, data must be padded to BS. For AES, if data not BS-alligned, they are padded by '80..00'""" l = len(data) if self.zAES: l %= 16 if l > 0: data += '\x80' + '\0'*(15-l) key = AES.new(self.keyValue, AES.MODE_CBC, IV='\0'*16) else: # suppose 8B aligned data assert l % 8 == 0 # for (3)DES KIK, ECB is used # KeyType.DES_IMPLICIT is supposed to be 3DES ECB if self.keyType in (KeyType.TDES_CBC, KeyType.DES_IMPLICIT): key = DES3.new(self.keyValue, DES.MODE_ECB) elif self.keyType in (KeyType.DES_ECB, KeyType.DES_CBC): key = DES.new(self.keyValue, DES.MODE_ECB) else: raise ValueError("Unknown key type %02X" % self.keyType) return key.encrypt(data)
def reencrypt(self, data): try: self.decoder = DES.new(self.key, DES.MODE_CBC, self.iv) # need to reinit it each time because of CBC decrypted=self.unpad(self.decoder.decrypt(base64.b64decode(data))) if debug: if len(decrypted)==8 and re.match(self.autogen,decrypted) is not None: self.debugf.write(self.currentdn+" =* "+decrypted+"\n") elif re.match(self.alphanumchar,decrypted) is not None: self.debugf.write(self.currentdn+" => "+decrypted+"\n") else: self.debugf.write(self.currentdn+" =x "+decrypted+"\n") encrypted=self.encoder.encrypt(self.pad(decrypted)) newdata=base64.b64encode(encrypted) return newdata except: raise
def __init__(self, iKICD): """ Constructor for KIC/KID object. iKICD - coding of KIC or KID (see ETSI 102.225, 5.1.2 and 5.1.3, u8)""" iKICD %= 0x100 self.iKICD = iKICD self.keyval = None if iKICD & KICD.ALGO == KICD.ALGO_DES: # DES/3DES key b43 = iKICD & 0x0C # bits 4 and 3 of KIC/KID self.keysize = 8 + 2*(b43 % 12) # mapping to DES, 3DES 2k, 3DES 3k self.cipModule = b43 % 12 and DES3 or DES self.MODE = b43 == KICD.DES_ECB and DES.MODE_EBC or DES.MODE_CBC self.BS = 8 self.zAES = False elif iKICD & 0x0F == KICD.ALGO_AES: # AES CBC / CMAC self.zAES = True self.cipModule = AES self.MODE = AES.MODE_CBC self.BS = 16 self.TlenB = 8 # length of CMAC, you may manually change to 4 self.irrPoly = 0x87 # for CMAC else: raise ValueError("Only DES/AES implemented for KIC/KID")
def sign(self, data): """ Sign data (as str) by KID key. Return signature as str.""" if self.zAES: data = [ord(x) for x in data] sLB = len(data) % self.BS if(sLB > 0 or len(data) == 0): data += [0x80] + [0]*(self.BS-sLB-1) xorkey = self.xorKey2 else: xorkey = self.xorKey1 for i in xrange(self.BS): data[-self.BS+i] ^= ord(xorkey[i]) cipher = AES.new(self.keyval, AES.MODE_CBC, IV='\0'*16) data = ''.join([chr(x) for x in data]) sig = cipher.encrypt(data)[-self.BS:] return sig[:self.TlenB] else: padlen = len(data) % self.BS if padlen > 0: padlen = self.BS - padlen sig = self.cipher(data + '\0'*padlen, True) return sig[-self.BS:]
def encryptData(self, encryptKey, privParameters, dataToEncrypt): if DES is None: raise error.StatusInformation( errorIndication=errind.encryptionError ) snmpEngineBoots, snmpEngineTime, salt = privParameters # 8.3.1.1 desKey, salt, iv = self.__getEncryptionKey( encryptKey, snmpEngineBoots ) # 8.3.1.2 privParameters = univ.OctetString(salt) # 8.1.1.2 desObj = DES.new(desKey, DES.MODE_CBC, iv) plaintext = dataToEncrypt + univ.OctetString((0,) * (8 - len(dataToEncrypt) % 8)).asOctets() ciphertext = desObj.encrypt(plaintext) # 8.3.1.3 & 4 return univ.OctetString(ciphertext), privParameters # 8.2.4.2
def basic_encrypt(cls, key, plaintext): assert len(plaintext) % 8 == 0 des = DES.new(key.contents, DES.MODE_CBC, '\0' * 8) return des.encrypt(plaintext)
def basic_decrypt(cls, key, ciphertext): assert len(ciphertext) % 8 == 0 des = DES.new(key.contents, DES.MODE_CBC, '\0' * 8) return des.decrypt(ciphertext)
def basic_encrypt(cls, key, plaintext): assert len(plaintext) % 8 == 0 des3 = DES3.new(key.contents, AES.MODE_CBC, '\0' * 8) return des3.encrypt(plaintext)
def basic_decrypt(cls, key, ciphertext): assert len(ciphertext) % 8 == 0 des3 = DES3.new(key.contents, AES.MODE_CBC, '\0' * 8) return des3.decrypt(ciphertext)
def basic_encrypt(cls, key, plaintext): assert len(plaintext) >= 16 aes = AES.new(key.contents, AES.MODE_CBC, '\0' * 16) ctext = aes.encrypt(_zeropad(plaintext, 16)) if len(plaintext) > 16: # Swap the last two ciphertext blocks and truncate the # final block to match the plaintext length. lastlen = len(plaintext) % 16 or 16 ctext = ctext[:-32] + ctext[-16:] + ctext[-32:-16][:lastlen] return ctext
def wrapAPDU(self, apdu): """ Wrap APDU for SCP02, i.e. calculate MAC and encrypt. Input APDU and output APDU are list of uint8. """ lc = len(apdu) - 5 assert len(apdu) >= 5, "Wrong APDU length: %d" % len(apdu) assert len(apdu) == 5 or apdu[4] == lc, \ "Lc differs from length of data: %d vs %d" % (apdu[4], lc) cla = apdu[0] b8 = cla & 0x80 if cla & 0x03 > 0 or cla & 0x40 != 0: # nonzero logical channel in APDU, check that are the same assert cla == self.CLA(False, b8), "CLA mismatch" sapdu = l2s(apdu) # CLA without log. channel can be 80 or 00 only if self.isCMAC: if self.i & M_CMAC_MODIF: # CMAC on unmodified APDU mlc = lc clac = chr(b8) else: # CMAC on modified APDU mlc = lc + 8 clac = chr(b8 + 0x04) mac = self.calcMAC_1d(clac + sapdu[1:4] + chr(mlc) + sapdu[5:]) mac = [ord(x) for x in mac] if self.isENC: k = DES3.new(self.ses_ENC, DES.MODE_CBC, ZERO8) data = s2l(k.encrypt(pad80(sapdu[5:], 8))) lc = len(data) else: data = apdu[5:] lc += 8 apdu = [self.CLA(True, b8)] + apdu[1:4] + [lc] + data + mac return apdu
def deriveKeys(self, card_challenge): """ Derive session keys and calculate host_ and card_ cryptograms.""" # session keys derivation k = DES3.new(self.i & M_BASEKEY and self.base_S_MAC or self.base_KEY, DES.MODE_CBC, IV=ZERO8) self.ses_C_MAC = k.encrypt(unhexlify("0101") + self.seqCounter + ZERO12) k = DES3.new(self.i & M_BASEKEY and self.base_S_MAC or self.base_KEY, DES.MODE_CBC, IV=ZERO8) self.ses_R_MAC = k.encrypt(unhexlify("0102") + self.seqCounter + ZERO12) k = DES3.new(self.i & M_BASEKEY and self.base_DEK or self.base_KEY, DES.MODE_CBC, IV=ZERO8) self.ses_DEK = k.encrypt(unhexlify("0181") + self.seqCounter + ZERO12) k = DES3.new(self.i & M_BASEKEY and self.base_S_ENC or self.base_KEY, DES.MODE_CBC, IV=ZERO8) self.ses_ENC = k.encrypt(unhexlify("0182") + self.seqCounter + ZERO12) # key for MAC encryption if self.i & M_ICV_ENC: self.k_icv = DES.new(self.ses_C_MAC[:8], DES.MODE_ECB) # card cryptogram calculation if self.i & M_PSEUDO: self.card_challenge = self.calcMAC_1d(self.SD_AID, True)[:6] else: assert len(card_challenge) == 6,\ "Wrong length or missing card challenge (mandatory)" self.card_challenge = card_challenge self.host_cryptogram = self.calcMAC_3d(self.seqCounter + self.card_challenge + self.host_challenge) self.card_cryptogram = self.calcMAC_3d(self.host_challenge + self.seqCounter + self.card_challenge)
def AesCbcEncryptEncoder(key=None, iv=None, key_size=16, key_provider=None, padder=None): ''' AES CBC Encrypt encoder. See :class:`~katnip.model.low_level.encoder.AesEncryptEncoder` for parameter description. ''' return AesEncryptEncoder(key, iv, AES.MODE_CBC, key_size, key_provider, padder)
def AesCbcDecryptEncoder(key=None, iv=None, key_size=16, key_provider=None): ''' AES CBC Decrypt encoder. See :class:`~katnip.model.low_level.encoder.AesDecryptEncoder` for parameter description. ''' return AesDecryptEncoder(key, iv, AES.MODE_CBC, key_size, key_provider)
def decryptData(self, decryptKey, privParameters, encryptedData): if DES is None: raise error.StatusInformation( errorIndication=errind.decryptionError ) snmpEngineBoots, snmpEngineTime, salt = privParameters # 8.3.2.1 if len(salt) != 8: raise error.StatusInformation( errorIndication=errind.decryptionError ) # 8.3.2.2 noop # 8.3.2.3 desKey, iv = self.__getDecryptionKey(decryptKey, salt) # 8.3.2.4 -> 8.1.1.3 if len(encryptedData) % 8 != 0: raise error.StatusInformation( errorIndication=errind.decryptionError ) desObj = DES.new(desKey, DES.MODE_CBC, iv) # 8.3.2.6 return desObj.decrypt(encryptedData.asOctets())
def decrypt_des(key, data): iv = key cipher = DES.new(key, DES.MODE_CBC, iv) return cipher.decrypt(data)
def decrypt_aes(key, iv, data): mode = AES.MODE_CBC cipher = AES.new(key, mode, IV=iv) return cipher.decrypt(data)
def decrypt_des(data): key = '&%#@?,:*' iv = '\x12\x34\x56\x78\x90\xab\xcd\xef' cipher = DES.new(key, DES.MODE_CBC, iv) return cipher.decrypt(data)
def decryptPBEWithMD5AndDES(plain, password, salt, iterations): key, iv = compute_key_iv(password, salt, iterations) decode = DES.new(key, DES.MODE_CBC, iv) decrypted = decode.decrypt(plain) decrypted = unpad(decrypted) return decrypted
def decrypt(plain, password, salt, iterations=20): key, iv = compute_key_iv(password, salt, iterations) decode = DES.new(key, DES.MODE_CBC, iv) decrypted = decode.decrypt(plain) decrypted = unpad_pkcs7(decrypted) return decrypted
def cipher(clear, key, IV): pad_len = 8 - len(clear) % 8 # length of padding padding = chr(pad_len) * pad_len # PKCS5 padding content clear += padding cipher = DES.new( key, DES.MODE_CBC, IV ) return base64.urlsafe_b64encode(IV + cipher.encrypt(clear))
def uncipher(cipher, key): cipher += '=' * (-len(cipher) % 4) b64_decoded = base64.urlsafe_b64decode(cipher) uncipher = DES.new( key, DES.MODE_CBC, b64_decoded[:8] ) clear = uncipher.decrypt(b64_decoded) padding = clear[-1] # Check padding if not all(c in padding for c in clear[-ord(padding):]): raise PaddingError() return clear[8:-ord(padding)]
def dblink11(self, data, options): key=binascii.unhexlify(data[2:18]) pw=binascii.unhexlify(data[18:]) cipher=DES.new(key, DES.MODE_CBC, '\0' * 8) return unpad(cipher.decrypt(pw))
def aes_encryption(incoming_shellcode, encryption_pad=4): # Generate a random key, create the cipher object # pad the shellcode, and encrypt the padded shellcode # return encrypted -> encoded shellcode and key random_aes_key = helpers.randomKey() iv = helpers.randomString(16) aes_cipher_object = AES.new(random_aes_key, AES.MODE_CBC, iv) padded_shellcode = encryption_padding(incoming_shellcode, encryption_pad) encrypted_shellcode = aes_cipher_object.encrypt(padded_shellcode) encoded_ciphertext = base64.b64encode(encrypted_shellcode) return encoded_ciphertext, random_aes_key, iv
def des_encryption(incoming_shellcode): # Generate a random key, create the cipher object # pad the shellcode, and encrypt the padded shellcode # return encrypted -> encoded shellcode and key random_des_key = helpers.randomKey(8) iv = helpers.randomString(8) des_cipher_object = DES.new(random_des_key, DES.MODE_CBC, iv) padded_shellcode = encryption_padding(incoming_shellcode) encrypted_shellcode = des_cipher_object.encrypt(padded_shellcode) encoded_ciphertext = base64.b64encode(encrypted_shellcode) return encoded_ciphertext, random_des_key, iv
def test_vanilla_CBC(self): self.crypto.mode = AES.MODE_CBC self.test_vanilla_base()
def setUp(self): crypt = CryptArgs('\x01' * 16, '\x00' * 16, 16, [16, 24, 32], AES.MODE_CBC, None) super(AesEncryptEncoderTestCase, self).setUp(crypt) self.crypto.padder = None
def test_AesCbcEncryptEncoder(self): ''' AesCbcEncryptEncoder(key=None, iv=None, key_size=16, key_provider=None, padder=None) ''' self.crypto.mode = AES.MODE_CBC self._test_generators_base( AesCbcEncryptEncoder( key=self.crypto.key, iv=self.crypto.iv, key_size=self.crypto.key_size, key_provider=self.crypto.key_provider, padder=self.crypto.padder ))
def test_AesCbcDecryptEncoder(self): ''' AesCbcDecryptEncoder(key=None, iv=None, key_size=16, key_provider=None) ''' self.crypto.mode = AES.MODE_CBC self._test_generators_base( AesCbcDecryptEncoder( key=self.crypto.key, iv=self.crypto.iv, key_size=self.crypto.key_size, key_provider=self.crypto.key_provider, ))
def setUp(self): crypt = CryptArgs('\x01' * 8, '\x00' * 8, 8, [8], DES.MODE_CBC, None) super(DesEncryptEncoderTestCase, self).setUp(crypt) self.crypto.padder = None
def setUp(self): crypt = CryptArgs('\x01' * 8, '\x00' * 8, 8, [8], DES.MODE_CBC, None) super(DesDecryptEncoderTestCase, self).setUp(crypt)
def setUp(self): crypt = CryptArgs('\x01' * 16, '\x00' * 8, 8, [16, 24], DES3.MODE_CBC, None) super(Des3EncryptEncoderTestCase, self).setUp(crypt) self.crypto.padder = None
def setUp(self): crypt = CryptArgs('\x01' * 16, '\x00' * 8, 8, [16, 24], DES3.MODE_CBC, None) super(Des3DecryptEncoderTestCase, self).setUp(crypt)
def populate_transform_menu(menu, obj, action_table): aes_menu = menu.addMenu("AES") aes_ecb_menu = aes_menu.addMenu("ECB mode") aes_cbc_menu = aes_menu.addMenu("CBC mode") action_table[aes_ecb_menu.addAction("Encrypt")] = lambda: obj.transform_with_key(lambda data, key: aes_encrypt_transform(data, key, AES.MODE_ECB, "")) action_table[aes_ecb_menu.addAction("Decrypt")] = lambda: obj.transform_with_key(lambda data, key: aes_decrypt_transform(data, key, AES.MODE_ECB, "")) action_table[aes_cbc_menu.addAction("Encrypt")] = lambda: obj.transform_with_key_and_iv(lambda data, key, iv: aes_encrypt_transform(data, key, AES.MODE_CBC, iv)) action_table[aes_cbc_menu.addAction("Decrypt")] = lambda: obj.transform_with_key_and_iv(lambda data, key, iv: aes_decrypt_transform(data, key, AES.MODE_CBC, iv)) blowfish_menu = menu.addMenu("Blowfish") blowfish_ecb_menu = blowfish_menu.addMenu("ECB mode") blowfish_cbc_menu = blowfish_menu.addMenu("CBC mode") action_table[blowfish_ecb_menu.addAction("Encrypt")] = lambda: obj.transform_with_key(lambda data, key: blowfish_encrypt_transform(data, key, Blowfish.MODE_ECB, "")) action_table[blowfish_ecb_menu.addAction("Decrypt")] = lambda: obj.transform_with_key(lambda data, key: blowfish_decrypt_transform(data, key, Blowfish.MODE_ECB, "")) action_table[blowfish_cbc_menu.addAction("Encrypt")] = lambda: obj.transform_with_key_and_iv(lambda data, key, iv: blowfish_encrypt_transform(data, key, Blowfish.MODE_CBC, iv)) action_table[blowfish_cbc_menu.addAction("Decrypt")] = lambda: obj.transform_with_key_and_iv(lambda data, key, iv: blowfish_decrypt_transform(data, key, Blowfish.MODE_CBC, iv)) cast_menu = menu.addMenu("CAST") cast_ecb_menu = cast_menu.addMenu("ECB mode") cast_cbc_menu = cast_menu.addMenu("CBC mode") action_table[cast_ecb_menu.addAction("Encrypt")] = lambda: obj.transform_with_key(lambda data, key: cast_encrypt_transform(data, key, CAST.MODE_ECB, "")) action_table[cast_ecb_menu.addAction("Decrypt")] = lambda: obj.transform_with_key(lambda data, key: cast_decrypt_transform(data, key, CAST.MODE_ECB, "")) action_table[cast_cbc_menu.addAction("Encrypt")] = lambda: obj.transform_with_key_and_iv(lambda data, key, iv: cast_encrypt_transform(data, key, CAST.MODE_CBC, iv)) action_table[cast_cbc_menu.addAction("Decrypt")] = lambda: obj.transform_with_key_and_iv(lambda data, key, iv: cast_decrypt_transform(data, key, CAST.MODE_CBC, iv)) des_menu = menu.addMenu("DES") des_ecb_menu = des_menu.addMenu("ECB mode") des_cbc_menu = des_menu.addMenu("CBC mode") action_table[des_ecb_menu.addAction("Encrypt")] = lambda: obj.transform_with_key(lambda data, key: des_encrypt_transform(data, key, DES.MODE_ECB, "")) action_table[des_ecb_menu.addAction("Decrypt")] = lambda: obj.transform_with_key(lambda data, key: des_decrypt_transform(data, key, DES.MODE_ECB, "")) action_table[des_cbc_menu.addAction("Encrypt")] = lambda: obj.transform_with_key_and_iv(lambda data, key, iv: des_encrypt_transform(data, key, DES.MODE_CBC, iv)) action_table[des_cbc_menu.addAction("Decrypt")] = lambda: obj.transform_with_key_and_iv(lambda data, key, iv: des_decrypt_transform(data, key, DES.MODE_CBC, iv)) des3_menu = menu.addMenu("Triple DES") des3_ecb_menu = des3_menu.addMenu("ECB mode") des3_cbc_menu = des3_menu.addMenu("CBC mode") action_table[des3_ecb_menu.addAction("Encrypt")] = lambda: obj.transform_with_key(lambda data, key: des3_encrypt_transform(data, key, DES3.MODE_ECB, "")) action_table[des3_ecb_menu.addAction("Decrypt")] = lambda: obj.transform_with_key(lambda data, key: des3_decrypt_transform(data, key, DES3.MODE_ECB, "")) action_table[des3_cbc_menu.addAction("Encrypt")] = lambda: obj.transform_with_key_and_iv(lambda data, key, iv: des3_encrypt_transform(data, key, DES3.MODE_CBC, iv)) action_table[des3_cbc_menu.addAction("Decrypt")] = lambda: obj.transform_with_key_and_iv(lambda data, key, iv: des3_decrypt_transform(data, key, DES3.MODE_CBC, iv)) rc2_menu = menu.addMenu("RC2") rc2_ecb_menu = rc2_menu.addMenu("ECB mode") rc2_cbc_menu = rc2_menu.addMenu("CBC mode") action_table[rc2_ecb_menu.addAction("Encrypt")] = lambda: obj.transform_with_key(lambda data, key: rc2_encrypt_transform(data, key, ARC2.MODE_ECB, "")) action_table[rc2_ecb_menu.addAction("Decrypt")] = lambda: obj.transform_with_key(lambda data, key: rc2_decrypt_transform(data, key, ARC2.MODE_ECB, "")) action_table[rc2_cbc_menu.addAction("Encrypt")] = lambda: obj.transform_with_key_and_iv(lambda data, key, iv: rc2_encrypt_transform(data, key, ARC2.MODE_CBC, iv)) action_table[rc2_cbc_menu.addAction("Decrypt")] = lambda: obj.transform_with_key_and_iv(lambda data, key, iv: rc2_decrypt_transform(data, key, ARC2.MODE_CBC, iv)) action_table[menu.addAction("RC4")] = lambda: obj.transform_with_key(lambda data, key: rc4_transform(data, key)) action_table[menu.addAction("XOR")] = lambda: obj.transform_with_key(lambda data, key: xor_transform(data, key))
def pyherion(code): """ Generates a crypted hyperion'esque version of python code using base64 and AES with a random key, wrapped in an exec() dynamic launcher. code = the python source code to encrypt Returns the encrypted python code as a string. """ imports = list() codebase = list() # strip out all imports from the code so pyinstaller can properly # launch the code by preimporting everything at compiletime for line in code.split("\n"): if not line.startswith("#"): # ignore commented imports... if "import" in line: imports.append(line) else: codebase.append(line) # encrypt the input file (less the imports) encrypted_code, key, iv = aes_encryption("\n".join(codebase), encryption_pad='{') encrypted_code = encrypted_code.decode('ascii') # some random variable names b64var = helpers.randomString() aesvar = helpers.randomString() # randomize our base64 and AES importing variable imports.append("from base64 import b64decode as " + b64var) imports.append("from Crypto.Cipher import AES as " + aesvar) # shuffle up our imports random.shuffle(imports) # add in the AES imports and any imports found in the file crypted = ";".join(imports) + "\n" # the exec() launcher for our base64'ed encrypted string to_be_encoded = "exec(" + aesvar + ".new(\"" + key + "\", " + aesvar + ".MODE_CBC, \"" + iv + "\").decrypt(" + b64var + "(\"" + encrypted_code + "\")).rstrip(b'{'))\n" to_be_encoded = to_be_encoded.encode() encoded_script = base64.b64encode(to_be_encoded).decode('ascii') crypted += "exec(" + b64var + "(\"" + encoded_script + "\"))" return crypted