1. 程式人生 > >javascript與php使用aes進行加密/解密

javascript與php使用aes進行加密/解密

cbc base scrip == pad encode ini echo script

  • javascript:
    a. 下載:
    npm  install  crypto-js

    b. 代碼:

    var CryptoJS = require("crypto-js");
    // 加密
    var key = CryptoJS.MD5(‘hello‘)
    key = CryptoJS.enc.Utf8.parse(key)
    var iv = CryptoJS.enc.Utf8.parse(‘1234567812345678‘)
    var encode = CryptoJS.AES.encrypt(
        ‘hello‘,
        key,
        {
            iv:iv,
            mode:CryptoJS.mode.CBC,
            padding:CryptoJS.pad.ZeroPadding
        }
    ).toString()
    console.log(encode)
    // 解密
    var bytes  = CryptoJS.AES.decrypt(
        encode,
        key,
        {
            iv:iv,
            mode:CryptoJS.mode.CBC,
            padding:CryptoJS.pad.ZeroPadding
        }
    )
    var decode = bytes.toString(CryptoJS.enc.Utf8)
    console.log(decode)

    c. 輸出:

    Kfh/NXiU/7keG+t/M0j6KQ==
    hello
    [Finished in 0.5s]
  • php:
    a. 代碼:
    <?php
    // 加密
    $str = "hello";
    $iv = "1234567812345678";
    $key = md5($str);
    $encode = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $str, MCRYPT_MODE_CBC,$iv);
    $encode = base64_encode($encode);
    echo $encode.PHP_EOL;
    // 解密
    $data = base64_decode($encode);
    $decode = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, $iv); 
    echo(trim($decode)).PHP_EOL;

    b. 輸出:

    Kfh/NXiU/7keG+t/M0j6KQ==
    hello
    [Finished in 0.2s]
  • javascript與php使用aes進行加密/解密