PHPPHP的读书–奥迪Q伍SA加密解密

PHP服务端与客户端交互可能提供开放API时,平时要求对敏感的数码进行加密,那时候rsa非对称加密就能派上用场了。

举个通俗易懂的例子,若是大家再登录一个网址,发送账号和密码,请求被阻挡了。

  • 密码没加密,那攻击者就直接得到了密码,那是最搓的。
  • 密码加密了,是不可逆加密,这攻击者只需求效法这一个请求即可登录。
  • 密码加密了,是可逆加密,当中辅导有时间等参数,后台能够依照时间等参数来判断是还是不是可行,但因为是在前者加密,其加密方法也能在代码中找到,找到加密办法就能够得出解密格局。

而是就算大家利用非对称加密就能够幸免上述难点。

非对称加密算法须要多少个密钥来开始展览加密和解密,那四个秘钥是公开密钥(public
key,简称公钥)和民用密钥(private key,简称私钥)。

行事进度如下,甲乙之间采纳非对称加密的方法成就了重在音讯的安全传输。

PHP 1

  • 乙方生成壹对密钥(公钥和私钥)并将公钥向其余方公开。
  • 取得该公钥的甲方使用该密钥对机密音信举办加密后再发送给乙方。
  • 乙方再用自身保留的另一把专用密钥(私钥)对加密后的消息进行解密。乙方只可以用其专用密钥(私钥)解密由相应的公钥加密后的消息。

在传输进程中,就算攻击者截获了传输的密文,并取得了乙的公钥,也心中无数破解密文,因为只有乙的私钥才能解密密文。
同样,假使乙要回复加密信息给甲,那么需求甲先颁布甲的公钥给乙用于加密,甲自身保存甲的私钥用于解密。

在非对称加密中利用的要紧算法有:QX5六SA、Elgamal、托特包算法、Rabin、D-H、ECC(椭圆曲线加密算法)等。

上边我们通过一个例子来申明什么用PHP来落实瑞鹰SA的加密解密。

<?php
class Rsa
{
    public $privateKey = '';

    public $publicKey = '';

    public function __construct()
    {
        $resource = openssl_pkey_new();
        openssl_pkey_export($resource, $this->privateKey);
        $detail = openssl_pkey_get_details($resource);
        $this->publicKey = $detail['key'];
    }

    public function publicEncrypt($data, $publicKey)
    {
        openssl_public_encrypt($data, $encrypted, $publicKey);
        return $encrypted;
    }

    public function publicDecrypt($data, $publicKey)
    {
        openssl_public_decrypt($data, $decrypted, $publicKey);
        return $decrypted;
    }

    public function privateEncrypt($data, $privateKey)
    {
        openssl_private_encrypt($data, $encrypted, $privateKey);
        return $encrypted;
    }

    public function privateDecrypt($data, $privateKey)
    {
        openssl_private_decrypt($data, $decrypted, $privateKey);
        return $decrypted;
    }
}


$rsa = new Rsa();
echo "公钥:\n", $rsa->publicKey, "\n";
echo "私钥:\n", $rsa->privateKey, "\n";

// 使用公钥加密
$str = $rsa->publicEncrypt('hello', $rsa->publicKey);
// 这里使用base64是为了不出现乱码,默认加密出来的值有乱码
$str = base64_encode($str);
echo "公钥加密(base64处理过):\n", $str, "\n";
$str = base64_decode($str);
$pubstr = $rsa->publicDecrypt($str, $rsa->publicKey);
echo "公钥解密:\n", $pubstr, "\n";
$privstr = $rsa->privateDecrypt($str, $rsa->privateKey);
echo "私钥解密:\n", $privstr, "\n";

// 使用私钥加密
$str = $rsa->privateEncrypt('world', $rsa->privateKey);
// 这里使用base64是为了不出现乱码,默认加密出来的值有乱码
$str = base64_encode($str);
echo "私钥加密(base64处理过):\n", $str, "\n";
$str = base64_decode($str);
$pubstr = $rsa->publicDecrypt($str, $rsa->publicKey);
echo "公钥解密:\n", $pubstr, "\n";
$privstr = $rsa->privateDecrypt($str, $rsa->privateKey);
echo "私钥解密:\n", $privstr, "\n";

世家执行一下能够见见公钥加密的数量,唯有私钥能解密,反之亦然,私钥加密的数目唯有公钥能解码。

执行结果如下:

PHP 2

那是PHP端的达成,可用在第叁方跟平塞内加尔达喀尔间的数目传输,但假使是前者传到后端该咋办呢,搜索了一下,发现了这些库jsencrypt

应用jsencrypt加密解密的例子如下:

<!DOCTYPE html>
<html>
<head>
  <title>JSEncrypt Example</title>
  <base id="basetag" href="/jsencrypt-2.3.0/">
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="jquery.js"></script>
  <script type="text/javascript" src="bin/jsencrypt.js"></script>
</head>
<body>

<div class="container">
  <script type="text/javascript">

  // Call this code when the page is done loading.
  $(function() {

    // Run a quick encryption/decryption when they click.
    $('#testme').click(function() {

      // Encrypt with the public key...
      var encrypt = new JSEncrypt();
      encrypt.setPublicKey($('#pubkey').val());
      var encrypted = encrypt.encrypt($('#input').val());
      console.log(encrypted)

      // Decrypt with the private key...
      var decrypt = new JSEncrypt();
      decrypt.setPrivateKey($('#privkey').val());
      var uncrypted = decrypt.decrypt(encrypted);
      console.log(uncrypted)

      // Now a simple check to see if the round-trip worked.
      if (uncrypted == $('#input').val()) {
        alert('It works!!!');
      } else {
        alert('Something went wrong....');
      }
    });
  });
</script>

<label for="privkey">Private Key</label><br/>
<textarea id="privkey" rows="15" cols="65">-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDkaTKbAERvJGE0
jGsdPXUI1FpO1uDkBkuuQU4LRv0Quw9r8j+fVNkN9rZVXMV7MiGOgb80Z0k9zRxZ
5KWOqMnSlrpyO3WjhFpDJeSmqZ4wLMFwmxrr31AjabD5Nkf9dQ7RiEIuM49g27+M
3OFvdIPcLgCyXnkl8FwBceBs38QbCXY5MrwlZr13yWZnyj6fbbG8t4atAzJ6bnj3
FZuvynC3QnMaVi6YnTIlBOUOHtqt/jsUTOCWkwKqkZh+RZF2fx3IFkSpJAOMgT5p
jSnfEJkK5E4JJHobLo/dFO0J7Gve+qb/lfJ9UpnZe78N1TAvbJiNZoN22ghbuIAW
M5qqIqOzAgMBAAECggEBAItUJFtqoVQOpADy+s/+UirNpjzbVJmjwXyNN3cnmW0g
PjsBrY+aqUCcUwLlMU2B+fg86w6jRokdWgL3t4m7Kkl8SkUuQgc5z/mP3tdPNkB6
vJDc/GIPeYnwidSrKOTSB/UGoiAesYJK6aCaiCV9tIWVxjUH7eyXnvf+qAChyrUW
PG/FirLyYmz1yRG99VKKE+iEIzemGSswU0DI0bwTFQ0MunLeJf0EdT20XppNwnl4
uoRgOBpMkW02vxDDWke2YIpk128KFRtPE3zF7W+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jANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA5GkymwBEbyRhNIxrHT11
CNRaTtbg5AZLrkFOC0b9ELsPa/I/n1TZDfa2VVzFezIhjoG/NGdJPc0cWeSljqjJ
0pa6cjt1o4RaQyXkpqmeMCzBcJsa699QI2mw+TZH/XUO0YhCLjOPYNu/jNzhb3SD
3C4Asl55JfBcAXHgbN/EGwl2OTK8JWa9d8lmZ8o+n22xvLeGrQMyem549xWbr8pw
t0JzGlYumJ0yJQTlDh7arf47FEzglpMCqpGYfkWRdn8dyBZEqSQDjIE+aY0p3xCZ
CuROCSR6Gy6P3RTtCexr3vqm/5XyfVKZ2Xu/DdUwL2yYjWaDdtoIW7iAFjOaqiKj
swIDAQAB
-----END PUBLIC KEY-----</textarea><br/>
<label for="input">Text to encrypt:</label><br/>
<textarea id="input" name="input" type="text" rows=4 cols=70>This is a test!</textarea><br/>
<input id="testme" type="button" value="Test Me!!!" /><br/>

</div>
</body>
</html>

中间的公钥和私钥都以地点PHP代码中生成的,那边好像唯有公钥加密,私钥解密。

得到当中打字与印刷出的加密后的数量,尝试在PHP中进行解密,能够观望也能解密成功。代码如下:

<?php
class Rsa
{
    public $privateKey = '-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDkaTKbAERvJGE0
jGsdPXUI1FpO1uDkBkuuQU4LRv0Quw9r8j+fVNkN9rZVXMV7MiGOgb80Z0k9zRxZ
5KWOqMnSlrpyO3WjhFpDJeSmqZ4wLMFwmxrr31AjabD5Nkf9dQ7RiEIuM49g27+M
3OFvdIPcLgCyXnkl8FwBceBs38QbCXY5MrwlZr13yWZnyj6fbbG8t4atAzJ6bnj3
FZuvynC3QnMaVi6YnTIlBOUOHtqt/jsUTOCWkwKqkZh+RZF2fx3IFkSpJAOMgT5p
jSnfEJkK5E4JJHobLo/dFO0J7Gve+qb/lfJ9UpnZe78N1TAvbJiNZoN22ghbuIAW
M5qqIq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OZyE+CMvb+XPwQKBgEeDjwTWxVhH/uksO3pw
MgbHjauD6AjuW9jc2a7ngFCWSQxQ3+xK1Spn6pbVdLPiBgInxCIl8d6S1yFU0Uan
iZHgy4fs1hdJRSuJ6qydqSwlS2C+gDpyY8ye0i+jq5VYYhKcpJCrCgaQGbleuaUd
ldp7v1FD8uyeemknGA35f6Id
-----END PRIVATE KEY-----';

    public $publicKey = '-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA5GkymwBEbyRhNIxrHT11
CNRaTtbg5AZLrkFOC0b9ELsPa/I/n1TZDfa2VVzFezIhjoG/NGdJPc0cWeSljqjJ
0pa6cjt1o4RaQyXkpqmeMCzBcJsa699QI2mw+TZH/XUO0YhCLjOPYNu/jNzhb3SD
3C4Asl55JfBcAXHgbN/EGwl2OTK8JWa9d8lmZ8o+n22xvLeGrQMyem549xWbr8pw
t0JzGlYumJ0yJQTlDh7arf47FEzglpMCqpGYfkWRdn8dyBZEqSQDjIE+aY0p3xCZ
CuROCSR6Gy6P3RTtCexr3vqm/5XyfVKZ2Xu/DdUwL2yYjWaDdtoIW7iAFjOaqiKj
swIDAQAB
-----END PUBLIC KEY-----';

    public function __construct()
    {
    }

    public function publicEncrypt($data, $publicKey)
    {
        openssl_public_encrypt($data, $encrypted, $publicKey);
        return $encrypted;
    }

    public function publicDecrypt($data, $publicKey)
    {
        openssl_public_decrypt($data, $decrypted, $publicKey);
        return $decrypted;
    }

    public function privateEncrypt($data, $privateKey)
    {
        openssl_private_encrypt($data, $encrypted, $privateKey);
        return $encrypted;
    }

    public function privateDecrypt($data, $privateKey)
    {
        openssl_private_decrypt($data, $decrypted, $privateKey);
        return $decrypted;
    }
}

$rsa = new Rsa();

// 使用公钥加密的内容
$str = 'IUMBGcLwJECdxUu3LMbeEhGQdoRjCLqFwfZQBO/Odh3tClbq76Tva7yYqTVxexXLmZ3uY8DrOk/XwcVVRr6g9rBnv/zxBxUShCdN0CwkoguvI+6Oju2aUBlM4FhUp+gmasa5YfqylEp1RpsVAp67GMGlxZvp0ekfhFXkjSqAguPd7dKq5YjftP12xOyuJHAzzg7U+eHxffxnneKqXkK7QrfQD6VrLpbYmayPSjMza/RbjXF+d85UeUZUaF25PZ7Y7kD4Yo7/hY/L6peeOkI5//tpl6U4QY9VsFsjAbIpNMsZuNjE/cZ57Kc5WScPsmy0o9wsp5DUEJmu+YYmr6adoA==';
$str = base64_decode($str);
$pubstr = $rsa->publicDecrypt($str, $rsa->publicKey);
echo "公钥解密:\n", $pubstr, "\n";
$privstr = $rsa->privateDecrypt($str, $rsa->privateKey);
echo "私钥解密:\n", $privstr, "\n";

解码结果如下:

PHP 3

参照摘录:

百度百科
非对称加密

PHP文档 加密扩充

相关文章