rsa openssl

Table of Contents

概念

对称加密算法在加密和解密时使用的是同一个秘钥;
而非对称加密算法需要两个密钥来进行加密和解密,这两个秘钥是公开密钥(public key,简称公钥)和私有密钥(private key,简称私钥)。
详细自行google或百度即可。

密钥生成

私钥

openssl genrsa -out rsa_private_key.pem 2048
  • -out 指定生成密钥的文件名
  • 2048 密钥长度,越长越安全,同时耗时越大

密钥

openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem
  • -out 指定生成文件
  • -in 密钥文件
  • -pubout 保存公钥值到输出文件中

php测试

rsa class

#!/usr/bin/php
<?php
/**
 * 使用openssl实现非对称加密
 * 
 */
class Rsa
{
    /**
     * 私钥
     * 
     */
    private $_privKey;

    /**
     * 公钥
     * 
     */
    private $_pubKey;

    /**
     * 保存文件地址
     */
    private $_keyPath;

    /**
     * 指定密钥文件地址
     * 
     */
    public function __construct($path)
    {
        if (empty($path) || !is_dir($path)) {
            throw new Exception('请指定密钥文件地址目录');
        }
        $this->_keyPath = $path;
    }

    /**
     * 创建公钥和私钥
     * 
     */
    public function createKey()
    {
        $config = [
            "config" => '/usr/local/etc/openssl/openssl.cnf',
            "digest_alg" => "sha512",
            "private_key_bits" => 4096,
            "private_key_type" => OPENSSL_KEYTYPE_RSA,
        ];
        // 生成私钥
        $rsa = openssl_pkey_new($config);
        openssl_pkey_export($rsa, $privKey, NULL, $config);
        file_put_contents($this->_keyPath . DIRECTORY_SEPARATOR . 'priv.key', $privKey);
        $this->_privKey = openssl_pkey_get_public($privKey);
        // 生成公钥
        $rsaPri = openssl_pkey_get_details($r);
        $pubKey = $rsaPri['key'];
        file_put_contents($this->_keyPath . DIRECTORY_SEPARATOR . 'pub.key', $pubKey);
        $this->_pubKey = openssl_pkey_get_public($pubKey);
    }

    /**
     * 设置私钥
     * 
     */
    public function setupPrivKey()
    {
        if (is_resource($this->_privKey)) {
            return true;
        }
        $file = $this->_keyPath . DIRECTORY_SEPARATOR . 'priv.key';
        $privKey = file_get_contents($file);
        $this->_privKey = openssl_pkey_get_private($privKey);
        return true;
    }

    /**
     * 设置公钥
     * 
     */
    public function setupPubKey()
    {
        if (is_resource($this->_pubKey)) {
            return true;
        }
        $file = $this->_keyPath . DIRECTORY_SEPARATOR . 'pub.key';
        $pubKey = file_get_contents($file);
        $this->_pubKey = openssl_pkey_get_public($pubKey);
        return true;
    }

    /**
     * 用私钥加密
     * 
     */
    public function privEncrypt($data)
    {
        if (!is_string($data)) {
            return null;
        }
        $this->setupPrivKey();
        $result = openssl_private_encrypt($data, $encrypted, $this->_privKey);
        if ($result) {
            return base64_encode($encrypted);
        }
        return null;
    }

    /**
     * 私钥解密
     * 
     */
    public function privDecrypt($encrypted)
    {
        if (!is_string($encrypted)) {
            return null;
        }
        $this->setupPrivKey();
        $encrypted = base64_decode($encrypted);
        $result = openssl_private_decrypt($encrypted, $decrypted, $this->_privKey);
        if ($result) {
            return $decrypted;
        }
        return null;
    }

    /**
     * 公钥加密
     * 
     */
    public function pubEncrypt($data)
    {
        if (!is_string($data)) {
            return null;
        }
        $this->setupPubKey();
        $result = openssl_public_encrypt($data, $encrypted, $this->_pubKey);
        if ($result) {
            return base64_encode($encrypted);
        }
        return null;
    }

    /**
     * 公钥解密
     * 
     */
    public function pubDecrypt($crypted)
    {
        if (!is_string($crypted)) {
            return null;
        }
        $this->setupPubKey();
        $crypted = base64_decode($crypted);
        $result = openssl_public_decrypt($crypted, $decrypted, $this->_pubKey);
        if ($result) {
            return $decrypted;
        }
        return null;
    }

    /**
     * __destruct
     * 
     */
    public function __destruct() {
        @fclose($this->_privKey);
        @fclose($this->_pubKey);
    }
}

$rsa = new Rsa('~/php');
$pre = $rsa->privEncrypt("zshuiquan.com");
echo $pre;
echo "\n";
$pud = $rsa->pubDecrypt($pre);
echo $pud;
echo "\n";
?>

测试

openssl genrsa -out rsa_private_key.pem 2048
openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem
cp rsa_private_key.pem priv.key
cp rsa_public_key.pem pub.key
php rsa.php

------  out ------
JCFEvSXJGqwiFB9uV0g+WxMQcFrIQmQvR9SiO+DzBH5Q2Rw3OJ69pZ5IKA0WVmlby+gomhsSRtDDs9e36v5m+is7z6oPxtw0jwzorQIWW6SP5G+pVPa43d4quKILOkrWBPUyXegyPcCc6bE7sGMOPpAjL6M0PvITuW4jqL2yLbRPw+eKj402UDKPHHKxS0G/2rYIY30PUl7gDGxmMQMnQc/cJoUsKhgt/zpSLxX1gwp5ZC/+2rQTddEmZuALC4BSiPmJRivXrQ27YRambu+8M0gK7WTH9NTGLx131vSnfcFLIqPtlr7UX55KlJG0oR7t77Uqmr+W9bxqPuSy6yDmVw==
zshuiquan.com

Author: josephzeng

Last Updated 2016-04-07. Created by Emacs 24.5.1 (Org mode 8.2.10)

Validate