Encrypt with CryptoJS and decrypt with PHP

前端 未结 3 1446
伪装坚强ぢ
伪装坚强ぢ 2020-12-08 12:07

On the client side (mobile device) I encrypt a users password with CryptoJS:

var lib_crypt = require(\'aes\');

$.loginButton.addEventListener(\'click\', fun         


        
3条回答
  •  遥遥无期
    2020-12-08 12:44

    Here is a solution based on this comment, using openssl_decrypt from PHP.

    The JavaScript part (development with NodeJS for browsers) — first, install CryptoJS with npm install crypto-js, then your JS code:

    import aes from 'crypto-js/aes'
    import encHex from 'crypto-js/enc-hex'
    import padZeroPadding from 'crypto-js/pad-zeropadding'
    
    // message to encrypt
    let msg = "Hello world";
    
    // the key and iv should be 32 hex digits each, any hex digits you want, but it needs to be 32 on length each
    let key = encHex.parse("0123456789abcdef0123456789abcdef");
    let iv =  encHex.parse("abcdef9876543210abcdef9876543210");
    
    // encrypt the message
    let encrypted = aes.encrypt(msg, key, {iv:iv, padding:padZeroPadding}).toString();
    
    // and finally, send this "encrypted" string to your server
    

    On the PHP side, your code will look like that:

    // we use the same key and IV
    $key = hex2bin("0123456789abcdef0123456789abcdef");
    $iv =  hex2bin("abcdef9876543210abcdef9876543210");
    
    // we receive the encrypted string from the post
    $encrypted = $_POST['decrypt'];
    $decrypted = openssl_decrypt($encrypted, 'AES-128-CBC', $key, OPENSSL_ZERO_PADDING, $iv);
    // finally we trim to get our original string
    $decrypted = trim($decrypted);
    

提交回复
热议问题