DES加密解密:android、java、js

需求:登录的时候WEB或APP将数据加密后传给JAVA后端,后端接收到数据解密后得到数据进行处理。

eg:

明文:12345sf$^
密文:zqia+QVK9LtJVHLzSlyFhA==

一、java端

依赖:

<dependency>
     <groupId>org.bouncycastle</groupId>
     <artifactId>bcprov-ext-jdk15on</artifactId>
     <version>1.70</version>
</dependency>
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.security.Security;
import java.util.Base64;

/**
 * 作者: 唐婉
 * 时间: 2022/8/5 11:23
 * 描述: DES加密解密算法
 */

public class MyDesUtil {

    //添加默认加密提供者-不然会使用JAVA自带的
    //java默认自带的只支持PKCS5Padding,安卓和js是7
    //需要导入jar包bcprov-ext-jdk15on
    static {
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    }

    /*秘钥  长度8的倍数*/
    public static final String SECRET_KEY = "79#t7b87#4e2&61c7*4%*a3!@@f4290f";

    /**
     * DES加密
     *
     * @param plaintext 明文
     * @return 密文
     */
    public static String encrypt(String plaintext) {
        try {
            byte[] byteContent = plaintext.getBytes(StandardCharsets.UTF_8);
            DESKeySpec desKey = new DESKeySpec(SECRET_KEY.getBytes());
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey securekey = keyFactory.generateSecret(desKey);
            Cipher cipher = Cipher.getInstance("DES/ECB/PKCS7Padding");
            cipher.init(Cipher.ENCRYPT_MODE, securekey, new SecureRandom());
            byte[] byteFinal = cipher.doFinal(byteContent);
            return Base64.getMimeEncoder().encodeToString(byteFinal);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * DES解密
     *
     * @param ciphertext 密文
     * @return 明文
     */
    public static String decrypt(String ciphertext) {
        try {
            byte[] byteContent = Base64.getMimeDecoder().decode(ciphertext);//---
            DESKeySpec desKey = new DESKeySpec(SECRET_KEY.getBytes());
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey secureKey = keyFactory.generateSecret(desKey);
            Cipher cipher = Cipher.getInstance("DES/ECB/PKCS7Padding");
            cipher.init(Cipher.DECRYPT_MODE, secureKey, new SecureRandom());
            return new String(cipher.doFinal(byteContent), "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
}

二、android端

import android.annotation.SuppressLint;
import android.os.Build;
import android.util.Base64;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;


import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import androidx.annotation.RequiresApi;

/**
 * Auth:Vincent
 * Time:2022/08/05
 * Desc:
 */
public class DESUtil {

    /*秘钥*/
    public static final String SECRET_KEY = "79#t7b87#4e2&61c7*4%*a3!@@f4290f";

    /**
     * DES加密
     *
     * @param plaintext 明文
     * @return 密文
     */
    public static String encrypt(String plaintext) {
        try {
            byte[] byteContent = plaintext.getBytes(StandardCharsets.UTF_8);
            DESKeySpec desKey = new DESKeySpec(SECRET_KEY.getBytes());
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey securekey = keyFactory.generateSecret(desKey);
            Cipher cipher = Cipher.getInstance("DES/ECB/PKCS7Padding");
            cipher.init(Cipher.ENCRYPT_MODE, securekey, new SecureRandom());
            byte[] byteFinal = cipher.doFinal(byteContent);
            return Base64.encodeToString(byteFinal, Base64.DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * DES解密
     *
     * @param ciphertext 密文
     * @return 明文
     */
    public static String decrypt(String ciphertext) {
        try {
            byte[] byteContent = Base64.decode(ciphertext, Base64.DEFAULT);
            DESKeySpec desKey = new DESKeySpec(SECRET_KEY.getBytes());
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey secureKey = keyFactory.generateSecret(desKey);
            Cipher cipher = Cipher.getInstance("DES/ECB/PKCS7Padding");
            cipher.init(Cipher.DECRYPT_MODE, secureKey, new SecureRandom());
            return new String(cipher.doFinal(byteContent), "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
}

注意:根据RFC822规定,BASE64Encoder编码每76个字符需要加上一个回车换行\n,很多Base64编码的java库还按照这个标准实行,也就是说加密后的字符串在后面会自动加个\n,如果想要不带换行符的可以换个库,比如使用Apache的 commons-codec.jar加密后是不带换行符的。

三、js  

import cryptoJs from 'crypto-js';

//DES加密
function encrypt(message){
    var key = '79#t7b87#4e2&61c7*4%*a3!@@f4290f';
    var keyHex = CryptoJS.enc.Utf8.parse(key);
    var encrypted = CryptoJS.DES.encrypt(message, keyHex, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
    });
    return encrypted.ciphertext.toString(CryptoJS.enc.Base64);
}

//DES解密
function decrypt(ciphertext){
    var key = '79#t7b87#4e2&61c7*4%*a3!@@f4290f';
    var keyHex = CryptoJS.enc.Utf8.parse(key);
    var decrypted = CryptoJS.DES.decrypt({
        ciphertext: CryptoJS.enc.Base64.parse(ciphertext)
    }, keyHex, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
    });
    var result = decrypted.toString(CryptoJS.enc.Utf8);
    return result;
}
posted @ 2022-08-24 17:51  蒂雪凌星  阅读(191)  评论(0编辑  收藏  举报
Live2D