Encrypt in Javascript, decrypt in PHP, using public-key cryptography

前端 未结 5 1912
不思量自难忘°
不思量自难忘° 2020-11-30 19:47

I\'d like to encrypt in JavaScript, decrypt in PHP, using public-key cryptography. I\'ve been trying to find libraries that can accomplish this, but am having issues.

<
5条回答
  •  甜味超标
    2020-11-30 20:35

    I've used something similar for my login page; it encrypts login credentials using the given public key information (N, e) which can be decrypted in PHP.

    It uses the following files that are part of JSBN:

    • jsbn.js - to work with big integers
    • rsa.js - for RSA encryption only (uses jsbn.js)
    • rng.js - basic entropy collector
    • prng4.js - ARC4 RNG backend

    To encrypt data:

    $pk = '-----BEGIN RSA PRIVATE KEY-----
    ...
    -----END RSA PRIVATE KEY-----';
    $kh = openssl_pkey_get_private($pk);
    $details = openssl_pkey_get_details($kh);
    
    function to_hex($data)
    {
        return strtoupper(bin2hex($data));
    }
    
    ?>
    
    

    This is how you would decode the sent data:

    $kh = openssl_pkey_get_private($pk);
    $details = openssl_pkey_get_details($kh);
    // convert data from hexadecimal notation
    $data = pack('H*', $data);
    if (openssl_private_decrypt($data, $r, $kh)) {
       echo $r;
    }
    

提交回复
热议问题