php 和 python 通用加密解密, php-python-encrypt-decrypt, 跨平台加密解密

 

php 版:

<?php
/**
 * Valid encryption methods AES-256-CFB
 *
 * $cypher = new MyCypher($iv);
 * $php_encrypted      = $cypher->encrypt('test');
 * $php_decrypted      = $cypher->decrypt($php_encrypted);
 */
class MyCypher {
    private $key       = 'my-key-for-testing';
    private $iv        = 'testing-iv';
    private $method    = "AES-256-CFB";
    private $blocksize = 32;
    private $padwith   = '`';

    /*
     * construct for cypher class - get, set key and iv
     */
    function __construct($iv = '', $key = '')
    {
        if (is_string($key) AND $key) $this->key = $key;
        if (is_string($iv)  AND $iv)  $this->iv = $iv;
    }

    /*
     * get hased key - if key is not set on init, then default key wil be used
     */
    private function getKEY()
    {
        if (!$this->key) die('Key not set!');
        return substr(hash('sha256', $this->key), 0, 32);
    }

    /*
     * get hashed IV value - if no IV values then it throw error
     */
    private function getIV()
    {
        if (!$this->iv) die('IV not set!');
        return substr(hash('sha256', $this->iv), 0, 16);
    }

    /*
     * Encrypt given string using AES encryption standard
     */
    public function encrypt($secret)
    {
        try
        {
            $padded_secret = $secret . str_repeat($this->padwith, ($this->blocksize - strlen($secret) % $this->blocksize));
            $encrypted_string = openssl_encrypt($padded_secret, $this->method, $this->getKEY(), OPENSSL_RAW_DATA, $this->getIV());
            $encrypted_secret = base64_encode($encrypted_string);
            return $encrypted_secret;
        }
        catch (Exception $e) {
            die('Error : ' . $e->getMessage());
        }
    }

    /*
     * Decrypt given string using AES standard
     */
    public function decrypt($secret)
    {
        try
        {
            $decoded_secret = base64_decode($secret);
            $decrypted_secret = openssl_decrypt($decoded_secret, $this->method, $this->getKEY(), OPENSSL_RAW_DATA, $this->getIV());
            return rtrim($decrypted_secret, $this->padwith);
        }
        catch (Exception $e) {
            die('Error : ' . $e->getMessage());
        }
    }
}

//$cypher = new MyCypher();
//$php_encrypted = $cypher->encrypt('test');
//$php_decrypted = $cypher->decrypt($php_encrypted);
//
//echo $php_encrypted."\n".$php_decrypted."\n";

//g4ZTzk8cqOF1+GbrwuuNZ63Jqn3XEaxLRDo/Pdl8OXs=
//test

 

python 3.x 版:

#!/usr/bin/env python
# encoding: UTF-8

# Python Class for AES encryption
"""
    Example Usage
    enc_str = cipher.encrypt('secret')
    dnc_str = cipher.decrypt(enc_str)
    print(enc_str,dnc_str)
"""

from Crypto.Cipher import AES
import base64
import hashlib
import sys

class Cryptor:
    # Default Key for encryption
    rawkey = 'my-key-for-testing'
    rawiv = 'testing-iv'
    method = AES.MODE_CFB
    blocksize = 32  # 16, 32..etc
    padwith = '`'  # padding value for string

    # lambda function for padding
    pad = lambda self, s: s + (self.blocksize - len(s) % self.blocksize) * self.padwith

    """
    construct for cypher class - get, set key and iv
    """

    def __init__(self, iv=None, key=None):

        self.key = key if key is not None else self.rawkey
        self.iv = key if iv is not None else self.rawiv

    """
    get hased key - if key is not set on init, then default key wil be used
    """

    def getKEY(self):
        if not self.key:
            sys.exit('key error')

        return hashlib.sha256(str(self.key).encode('utf-8')).hexdigest()[:32]

    """
    get hashed IV value - if no IV values then it throw error
    """

    def getIV(self):
        if not self.iv:
            sys.exit('iv error')

        return hashlib.sha256(str(self.iv).encode('utf-8')).hexdigest()[:16]

    """
    Encrypt given string using AES encryption standard
    """

    def encrypt(self, text):
        cipher = AES.new(self.getKEY(), self.method, self.getIV(), segment_size=128)
        return base64.b64encode(cipher.encrypt(self.pad(text)))

    """
    Decrypt given string using AES standard
    """

    def decrypt(self, encrypted):
        encrypted = base64.b64decode(encrypted)
        cipher = AES.new(self.getKEY(), self.method, self.getIV(), segment_size=128)
        return str(cipher.decrypt(encrypted),  encoding = "utf-8").rstrip(self.padwith)


# if __name__ == '__main__':
#     aaa = Cryptor()
#     enc_str = aaa.encrypt('test')
#     print(enc_str)
#     b'g4ZTzk8cqOF1+GbrwuuNZ63Jqn3XEaxLRDo/Pdl8OXs='
#
#     dec_str = aaa.decrypt(enc_str)
#     print(dec_str)
#     test

 

 

python 2.x 版:

#!/usr/bin/env python2
#encoding: UTF-8

# Python Class for AES encryption
"""
    Example Usage
    enc_str = cipher.encrypt('secret')
    enc_str = cipher.decrypt(enc_str)
    print enc_str; #secret
"""

from Crypto.Cipher import AES
import base64
import hashlib
import sys

class MyCypher:
    #Default Key for encryption
    rawkey      = 'my-key-for-testing'
    rawiv       = 'my-key-for-testing'
    method      = AES.MODE_CFB
    blocksize   = 32  # 16, 32..etc
    padwith     = '`' # padding value for string  

    #lambda function for padding
    pad         = lambda self, s: s + (self.blocksize - len(s) % self.blocksize) * self.padwith

    """
    construct for cypher class - get, set key and iv
    """
    def __init__(self, iv='', key=''):

        if(not key):
            key = self.rawkey

        if(not iv):
            iv = self.rawiv

        self.key    = key
        self.iv     = iv

    """
    get hased key - if key is not set on init, then default key wil be used
    """
    def getKEY(self):
        if(not self.key):
            sys.exit()

        return hashlib.sha256(self.key).hexdigest()[:32]

    """
    get hashed IV value - if no IV values then it throw error
    """
    def getIV(self):
        if(not self.iv):
            sys.exit()

        return hashlib.sha256(self.iv).hexdigest()[:16]

    """
    Encrypt given string using AES encryption standard
    """
    def encrypt(self, raw):
        cipher = AES.new(self.getKEY(), self.method, self.getIV(), segment_size=128)
        return base64.b64encode(cipher.encrypt(self.pad(raw)))

    """
    Decrypt given string using AES standard
    """
    def decrypt(self, encrypted):
        encrypted = base64.b64decode(encrypted)
        cipher = AES.new(self.getKEY(), self.method, self.getIV(), segment_size=128)
        return cipher.decrypt(encrypted).rstrip(self.padwith)

 

 

 

本文:php 和 python 通用加密解密, php-python-encrypt-decrypt, 跨平台加密解密

Leave a Reply