简体   繁体   English

Python 中的 openssl_decrypt 是什么?

[英]What is openssl_decrypt in Python?

I can't seem to do this PHP code in python:我似乎无法在 python 中执行此 PHP 代码:

openssl_decrypt( $acipher, "aes-256-gcm", $secret, OPENSSL_RAW_DATA, $bnonce, $tag);

This is my Python code:这是我的 Python 代码:

from crypto.Cipher import AES
cipher = AES.new(acipher, AES.MODE_GCM, acipher)
plaintext = cipher.decrypt(secret)
# i don't even know where to put the "$bnonce, $tag", haha.

I'm quite stuck, please help.我卡住了,请帮忙。

From php documentation i modified your function vars you can rename them if you like从 php 文档中,我修改了您的 function 变量,您可以根据需要重命名它们

openssl_decrypt( $acipher,
             "aes-256-gcm",
             $passphrase, //This is your secret
             OPENSSL_RAW_DATA,
             $iv, //This is your nonce
             $tag //This is your tag
);

This is how it would look in python这就是它在 python 中的样子

#!/usr/bin/env python3
# pip install pycryptodome

import json

from base64 import b64encode,b64decode

from Crypto.Cipher import AES

from Crypto.Random import get_random_bytes


from Crypto.Random import get_random_bytes


def python_encrypt(data, passphrase, iv):
    """
         Encrypt using AES-256-GCM 
    """

    cipher = AES.new(passphrase, AES.MODE_GCM,iv)
    ciphertext, tag = cipher.encrypt_and_digest(data)
    json_k = [ 'nonce', 'ciphertext', 'tag' ]

    json_v = [ b64encode(x).decode('utf-8') for x in [cipher.nonce, ciphertext, tag ]]

    result = json.dumps(dict(zip(json_k, json_v))) 
   
    return result
    
    
def python_decrypt(data, passphrase, iv, tag):
    """
         Decrypt using AES-256-GCM 
    """
    
    cipher = AES.new(passphrase, AES.MODE_GCM, iv)

    decrypted = cipher.decrypt_and_verify(data, tag)
 
    return decrypted

#Testing code out
data = b"secret"   
passphrase = get_random_bytes(16)
nonce = get_random_bytes(16)

enc_json = python_encrypt(data,passphrase,nonce)

print(enc_json)

b64 = json.loads(enc_json)

json_k = [ 'nonce', 'ciphertext', 'tag' ]

jv = {k:b64decode(b64[k]) for k in json_k}


print(python_decrypt(jv['ciphertext'], passphrase, jv['nonce'], jv['tag']))

Modified from the docs文档修改

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM