js、Java前端DES加密 后端解密 前后端一致

JS

下载库文件,注意一下目录设置。
https://github.com/sytelus/CryptoJS

在这里插入图片描述

<script>
    function encrypted() {
        pre_passwd = document.getElementById("password").value

        var keyHex = CryptoJS.enc.Utf8.parse('12345678');

        var later_passwd = CryptoJS.DES.encrypt(pre_passwd, keyHex, {
            mode: CryptoJS.mode.ECB,
            padding: CryptoJS.pad.Pkcs7
        });
        document.getElementById("password").value = later_passwd.toString()
        // console.log(keyHex.toString())
        // console.log(pre_passwd)
        console.log(later_passwd.toString());

        // direct decrypt ciphertext
        /*var decrypted = CryptoJS.DES.decrypt({
            ciphertext: CryptoJS.enc.Base64.parse(encrypted.toString())
        }, keyHex, {
            mode: CryptoJS.mode.ECB,
            padding: CryptoJS.pad.Pkcs7
        });

        console.log(decrypted.toString(CryptoJS.enc.Utf8));*/
    }

</script>

Java

        <dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcprov-jdk16</artifactId>
            <version>1.46</version>
        </dependency>
public class DesUtils {

    private final static String DES = "DES";//方式
    private final static String ENCODE = "UTF-8";//编码
    private final static String defaultKey = "12345678";//8的倍数秘钥


    /**
     * 使用 默认key 加密
     *
     * @return String
     * @author lifq
     * @date 2015-3-17 下午02:46:43
     */
    public static String encrypt(String data) throws Exception {
        byte[] bt = encrypt(data.getBytes(ENCODE), defaultKey.getBytes(ENCODE));
        String strs = new BASE64Encoder().encode(bt);
        return strs;
    }

    /**
     * 使用 默认key 解密
     *
     * @return String
     * @author lifq
     * @date 2015-3-17 下午02:49:52
     */
    public static String decrypt(String data) throws IOException, Exception {
        if (data == null)
            return null;
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] buf = decoder.decodeBuffer(data);
        byte[] bt = decrypt(buf, defaultKey.getBytes(ENCODE));
        return new String(bt, ENCODE);
    }

    /**
     * Description 根据键值进行加密
     *
     * @param data
     * @param key
     *            加密键byte数组
     * @return
     * @throws Exception
     */
    public static String encrypt(String data, String key) throws Exception {
        byte[] bt = encrypt(data.getBytes(ENCODE), defaultKey.getBytes(ENCODE));
        String strs = new BASE64Encoder().encode(bt);
        return strs;
    }

    /**
     * Description 根据键值进行解密
     *
     * @param data
     * @param key
     *            加密键byte数组
     * @return
     * @throws IOException
     * @throws Exception
     */
    public static String decrypt(String data, String key) throws IOException,
            Exception {
        if (data == null)
            return null;
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] buf = decoder.decodeBuffer(data);
        byte[] bt = decrypt(buf, key.getBytes(ENCODE));
        return new String(bt, ENCODE);
    }

    /**
     * Description 根据键值进行加密
     *
     * @param data
     * @param key
     *            加密键byte数组
     * @return
     * @throws Exception
     */
    private static byte[] encrypt(byte[] data, byte[] key) throws Exception {
        // 生成一个可信任的随机数源
        SecureRandom sr = new SecureRandom();

        // 从原始密钥数据创建DESKeySpec对象
        DESKeySpec dks = new DESKeySpec(key);

        // 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
        SecretKey securekey = keyFactory.generateSecret(dks);

        // Cipher对象实际完成加密操作
        Cipher cipher = Cipher.getInstance(DES);

        // 用密钥初始化Cipher对象
        cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);

        return cipher.doFinal(data);
    }

    /**
     * Description 根据键值进行解密
     *
     * @param data
     * @param key
     *            加密键byte数组
     * @return
     * @throws Exception
     */
    private static byte[] decrypt(byte[] data, byte[] key) throws Exception {
        // 生成一个可信任的随机数源
        SecureRandom sr = new SecureRandom();

        // 从原始密钥数据创建DESKeySpec对象
        DESKeySpec dks = new DESKeySpec(key);

        // 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
        SecretKey securekey = keyFactory.generateSecret(dks);

        // Cipher对象实际完成解密操作
        Cipher cipher = Cipher.getInstance(DES);

        // 用密钥初始化Cipher对象
        cipher.init(Cipher.DECRYPT_MODE, securekey, sr);

        return cipher.doFinal(data);
    }
}
    <dependency>
        <groupId>commons-codec</groupId>
        <artifactId>commons-codec</artifactId>
        <version>1.10</version>
    </dependency>

网上说1.13版本以后不一样了,,我也不知道。建议版本一样吧,而且我这种方案前后端加密不一致。

完整前后端代码

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <link type="text/css" rel="stylesheet"
          href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.95.2/css/materialize.css"
          media="screen,projection"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
</head>

<body>
<script type="text/javascript" src="js/cryptoJS/rollups/tripledes.js" charset="UTF-8"></script>
<script type="text/javascript" src="js/cryptoJS/components/mode-ecb.js" charset="UTF-8"></script>
<!--<script type="text/javascript" src="js/crypto-js-4.0.0/tripledes.js" charset="UTF-8"></script>-->
<!--<script type="text/javascript" src="js/crypto-js-4.0.0/mode-ecb.js" charset="UTF-8"></script>-->
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script type="text/javascript"
        src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.95.2/js/materialize.min.js"></script>
<div class="row" style="margin-top: 200px">

    <form class="col s12" action="/login" method="post">
        <div class="row">
            <div class="input-field col s6" style="float: none; margin:auto">
                <input id="username" name="username" type="text" class="validate" autofocus>
                <label for="username">用户名:</label>
            </div>
        </div>
        <div class="row">
            <div class="input-field col s6" style="float: none; margin:auto">
                <input id="password" name="password" type="password" class="validate">
                <label for="password">密码:</label>
            </div>
        </div>
        <div class="row">
            <div class="input-field col s6" style="float: none; margin:auto">
                <button class="btn waves-effect waves-light" onclick="encrypted()" type="submit">登录
                    <i class="mdi-content-send right"></i>
                </button>
            </div>
        </div>


    </form>
</div>
</body>
<script>
    function encrypted() {
        pre_passwd = document.getElementById("password").value

        var keyHex = CryptoJS.enc.Utf8.parse('12345678');

        var later_passwd = CryptoJS.DES.encrypt(pre_passwd, keyHex, {
            mode: CryptoJS.mode.ECB,
            padding: CryptoJS.pad.Pkcs7
        });
        document.getElementById("password").value = later_passwd.toString()
        // console.log(keyHex.toString())
        // console.log(pre_passwd)
        console.log(later_passwd.toString());

        // direct decrypt ciphertext
        /*var decrypted = CryptoJS.DES.decrypt({
            ciphertext: CryptoJS.enc.Base64.parse(encrypted.toString())
        }, keyHex, {
            mode: CryptoJS.mode.ECB,
            padding: CryptoJS.pad.Pkcs7
        });

        console.log(decrypted.toString(CryptoJS.enc.Utf8));*/
    }

</script>
</html>

注意有几种模式:ECB、BCB、几个参数必须对应住,最好在在线网站上测试一下结果是不是对应。

image-20200811092305636

©️2020 CSDN 皮肤主题: 像素格子 设计师:CSDN官方博客 返回首页