Openssl RSA and AES

配置流程

  • 下载服务器公钥 server_public.pem
  • 上传客户公钥 customer_public.pem

命令示例

```bash
# 生成秘钥
openssl genpkey -algorithm RSA -outform PEM -out private.pem -pass pass:123456 -aes-128-cbc -pkeyopt rsa_keygen_bits:1024
# -outform PEM|DER 输出格式
# -algorithm 算法 RSA,DSA,DH,EC
# -aes-128-cbc 私钥的对称加密方式

# 根据秘钥生成公钥
openssl pkey -in private.pem -inform PEM -passin pass:123456 -out public.pem -outform PEM -pubout

# 公钥加密
openssl pkeyutl -encrypt -inkey public.pem -keyform PEM -pubin -in data.sql -out data_encrypt.sql
# 秘钥解密
openssl pkeyutl -decrypt -inkey private.pem -keyform PEM -passin pass:123456 -in data_encrypt.sql -out data_decrypt.sql

# 秘钥签名
openssl pkeyutl -sign -inkey private.pem -keyform PEM -passin pass:123456 -in data.json -out data.json.sign
# 公钥验签
openssl pkeyutl -verify -inkey public.pem -keyform PEM -pubin -in data.json -sigfile data.json.sign

代码示例

$data= 'this is my secret';
$dataLength = strlen($data);

// 生成用于AES加密的随机秘钥
$keyIvLength = openssl_cipher_iv_length("AES-128-CBC");
$keyIv = openssl_random_pseudo_bytes($keyIvLength);
$key = bin2hex($keyIv);

// RSA加密用于AES加密的随机秘钥
$public = openssl_pkey_get_public("file://server_public.pem");
openssl_public_encrypt($key, $keyEncrypt, $public, OPENSSL_PKCS1_PADDING);
openssl_free_key($public);

// AES使用随机秘钥加密数据
$dataEncrypt = openssl_encrypt($data, "AES-128-CBC", $key, 0,$keyIv);

// RSA签名数据
$private = openssl_pkey_get_private("file://customer_private.pem","123456");
openssl_sign($dataEncrypt, $dataSignature, $private);
openssl_free_key($private);

$response=[
    'code'=>0,
    'message'=>'success',
    'signature'=>base64_encode($dataSignature),
    'data'=>base64_encode($dataEncrypt),
    'key'=>base64_encode($keyEncrypt),
];

// RSA验证签名
$public = openssl_pkey_get_public("file://customer_public.pem");
$status = openssl_verify($dataEncrypt, $dataSignature, $public);
openssl_free_key($public);

// RSA解密用于AES加密的随机秘钥
$private = openssl_pkey_get_private("file://server_private.pem","123456");
openssl_private_decrypt($keyEncrypt, $keyDecrypt, $private, OPENSSL_PKCS1_PADDING);
openssl_free_key($private);

// AES使用随机秘钥解密数据
// $keyIvDecrypt = pack("H*",$keyDecrypt);
$keyIvDecrypt = hex2bin($keyDecrypt);
$dataDecrypt = openssl_decrypt($dataEncrypt, "AES-128-CBC", $keyDecrypt, 0,$keyIvDecrypt);

你可能感兴趣的:(Openssl RSA and AES)