对称加密DES/ECB/NoPadding

对称加密DES/ECB/NoPadding

前端加密

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>JS设置DES加密处理</title>
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
<script src="crypto-js.min.js"></script>
<script>
    //DES 解密 加密
    function encryptByDES(message, key) {
        var keyHex = CryptoJS.enc.Utf8.parse(key);
        var encrypted = CryptoJS.DES.encrypt(message, keyHex, {
            mode : CryptoJS.mode.ECB,
            padding : CryptoJS.pad.Pkcs7
        });
        return encrypted.toString();
    }
    //DES 解密

    function decryptByDES(ciphertext, key) {
        var keyHex = CryptoJS.enc.Utf8.parse(key);
        // direct decrypt ciphertext
        var decrypted = CryptoJS.DES.decrypt({
            ciphertext : CryptoJS.enc.Base64.parse(ciphertext)
        }, keyHex, {
            mode : CryptoJS.mode.ECB,
            padding : CryptoJS.pad.Pkcs7
        });
        return decrypted.toString(CryptoJS.enc.Utf8);
    }
</script>
<script>
    //加密
    function encryptStr() {
        var strKey = $.trim($('#key').val());
        var strMsg = $.trim($('#text1').val());
        $('#text2').val(encryptByDES(strMsg, strKey));
    }
    //解密

    function decryptStr() {
        var strKey = $.trim($('#key').val());
        var ciphertext = $.trim($('#text2').val());
        $('#text3').val(decryptByDES(ciphertext, strKey));
    }
</script>
</head>

<body>
    <h1>JS设置DES加密处理</h1>
    <label>加密秘钥key</label>
    <input type="text" value='cgj962360' id="key" />
    <div>
        <textarea id="text1" placeholder="请输入需要加密的字符" cols='50'>abcde</textarea>
        <input type="button" value="加密" onclick="encryptStr();" />
        <textarea id="text2" cols='50'></textarea>
        <input type="button" value="解密" onclick="decryptStr();" />
        <textarea id="text3"  cols='50'></textarea>
    </div>
</body>
</html>

后端加密

package com.ruoyi.common.utils;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.*;
import javax.crypto.spec.DESKeySpec;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;

/**
 * DES/ECB/NoPadding 加密
 * 与前端
 */


public class DesUtil {
    /**
     * 加密的key
     */
    public static final String KEY = "abcde";
    /**
     * @param strData 需要加密的字符串
     * @return
     */
    public static String encrypt(String strData) {
        try {
            byte[] keyBytes = KEY.getBytes(StandardCharsets.UTF_8);
            DESKeySpec dks = new DESKeySpec(keyBytes);
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey key = keyFactory.generateSecret(dks);
            Cipher ecipher = Cipher.getInstance("DES/ECB/NoPadding");

            // CBC requires an initialization vector
            ecipher.init(Cipher.ENCRYPT_MODE, key);

            ByteArrayInputStream bais = new ByteArrayInputStream(strData.getBytes(StandardCharsets.UTF_8));
            ByteArrayOutputStream baos = new ByteArrayOutputStream();


            // Base64 加密实例
            BASE64Encoder base64Encoder = new BASE64Encoder();

            //加密
            // Bytes written to out will be encrypted
            CipherOutputStream cos = new CipherOutputStream(baos, ecipher);
            byte[] buf = new byte[ecipher.getBlockSize()];

            // Read in the cleartext bytes and write to out to encrypt
            int numRead = 0;
            while (true) {
                numRead = bais.read(buf);
                boolean bBreak = false;
                if (numRead == -1 || numRead < buf.length) {
                    int pos = numRead == -1 ? 0 : numRead;
                    byte byteFill = (byte) (buf.length - pos);
                    for (int i = pos; i < buf.length; ++i) {
                        buf[i] = byteFill;
                    }
                    bBreak = true;
                }
                cos.write(buf);

                if (bBreak)
                    break;
            }
            cos.close();
            //Base64加密
            String outStr = base64Encoder.encode(baos.toByteArray());
            //结果
            return outStr;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @param encodeStr
     * @return
     */
    public static String decrypt(String encodeStr) {
        try {
            byte[] keyBytes = KEY.getBytes(StandardCharsets.UTF_8);
            DESKeySpec dks = new DESKeySpec(keyBytes);
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey key = keyFactory.generateSecret(dks);
            Cipher dcipher = Cipher.getInstance("DES/ECB/NoPadding");

            // CBC requires an initialization vector
            dcipher.init(Cipher.DECRYPT_MODE, key);
            // Base64 加密实例
            BASE64Decoder base64Decoder = new BASE64Decoder();
            // 声明加密输出
            byte[] bytes = base64Decoder.decodeBuffer(encodeStr);

            ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
            // 声明加密输出
            ByteArrayOutputStream baos = new ByteArrayOutputStream();


            CipherInputStream cis = new CipherInputStream(bais, dcipher);
            byte[] buf = new byte[dcipher.getBlockSize()];

            // Read in the decrypted bytes and write the cleartext to out
            int numRead = 0;
            while ((numRead = cis.read(buf)) >= 0) {
                if (cis.available() > 0) {
                    baos.write(buf, 0, numRead);
                } else {
                    byte byteBlock = buf[buf.length - 1];
                    int i = 0;
                    for (i = buf.length - byteBlock; i >= 0 && i < buf.length; ++i) {
                        if (buf[i] != byteBlock) {
                            break;
                        }
                    }

                    if (i == buf.length) {
                        baos.write(buf, 0, buf.length - byteBlock);
                    } else {
                        baos.write(buf);
                    }
                }
            }

            baos.close();

            return baos.toString("utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        String chen123123 = encrypt("Chen123123");
        System.out.println(chen123123.concat("    111111111111"));
        String jiemi = decrypt(chen123123);
        System.out.println(jiemi.concat("    22222222222"));


    }
}

测试结果

前端加密解密与后端加密解密,结果一样,可以搭配使用。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值