首页 > 编程语言 >DES加密解密:android、java、js

DES加密解密:android、java、js

时间:2022-08-24 18:06:12浏览次数:182  
标签:return String java DES crypto js Cipher import

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

eg:

明文:12345678
密文:PofrPuMcG5CiXuyR5B5ysQ==

一、java端

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.util.Base64;

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

public class BearDesUtil {

    /*秘钥 保持一致才能保证加解密的值一样  长度为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");
            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");
            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");
            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");
            cipher.init(Cipher.DECRYPT_MODE, secureKey, new SecureRandom());
            return new String(cipher.doFinal(byteContent), "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
}

三、js  

这里只提供加密,解密写法和上面都差不多,一般用不到,所以等哪天闲了或者心情特别好的时候还记得这回事的话再加。

import cryptoJs from 'crypto-js';

export 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();
}

<!-- 调用  一般随机生成key把密码和和key都传给后端,这里及上面为了一致都写死-->
encryptByDES(要加密的密码密码, '79#t7b87#4e2&61c7*4%*a3!@@f4290f');

标签:return,String,java,DES,crypto,js,Cipher,import
From: https://www.cnblogs.com/smiles365/p/16621073.html

相关文章

  • abap转java时间戳
    sap与java系统交互时,日期、时间转换时间戳可以使用下面方法实现: 时间戳生成cl_pco_utility=>convert_abap_timestamp_to_java  时间戳解析cl_pco_utility=>conv......
  • JS函数封装实现控件拖拽
    js脚本exportfunctiondragBox(drag,wrap){//用于获取父容器的样式属性值functiongetCss(ele,prop){//getComputedStyle返回值是带单位的字符串,所以......
  • system desing 系统设计(十一): 评论comment功能设计
    1、互联网服务重要的功能之一就是评论了,从电商到社交,从短视频到长视频,无一例外都有评论功能!如果是一些流量小的站点(averageQPS只有几到十几那种),每天有几千条评论已经......
  • java设计思路-项目中两种接口设计方法,请讲出优缺点
    结论:通过函数式接口,可以任意组装成不同粒度的接口,使用起来很灵活,强烈推荐。第一种设计方法:packagecom.iit.service.user;importcom.iit.domain.User;//这是第1种......
  • 网页编辑器粘贴图片自动上传到服务器(Java版)
    ​ 在之前在工作中遇到在富文本编辑器中粘贴图片不能展示的问题,于是各种网上扒拉,终于找到解决方案,在这里感谢一下知乎中众大神以及TheViper。通过知乎提供的思路找到粘......
  • phantomjs实现截图
    准备阶段下载phantomjsPhantomJSAPI参考EChartsConvert浏览器查看base64编码图片方法echarts官网java后端使用freemarker生成echarts图表word流程简要说明1.下载p......
  • JS控制浏览器打印样式,分页及移除页眉页尾
    很简单,引入以下CSS即可:<style>/*分页符*/.print_gap{page-break-before:always;}.print_gap.gap_line{height:1px;background:#e5e5e5;margin:40pt030pt;......
  • mysql php js 经纬度 转换 查询
    坐标系介绍地球坐标(WGS84)WGS-84:是国际标准,GPS坐标(GoogleEarth使用、或者GPS模块)国际标准,从专业GPS设备中取出的数据的坐标系国际地图提供商使用的坐标系火星坐......
  • 【java】使用opencv获取摄像头并推流
    1、环境OSX12.5Java8vscode 2、脚本JavaCvCameraTest.javaimportjavax.swing.JFrame;importorg.bytedeco.ffmpeg.global.avcodec;importorg.bytedeco.java......
  • jsp
    注意要写成out.println,去掉system   ......