def setUp(self): self.pem_priv_key = """-----BEGIN PRIVATE KEY----- MIIEwAIBADANBgkqhkiG9w0BAQEFAASCBKowggSmAgEAAoIBAQDDLrmt4lKRpm6P 2blptwJsa1EBuxuuAayLjwNqKGvm5c1CAUEa/NtEpUMM8WYKRDwxzakUIGI/BdP3 NOEMphcs5+OekgJLhzoSdtAIrXPy8JIidENZE6FzCJ2b6fHU5O4hoNvv1Bx5yoZr HVaWJIZMRRocJJ0Nf9oMaU8IE6m6OdBzQHEwcnL2/a8Q3VxstHufzjILmaZD9WL+ 6AESlQMKZPNQ+Xd7d4nvnVkY4ZV46tA+KvADGuotgovQwG+uiyQoGRrQUms21vHF zIvd3G9OCiyCTCHSyfsE3g7tks33NZ8O8gF8xa9OmU9TQPwwAyUr6JQXz0CW77o7 Cr9LpHuNAgMBAAECggEBAJRbMbtfqc8XqDYjEfGur2Lld19Pb0yl7RbvD3NjYhDR X2DqPyhaRfg5fWubGSp4jyBz6C5qJwMsVN80DFNm83qoj7T52lC6aoOaV6og3V8t SIZzxLUyXKdpRxM5kR13HSHmeQYkPbi9HcrRM/1PqdzTMXNuyQl3wq9oZDAJchsf fmoh080htkaxhEb1bMXa2Lj7j2OIkHOsQeIu6BdbxIKRPIT+zrcklE6ocW8fTWAS Qi3IZ1FYLL+fs6TTxjx0VkC8QLaxWxY0pqTiwS7ndZiZKc3l3ARuvRk8buP+X3Jg BD86FQ18OXZC9boMbDbzv2cOLtdkq5pS3lJE4F9gjYECgYEA69ukU2pNWot2OPwK PuPwAXWNrvnvFzQgIc0qOiCmgKJU6wqunlop4Bx5XmetHExVyJVBEhaHoDr0F3Rs gt8IclKDsWGXoVcgfu3llMimiZ05hOf/XtcGTCZwZenMQ30cFh4ZRuUu7WCZ9tqO 28P8jCXB3IcaRpRnNvVvmCr5NXECgYEA09nUzRW993SlohceRW2C9fT9HZ4BaPWO 5wVlnoo5mlUfAyzl+AGT/WlKmrn/1gAHIznQJ8ZIABQvPaBXhvkANXZP5Ie0lObw jA7qFuKt7yV4GGlDnU1MOLh+acABMQBGSx8BJDaomH7glTiPEPTZjoP6wfAsd1uv Knjt7jH2ad0CgYEAx9ghknRd+rx0fbBBVix4riPW20324ihOmZVnlD0aF6B0Z3tz ncUz+irmQ7GBIpsjjIO60QK6BHAvZrhFQVaNp6B26ZORkSlr5WDZyImDYtMPa6fP 36I+OcPQNOo3I3Acnjj+ne2PJ59Ula92oIudr3pGmv72qpsQIacw2TSAWGECgYEA sdNAN+HPMn68ZaGoLDjvW8uIB6tQnay5hhvWn8yA65YV0RGH+7Q/Z9BQ6i3EnPor A5uMqUZbu4011jHYJpiuXzHvf/GVWAO92KLQReOCgqHd/Aen1MtEdrwOiG+90Ebd ukLNL3ud61tc4oS2OlJ8p48LFm2mtY3FLA6UEYPoxhUCgYEAtsfWIGnBh7XC+HwI 2higSgN92VpJHSPOyOi0aG/u5AEQ+fsCUIi3KakxzvmiGMAEvWItkKyz2Gu8smtn 2HVsGxI5UW7aLw9s3qe8kyMSfUk6pGamVhJUQmDr77+5zEzykPBxwGwDwdeR43CR xVgf/Neb/avXgIgi6drj8dp1fWA= -----END PRIVATE KEY----- """ rsa_priv_key = RSA.importKey(self.pem_priv_key) self.priv_key = PKCS1_v1_5.new(rsa_priv_key) self.pub_key = PKCS1_v1_5.new(rsa_priv_key.publickey()) unittest.TestCase.setUp(self)
def rsa(origin): print("\nRSA") while True: key_length: int = int(input("key length(x256, >=1024): ")) if key_length < 1024 or (key_length % 256) != 0: print( "key length should longer than 1024 and should divisible with 256" ) else: break key = RSA.generate(key_length) # random key generate private_key = key.exportKey('DER') public_key = key.publickey().exportKey('DER') private_key = RSA.importKey(private_key) public_key = RSA.importKey(public_key) encrypt = PKCS1_v1_5.new(public_key) cipher_text = encrypt.encrypt(origin.encode('utf-8')) print(f"encrypted: {cipher_text}") decrypt = PKCS1_v1_5.new(private_key) plaintext = decrypt.decrypt(cipher_text, sentinel=None).decode() print(f"decrypted: {plaintext}")
def encrypt_and_decrypt_test(): # 加载公钥 recipient_key = RSA.import_key(open("my_rsa_public.pem").read()) cipher_rsa = PKCS1_v1_5.new(recipient_key) # type: ignore en_data = cipher_rsa.encrypt(b"123456") print(len(en_data), en_data) # 读取密钥 private_key = RSA.import_key(open("my_private_rsa_key.bin").read()) cipher_rsa = PKCS1_v1_5.new(private_key) # type: ignore data = cipher_rsa.decrypt(en_data, None) print(data)
def encrypt_and_decrypt_test(password="******"): # 加载公钥 recipient_key = RSA.import_key(open("my_rsa_public.pem").read()) cipher_rsa = PKCS1_v1_5.new(recipient_key) en_data = cipher_rsa.encrypt(b"123456") print(len(en_data), en_data) # 读取密钥 private_key = RSA.import_key(open("my_private_rsa_key.bin").read(), passphrase=password) cipher_rsa = PKCS1_v1_5.new(private_key) data = cipher_rsa.decrypt(en_data, None) print(data)
def decrypt(self, cipher): """ :type cipher long :param cipher: 密文 :return: """ cipher = self.encoding_2_long(cipher, self.cipher_encoding) if self.d is not None: d = self.d else: d = inverse(self.e, (self.p - 1) * (self.q - 1)) if self.n is not None: n = self.n else: n = self.p * self.q rsa = RSA.construct((n, self.e, d)) if self.padding == 'PKCS1_OAEP': rsa = PKCS1_OAEP.new(rsa) plain = rsa.decrypt(long_to_bytes(cipher)) elif self.padding == 'PKCS1_v1_5': rsa = PKCS1_v1_5.new(rsa) plain = rsa.decrypt(long_to_bytes(cipher), True) else: plain = pow(cipher, d, n) return self.long_2_encoding(plain, self.plain_encoding) plain = self.long_2_encoding(bytes_to_long(plain), self.plain_encoding) return plain
def encrypt(self, plain): """ :type plain long :param plain: 明文 :return: """ plain = self.encoding_2_long(plain, self.plain_encoding) rsa = RSA.construct(( self.n, self.e, )) # 最佳非对称加密填充(OAEP) if self.padding == 'PKCS1_OAEP': rsa = PKCS1_OAEP.new(rsa) cipher = rsa.encrypt(long_to_bytes(plain)) elif self.padding == 'PKCS1_v1_5': rsa = PKCS1_v1_5.new(rsa) cipher = rsa.encrypt(long_to_bytes(plain)) else: cipher = pow(plain, self.e, self.n) return self.long_2_encoding(cipher, self.cipher_encoding) cipher = self.long_2_encoding(bytes_to_long(cipher), self.cipher_encoding) return cipher
def test_return_type(self): pt = b"XYZ" cipher = PKCS.new(self.key1024) ct = cipher.encrypt(pt) self.assertTrue(isinstance(ct, bytes)) pt2 = cipher.decrypt(ct, b'\xAA' * 3) self.assertTrue(isinstance(pt2, bytes))
def mid_sever_decode(self, cypher, sq, url): prk = self.mid_server_transport_priKey2(self, sq, url) print(cypher) prk = prk.replace("\\n", "")[27:-25] start = '-----BEGIN RSA PRIVATE KEY-----\n' end = '-----END RSA PRIVATE KEY-----' length = len(prk) divide = 64 # 切片长度 offset = 0 # 拼接长度 result0 = '' while length - offset > 0: if length - offset > divide: result0 += prk[offset:offset + divide] + '\n' else: result0 += prk[offset:] + '\n' offset += divide result0 = start + result0 + end prk = result0 prk = RSA.importKey(prk) prk0 = Cipher_pkcs1_v1_5.new(prk) # if(prk['code']==200): # prk=prk['prk'] result = prk0.decrypt(base64.b64decode(cypher), prk0) msg.deleteis_by_sq(sq) print(result) return {'code': 200, 'result': str(result)}
def _add_header_client_encryption_key(api_context: ApiContext, key: bytes, custom_headers: Dict[str, str]) -> None: public_key_server = api_context.installation_context.public_key_server key_cipher = PKCS1_v1_5_Cipher.new(public_key_server) key_encrypted = key_cipher.encrypt(key) key_encrypted_base64 = base64.b64encode(key_encrypted).decode() custom_headers[_HEADER_CLIENT_ENCRYPTION_KEY] = key_encrypted_base64
def _encrypt(connection_info_str, public_key): """Encrypt the connection information using a generated AES key that is then encrypted using the public key passed from the server. Both are then returned in an encoded JSON payload. This code also exists in the Python kernel-launcher's launch_ipykernel.py script. """ aes_key = get_random_bytes(16) cipher = AES.new(aes_key, mode=AES.MODE_ECB) # Encrypt the connection info using the aes_key encrypted_connection_info = cipher.encrypt(pad(connection_info_str, 16)) b64_connection_info = base64.b64encode(encrypted_connection_info) # Encrypt the aes_key using the server's public key imported_public_key = RSA.importKey(base64.b64decode(public_key.encode())) cipher = PKCS1_v1_5.new(key=imported_public_key) encrypted_key = base64.b64encode(cipher.encrypt(aes_key)) # Compose the payload and Base64 encode it payload = { "version": LAUNCHER_VERSION, "key": encrypted_key.decode(), "conn_info": b64_connection_info.decode() } b64_payload = base64.b64encode( json.dumps(payload).encode(encoding='utf-8')) return b64_payload
def get_sign(ts,token): s = token[:50] + ts key = '-----BEGIN PUBLIC KEY-----\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDQENQujkLfZfc5Tu9Z1LprzedEO3F7gs+7bzrgPsMl29LX8UoPYvIG8C604CprBQ4FkfnJpnhWu2lvUB0WZyLq6sBrtuPorOc42+gLnFfyhJAwdZB6SqWfDg7bW+jNe5Ki1DtU7z8uF6Gx+blEMGo8Dg+SkKlZFc8Br7SHtbL2tQIDAQAB\n-----END PUBLIC KEY-----' public_key = RSA.import_key(key) cipher = PKCS1_v1_5.new(public_key) encrypted_bytes = cipher.encrypt(s.encode()) return b64encode(encrypted_bytes).decode()
def Decrypt(private_key,ciphertext):#根据秘钥和密文解密 cipher_rsa = PKCS1_v1_5.new(RSA.import_key(private_key.encode())) ret = cipher_rsa.decrypt(base64.b64decode(ciphertext),None) if ret!=None: return ret.decode() else: return None
def decrypt(en_data): """ @param string en_data @param string password return dict """ # 读取密钥 private_key = RSA.import_key( open(os.getcwd() + "/app/my_private_rsa_key.bin").read()) cipher_rsa = PKCS1_v1_5.new(private_key) # type: ignore #切割字符串 en_data_list = en_data.split(",") data = "" for en in en_data_list: en = base64.b64decode(en) if len(en) == 127: hex_fixed = '00' + en.hex() en = base64.b16decode(hex_fixed.upper()) try: data += str( cipher_rsa.decrypt(en, None), "utf8" ) #chardet.detect(cipher_rsa.decrypt(en, None))['encoding'])#推断字符集 except Exception as e: print(e) return json.loads(data, encoding='utf8')
def _get_encrypted_card_number(self, card_number: string) -> string: pk_json = self._http_session.get(self._public_key_url, headers=self._default_headers).json() rsa_pk = RSA.importKey(pk_json['publicKey']) cipher = PKCS1_v1_5.new(rsa_pk) cipher_text = cipher.encrypt(card_number.encode()) encrypted_card_number = str(base64.b64encode(cipher_text), "utf-8") + ":".join([":3", pk_json['keyId'], self._get_obfuscated_card_number(card_number=card_number)]) return encrypted_card_number
def _perform_login(self, username, password): try: from Cryptodome.PublicKey import RSA from Cryptodome.Cipher import PKCS1_v1_5 except ImportError: try: from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_v1_5 except ImportError: raise ExtractorError('pycryptodomex not found. Please install', expected=True) key_data = self._download_json( 'https://passport.bilibili.tv/x/intl/passport-login/web/key?lang=en-US', None, note='Downloading login key', errnote='Unable to download login key')['data'] public_key = RSA.importKey(key_data['key']) password_hash = PKCS1_v1_5.new(public_key).encrypt((key_data['hash'] + password).encode('utf-8')) login_post = self._download_json( 'https://passport.bilibili.tv/x/intl/passport-login/web/login/password?lang=en-US', None, data=urlencode_postdata({ 'username': username, 'password': base64.b64encode(password_hash).decode('ascii'), 'keep_me': 'true', 's_locale': 'en_US', 'isTrusted': 'true' }), note='Logging in', errnote='Unable to log in') if login_post.get('code'): if login_post.get('message'): raise ExtractorError(f'Unable to log in: {self.IE_NAME} said: {login_post["message"]}', expected=True) else: raise ExtractorError('Unable to log in')
def _encode_password(self, password: str = None) -> Optional[str]: """Encrypts the raw password into a form that Instagram accepts.""" if not self.state.public_api_key: return if not any([password, self._raw_password]): return key = Random.get_random_bytes(32) iv = Random.get_random_bytes(12) time = int(datetime.datetime.now().timestamp()) pubkey = base64.b64decode(self.state.public_api_key) rsa_key = RSA.importKey(pubkey) rsa_cipher = PKCS1_v1_5.new(rsa_key) encrypted_key = rsa_cipher.encrypt(key) aes = AES.new(key, AES.MODE_GCM, nonce=iv) aes.update(str(time).encode('utf-8')) encrypted_password, cipher_tag = aes.encrypt_and_digest(bytes(password or self._raw_password, 'utf-8')) encrypted = bytes([1, int(self.state.public_api_key_id), *list(iv), *list(struct.pack('<h', len(encrypted_key))), *list(encrypted_key), *list(cipher_tag), *list(encrypted_password)]) encrypted = base64.b64encode(encrypted).decode('utf-8') encrypted_password = f'#PWD_INSTAGRAM:4:{time}:{encrypted}' if password is not None: return encrypted_password self._encoded_password = encrypted_password
def decrypt(self, ciphertext, key, padding="pkcs1_padding"): if padding == "pkcs1_padding": cipher = PKCS1_v1_5.new(key) if self.with_digest: dsize = SHA.digest_size else: dsize = 0 sentinel = Random.new().read(32 + dsize) text = cipher.decrypt(ciphertext, sentinel) if dsize: _digest = text[-dsize:] _msg = text[:-dsize] digest = SHA.new(_msg).digest() if digest == _digest: text = _msg else: raise DecryptionFailed() else: if text == sentinel: raise DecryptionFailed() elif padding == "pkcs1_oaep_padding": cipher = PKCS1_OAEP.new(key) text = cipher.decrypt(ciphertext) else: raise Exception("Unsupported padding") return text
def de_js_encrypt(en_pwd): """ 解密通过jsencrypt.js文件加密的密码 :param en_pwd: :return: """ key = """-----BEGIN RSA PRIVATE KEY----- MIICWwIBAAKBgGhvDNv1H/3EGeNcS+ju3Ytx7QlWtvUi3KqV5U73md9G4Gyw+izQ uvYYnZ/rDZrHocLB2fVcSZKKj8vNxkkpNqv00OJCGbwzGcOtXOpsRpiY2qhd0kvR wglnN84h9kWq8C6oMe/eWwZkpsCQJMmtiHeHdzSUxHkf4mpwxUfVDqF5AgMBAAEC gYBKjjUs9qN/JDejJCohQh4xxgSGLTzyZpAIzHhnVsaoKs5faj1AL0e6Fzq4hzMw M6LdCk2TJ+5ySq97vQz5AA5B5nf0y4zokCwYn5vdFVVtZeyiVeY0LYSpEvBS0xHY G3SJWLjMEtql2k1xJ8/1jvFkMx5SJKzruFFTvkRKn4bRAQJBANAuL2HZDjgcqgeF M7pQOKR+MxJzkN0hWBap1yJ5HQnUPqsEyBD3/BIcffCk2rQkfxnMT7gbnbiWVUd7 /Ioh+FkCQQCAbClrx7wQW26JMjRqSBVyHWm1RoYDi0/USs7B9mct2KNGkPVr8dAB nm/glt5Rs9ay2QHbI103TjSPP938xs4hAkB6oup4utQcjA5B1d8uH3nutQVDFl89 VRo+Z5j7jttjYev09SEileOhi7VJIORRgLp7KRfBPkuAZNciAFE50l8pAkBYE9bE yRQ+07aX+grg6ddrkKizX08Cl0WFAFmVxf02AGLbPwhTpGFY+uUYT+DigEk8GIGh XjvMdqKtrMv/VgqBAkEAjqQqCyiK1R9INladDpt8PjAJZecr1PLVdulyzlHvMm2l CHd72qhDwZUKVQck56xLGpPVPBGyyMl+cjRhZ+mnIQ== -----END RSA PRIVATE KEY-----""" rsakey = RSA.importKey(key) # 导入私钥 cipher = PKCS1_v1_5.new(rsakey) # 生成对象 missing_padding = len(en_pwd) % 4 if missing_padding: en_pwd += '=' * (4 - missing_padding) text = cipher.decrypt(base64.b64decode(en_pwd.encode('utf-8')), "ERROR") # 将密文解密成明文,返回的是一个bytes类型数据,需要自己转换成str return text.decode('utf-8')
def _encrypt_password(self) -> None: """Encrypts the raw password into a form that Instagram accepts.""" if not self.state.public_api_key: return # the api key will be retrieved from the first request, so it will not # be present during the initial request key = Random.get_random_bytes(32) iv = Random.get_random_bytes(12) time = int(datetime.datetime.now().timestamp()) pubkey = base64.b64decode(self.state.public_api_key) rsa_key = RSA.importKey(pubkey) rsa_cipher = PKCS1_v1_5.new(rsa_key) encrypted_key = rsa_cipher.encrypt(key) aes = AES.new(key, AES.MODE_GCM, nonce=iv) aes.update(str(time).encode('utf-8')) encrypted_password, cipher_tag = aes.encrypt_and_digest(bytes(self._unencrypted_password, 'utf-8')) encrypted = bytes([1, int(self.state.public_api_key_id), *list(iv), *list(struct.pack('<h', len(encrypted_key))), *list(encrypted_key), *list(cipher_tag), *list(encrypted_password)]) encrypted = base64.b64encode(encrypted).decode('utf-8') self._encrypted_password = f'#PWD_INSTAGRAM:4:{time}:{encrypted}'
def encrypt(s): # 标准的rsa调python的库就可以了 public_key = r"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDhNhuAr4UjFv+cj99PbAQWWx9H X+3jSRThJqJdXkWUMFMTRay8EYRtPFIiwiOUU4gCh4ePMxiuZJWUBHe1waOkXEFc Kg17luhVqECsO+EOLhxa3yHoXA5HcSKlG85hNV3G4uQCr+C8SOE0vCGTnMdnEGmU nG1AGGe44YKy6XR4VwIDAQAB" rsa_key = RSA.import_key(base64.b64decode(public_key)) cipher = PKCS1_v1_5.new(rsa_key) return base64.b64encode(cipher.encrypt( s.encode(encoding="UTF-8"))).decode("UTF-8")
def testVerify1(self): for test in self._testData: # Build the key key = RSA.importKey(test[0]) # The real test cipher = PKCS.new(key) pt = cipher.decrypt(t2b(test[2]), "---") self.assertEqual(pt, b(test[1]))
def rsa_decrypt(key, data): sentinel = Random.new().read(35) cipher = PKCS1_v1_5.new(key) b = base64.b64decode(data) s = b''.join([ cipher.decrypt(b[i:i + 128], sentinel) for i in range(0, len(b), 128) ]) return s.decode('utf-8')
def _encrypted_password(public_key, password): try: raw_key = b64decode(public_key) key = RSA.importKey(raw_key) cipher = PKCS1_v1_5.new(key) return b64encode(cipher.encrypt(password.encode("utf-8"))) except Exception as e: print(e)
def RSA_gKey_Decrypt(cipher_text): with open('ghost-private.pem', 'rb') as f: key = f.read() rsakey = RSA.importKey(key) # 导入读取到的私钥 cipher = Cipher_pkcs1_v1_5.new(rsakey) # 生成对象 # 将密文解密成明文,返回的是bytes类型,需要自己转成str,主要是对中文的处理 text = cipher.decrypt(base64.b64decode(cipher_text), "ERROR") return text.decode(encoding=encode_gbk_utf8)
def RSA_gKey_Encrypt(message): with open('ghost-public.pem', 'rb') as f: key = f.read() rsakey = RSA.importKey(key) # 导入读取到的公钥 cipher = Cipher_pkcs1_v1_5.new(rsakey) # 生成对象 # 加密message明文,python3加密的数据必须是bytes,不能是str cipher_text = base64.b64encode( cipher.encrypt(message.encode(encoding=encode_gbk_utf8))) return cipher_text
def get_header_key(priva_key): public_key = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAM1xhOWaThSMpfxFsjV5YaWOFHt+6RvS+zH2Pa47VVr8PkZYnRaaKKy2MYBuEh7mZfM/R1dUXTgu0gp6VTNeNQkCAwEAAQ==" # 导入公钥 rsa_key = RSA.import_key(base64.b64decode(public_key)) # 生成对象 rsa_object = PKCS1_v1_5.new(rsa_key) # 加密 header_key = base64.b64encode(rsa_object.encrypt(priva_key.encode(encoding="utf-8"))) return header_key
def testEncryptVerify1(self): # Encrypt/Verify messages of length [0..RSAlen-11] # and therefore padding [8..117] for pt_len in range(0, 128 - 11 + 1): pt = self.rng(pt_len) cipher = PKCS.new(self.key1024) ct = cipher.encrypt(pt) pt2 = cipher.decrypt(ct, "---") self.assertEqual(pt, pt2)
def testEncryptVerify1(self): # Encrypt/Verify messages of length [0..RSAlen-11] # and therefore padding [8..117] for pt_len in range(0,128-11+1): pt = self.rng(pt_len) cipher = PKCS.new(self.key1024) ct = cipher.encrypt(pt) pt2 = cipher.decrypt(ct, "---") self.assertEqual(pt,pt2)
def decrypt(self, text: str): """ rsa 解密 """ key = RSA.import_key(self._get_private_key()) cipher = PKCS1_v1_5.new(key) return cipher.decrypt(base64.b64decode(text), Random.new().read(15 + SHA.digest_size)).decode()
def rsa_encode(self, public_key_file, plaintext): # 加载公钥 plaintext = plaintext.encode(encoding='utf-8') recipient_key = RSA.import_key(open(public_key_file).read()) cipher_rsa = PKCS1_v1_5.new(recipient_key) en_data = cipher_rsa.encrypt(plaintext) print(len(en_data), en_data) return en_data
def __init__(self, s): recipient_key = RSA.import_key(open("public.pem").read()) self.rsa = PKCS1_v1_5.new(recipient_key) # 使用CBC模式加密 self.aes_mode = AES.MODE_CBC self.user_auth_key = {}
def encrypt(self, msg, key, padding="pkcs1_padding"): if padding == "pkcs1_padding": cipher = PKCS1_v1_5.new(key) if self.with_digest: # add a SHA digest to the message h = SHA.new(msg) msg += h.digest() elif padding == "pkcs1_oaep_padding": cipher = PKCS1_OAEP.new(key) else: raise Exception("Unsupported padding") return cipher.encrypt(msg)
def testVerify2(self): # Verify that decryption fails if ciphertext is not as long as # RSA modulus cipher = PKCS.new(self.key1024) self.assertRaises(ValueError, cipher.decrypt, '\x00'*127, "---") self.assertRaises(ValueError, cipher.decrypt, '\x00'*129, "---") # Verify that decryption fails if there are less then 8 non-zero padding # bytes pt = b('\x00\x02' + '\xFF'*7 + '\x00' + '\x45'*118) pt_int = bytes_to_long(pt) ct_int = self.key1024._encrypt(pt_int) ct = long_to_bytes(ct_int, 128) self.assertEqual("---", cipher.decrypt(ct, "---"))
def testEncrypt1(self): for test in self._testData: # Build the key key = RSA.importKey(test[0]) # RNG that takes its random numbers from a pool given # at initialization class randGen: def __init__(self, data): self.data = data self.idx = 0 def __call__(self, N): r = self.data[self.idx:self.idx+N] self.idx += N return r # The real test cipher = PKCS.new(key, randfunc=randGen(t2b(test[3]))) ct = cipher.encrypt(b(test[1])) self.assertEqual(ct, t2b(test[2]))
def testMemoryview(self): pt = b"XER" cipher = PKCS.new(self.key1024) ct = cipher.encrypt(memoryview(bytearray(pt))) pt2 = cipher.decrypt(memoryview(bytearray(ct)), "---") self.assertEqual(pt, pt2)
def testEncrypt2(self): # Verify that encryption fail if plaintext is too long pt = '\x00'*(128-11+1) cipher = PKCS.new(self.key1024) self.assertRaises(ValueError, cipher.encrypt, pt)
def run(self): if self.options.action.upper() == 'MASTERKEY': fp = open(options.file, 'rb') data = fp.read() mkf= MasterKeyFile(data) mkf.dump() data = data[len(mkf):] if mkf['MasterKeyLen'] > 0: mk = MasterKey(data[:mkf['MasterKeyLen']]) data = data[len(mk):] if mkf['BackupKeyLen'] > 0: bkmk = MasterKey(data[:mkf['BackupKeyLen']]) data = data[len(bkmk):] if mkf['CredHistLen'] > 0: ch = CredHist(data[:mkf['CredHistLen']]) data = data[len(ch):] if mkf['DomainKeyLen'] > 0: dk = DomainKey(data[:mkf['DomainKeyLen']]) data = data[len(dk):] if self.options.system and self.options.security: # We have hives, let's try to decrypt with them self.getLSA() decryptedKey = mk.decrypt(self.dpapiSystem['UserKey']) if decryptedKey: print('Decrypted key with UserKey') print('Decrypted key: 0x%s' % hexlify(decryptedKey).decode('latin-1')) return decryptedKey = mk.decrypt(self.dpapiSystem['MachineKey']) if decryptedKey: print('Decrypted key with MachineKey') print('Decrypted key: 0x%s' % hexlify(decryptedKey).decode('latin-1')) return decryptedKey = bkmk.decrypt(self.dpapiSystem['UserKey']) if decryptedKey: print('Decrypted Backup key with UserKey') print('Decrypted key: 0x%s' % hexlify(decryptedKey).decode('latin-1')) return decryptedKey = bkmk.decrypt(self.dpapiSystem['MachineKey']) if decryptedKey: print('Decrypted Backup key with MachineKey') print('Decrypted key: 0x%s' % hexlify(decryptedKey).decode('latin-1')) return elif self.options.key: key = unhexlify(self.options.key[2:]) decryptedKey = mk.decrypt(key) if decryptedKey: print('Decrypted key with key provided') print('Decrypted key: 0x%s' % hexlify(decryptedKey).decode('latin-1')) return elif self.options.pvk and dk: pvkfile = open(self.options.pvk, 'rb').read() key = PRIVATE_KEY_BLOB(pvkfile[len(PVK_FILE_HDR()):]) private = privatekeyblob_to_pkcs1(key) cipher = PKCS1_v1_5.new(private) decryptedKey = cipher.decrypt(dk['SecretData'][::-1], None) if decryptedKey: domain_master_key = DPAPI_DOMAIN_RSA_MASTER_KEY(decryptedKey) key = domain_master_key['buffer'][:domain_master_key['cbMasterKey']] print('Decrypted key with domain backup key provided') print('Decrypted key: 0x%s' % hexlify(key).decode('latin-1')) return elif self.options.sid and self.options.key is None: # Do we have a password? if self.options.password is None: # Nope let's ask it from getpass import getpass password = getpass("Password:"******"Password:"******"G$BCKUPKEY_PREFERRED", "G$BCKUPKEY_P"): buffer = crypto.decryptSecret(connection.getSessionKey(), lsad.hLsarRetrievePrivateData(dce, resp['PolicyHandle'], keyname)) guid = bin_to_string(buffer) name = "G$BCKUPKEY_{}".format(guid) secret = crypto.decryptSecret(connection.getSessionKey(), lsad.hLsarRetrievePrivateData(dce, resp['PolicyHandle'], name)) keyVersion = struct.unpack('<L', secret[:4])[0] if keyVersion == 1: # legacy key backup_key = P_BACKUP_KEY(secret) backupkey = backup_key['Data'] if self.options.export: logging.debug("Exporting key to file {}".format(name + ".key")) open(name + ".key", 'wb').write(backupkey) else: print("Legacy key:") print("0x%s" % hexlify(backupkey)) print("\n") elif keyVersion == 2: # preferred key backup_key = PREFERRED_BACKUP_KEY(secret) pvk = backup_key['Data'][:backup_key['KeyLength']] cert = backup_key['Data'][backup_key['KeyLength']:backup_key['KeyLength'] + backup_key['CertificateLength']] # build pvk header (PVK_MAGIC, PVK_FILE_VERSION_0, KeySpec, PVK_NO_ENCRYPT, 0, cbPvk) header = PVK_FILE_HDR() header['dwMagic'] = 0xb0b5f11e header['dwVersion'] = 0 header['dwKeySpec'] = 1 header['dwEncryptType'] = 0 header['cbEncryptData'] = 0 header['cbPvk'] = backup_key['KeyLength'] backupkey_pvk = header.getData() + pvk # pvk blob backupkey = backupkey_pvk if self.options.export: logging.debug("Exporting certificate to file {}".format(name + ".der")) open(name + ".der", 'wb').write(cert) logging.debug("Exporting private key to file {}".format(name + ".pvk")) open(name + ".pvk", 'wb').write(backupkey) else: print("Preferred key:") header.dump() print("PRIVATEKEYBLOB:{%s}" % (hexlify(backupkey))) print("\n") return elif self.options.action.upper() == 'CREDENTIAL': fp = open(options.file, 'rb') data = fp.read() cred = CredentialFile(data) blob = DPAPI_BLOB(cred['Data']) if self.options.key is not None: key = unhexlify(self.options.key[2:]) decrypted = blob.decrypt(key) if decrypted is not None: creds = CREDENTIAL_BLOB(decrypted) creds.dump() return else: # Just print the data blob.dump() elif self.options.action.upper() == 'VAULT': if options.vcrd is None and options.vpol is None: print('You must specify either -vcrd or -vpol parameter. Type --help for more info') return if options.vcrd is not None: fp = open(options.vcrd, 'rb') data = fp.read() blob = VAULT_VCRD(data) if self.options.key is not None: key = unhexlify(self.options.key[2:]) cleartext = None for i, entry in enumerate(blob.attributesLen): if entry > 28: attribute = blob.attributes[i] if 'IV' in attribute.fields and len(attribute['IV']) == 16: cipher = AES.new(key, AES.MODE_CBC, iv=attribute['IV']) else: cipher = AES.new(key, AES.MODE_CBC) cleartext = cipher.decrypt(attribute['Data']) if cleartext is not None: # Lookup schema Friendly Name and print if we find one if blob['FriendlyName'].decode('utf-16le')[:-1] in VAULT_KNOWN_SCHEMAS: # Found one. Cast it and print vault = VAULT_KNOWN_SCHEMAS[blob['FriendlyName'].decode('utf-16le')[:-1]](cleartext) vault.dump() else: # otherwise hexdump(cleartext) return else: blob.dump() elif options.vpol is not None: fp = open(options.vpol, 'rb') data = fp.read() vpol = VAULT_VPOL(data) vpol.dump() if self.options.key is not None: key = unhexlify(self.options.key[2:]) blob = vpol['Blob'] data = blob.decrypt(key) if data is not None: keys = VAULT_VPOL_KEYS(data) keys.dump() return print('Cannot decrypt (specify -key or -sid whenever applicable) ')