一个非常基本的加密类,如下所示,将允许您加密和解密数据 - 加密的数据可以存储在数据库中或通过电子邮件等发送 - 没有承诺提供的安全级别但是因为很快就组装好了。
pubkey 和 hashsecret 越长越好...
<?php
class encryption{
public function __construct(){
$this->config=array(
'hashalgo' => 'sha256',
'cipher' => 'AES-128-CBC',
'hashsecret' => 'banana womble hippopotamus pomegranate',
'pubkey' => 'CAqKgAwIBAgILBAAAAAABD4Ym5g0wDQYJKoZIhvcNAQEFBQAwTDEgMB4GA1UECxMXR2xv
YmFsU2lnbiBSb290IENBIC0gUjIxEzARBgNVBAoTCkdsb2JhbFNpZ24xEzARBgNVBAMTCkdsb2Jh
bFNpZ24wHhcNMDYxMjE1MDgwMDAwWhcNMjExMjE1MDgwMDAwWjBMMSAwHgYDVQQLExdHbG9iYWxT
aWduIFJvb3QgQ0EgLSBSMjETMBEGA1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFsU2ln
bjCCASIwDQYJKoZIhvcNAQEBBQADggEPA'
);
}
private function makehash( $data, $key ){
return hash_hmac( $this->config['hashalgo'], $data, $key, true );
}
public function encrypt( $data=false ){
$conf=(object)$this->config;
if( !empty( $data ) && in_array( $conf->cipher, openssl_get_cipher_methods() ) ){
$ivlen = openssl_cipher_iv_length( $conf->cipher );
$iv = openssl_random_pseudo_bytes( $ivlen );
$encrypted = openssl_encrypt( $data, $conf->cipher, $conf->pubkey, $options=OPENSSL_RAW_DATA, $iv );
$hash = $this->makehash( $encrypted, $conf->pubkey );
return base64_encode( $iv . $hash . $encrypted );
}
return false;
}
public function decrypt( $data ){
$conf=(object)$this->config;
if( !empty( $data ) && in_array( $conf->cipher, openssl_get_cipher_methods() ) ){
$shalength=32;
$data = base64_decode( $data );
$ivlen = openssl_cipher_iv_length( $conf->cipher );
$iv = substr( $data, 0, $ivlen );
$hash = substr( $data, $ivlen, $shalength );
$encrypted = substr( $data, $ivlen + $shalength );
$decrypted = openssl_decrypt( $encrypted, $conf->cipher, $conf->pubkey, $options=OPENSSL_RAW_DATA, $iv );
if( $decrypted && hash_equals( $hash, $this->makehash( $encrypted, $conf->pubkey ) ) ){
return $decrypted;
}
}
return false;
}
}
$obj=new encryption;
$password="pocahontas";
$encrypted=$obj->encrypt( $password );
$decrypted=$obj->decrypt( $encrypted );
printf('<pre>
Password: %s
Encrypted: %s
Decrypted: %s
</pre>',$password,$encrypted,$decrypted);
?>
这将输出如下内容:
Password: pocahontas
Encrypted: Hvx3j9lwtEII3pR+m05TYDv+BV0IwLa8dQavGgaeQCJITSCU88AYhZrt+swMYNKOD3VQX6PN0mcA/rDkdwmqGw==
Decrypted: pocahontas
如您所见,原始密码每次都使用不同的值加密,但解密时总是解码为相同的原始密码。