2012-10-24 46 views
6

我正在尋找兩個適合的代碼片段來編碼一些文本與python,這是在php解碼。我正在尋找「簡單」和兼容的東西,而我自己並沒有太多加密經驗。使用python加密數據,解密在php

如果有人能給出一個很好的工作示例!

+2

語言應該沒有關係,只要你選擇合適的加密/解密算法與預先存在的庫。 –

+0

你想編碼/解碼或加密/解密? http://stackoverflow.com/questions/4657416/difference-between-encoding-and-encryption – ale

+0

加密:明文給出一個python腳本返回一些不可讀的字符。這是一個PHP腳本,返回原始文本。在Python和php腳本中都使用了一個鍵。 – Alex

回答

14

蟒蛇加密

from Crypto.Cipher import AES 
import base64 
import os 
# the block size for the cipher object; must be 16, 24, or 32 for AES 
BLOCK_SIZE = 32 
BLOCK_SZ = 14 

# the character used for padding--with a block cipher such as AES, the value 
# you encrypt must be a multiple of BLOCK_SIZE in length. This character is 
# used to ensure that your value is always a multiple of BLOCK_SIZE 
PADDING = '{' 

# one-liner to sufficiently pad the text to be encrypted 
pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING 

# one-liners to encrypt/encode and decrypt/decode a string 
# encrypt with AES, encode with base64 
EncodeAES = lambda c, s: base64.b64encode(c.encrypt(pad(s))) 
DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(PADDING) 
secret = "332SECRETabc1234" 
iv = "HELLOWORLD123456" 
cipher=AES.new(key=secret,mode=AES.MODE_CBC,IV=iv) 
my_text_to_encode = "password" 
encoded = EncodeAES(cipher, my_text_to_encode) 
print 'Encrypted string:', encoded 

PHP解密(注意編碼的文本只是複製/從上面蟒紋貼)

<?php 
$enc = "x3OZjCAL944N/awRHSrmRBy9P4VLTptbkFdEl2Ao8gk="; 
$secret = "332SECRETabc1234"; // same secret as python 
$iv="HELLOWORLD123456"; // same iv as python 
$padding = "{"; //same padding as python 
function decrypt_data($data, $iv, $key) { 
    $cypher = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, ''); 

    if(is_null($iv)) { 
     $ivlen = mcrypt_enc_get_iv_size($cypher); 
     $iv = substr($data, 0, $ivlen); 
     $data = substr($data, $ivlen); 
    } 

    // initialize encryption handle 
    if (mcrypt_generic_init($cypher, $key, $iv) != -1) { 
      // decrypt 
      $decrypted = mdecrypt_generic($cypher, $data); 

      // clean up 
      mcrypt_generic_deinit($cypher); 
      mcrypt_module_close($cypher); 

      return $decrypted; 
    } 

    return false; 
} 



$res = decrypt_data(base64_decode($enc), $iv, $secret); 
print rtrim($res,$padding); 
?> 
+0

完美!非常感謝 – Alex

0

您可以使用python-mcrypt for python。在PHP中,你有相應的解密函數來加密。我希望php中的documentation足夠清楚地展示如何解密mcrypt。祝你好運。