IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 移动开发 -> RSA加密解密&DES加密解密 -> 正文阅读

[移动开发]RSA加密解密&DES加密解密

RSA

java

依赖

<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.15</version>
</dependency>

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>

RSACoder

package com.zzhua.rsa2;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

public class RSACoder {

    public static final String KEY_ALGORITHM = "RSA";
    public static final String SIGNATURE_ALGORITHM = "MD5withRSA";

    private static final String PUBLIC_KEY = "RSAPublicKey";
    private static final String PRIVATE_KEY = "RSAPrivateKey";

    public static byte[] decryptBASE64(String key) {
        return Base64.decodeBase64(key);
    }

    public static String encryptBASE64(byte[] bytes) {
        return Base64.encodeBase64String(bytes);
    }

    /**
     * 用私钥对信息生成数字签名
     *
     * @param data    加密数据
     * @param privateKey 私钥
     * @return
     * @throws Exception
     */
    public static String sign(byte[] data, String privateKey) throws Exception {
        // 解密由base64编码的私钥
        byte[] keyBytes = decryptBASE64(privateKey);
        // 构造PKCS8EncodedKeySpec对象
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        // KEY_ALGORITHM 指定的加密算法
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        // 取私钥匙对象
        PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec);
        // 用私钥对信息生成数字签名
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        signature.initSign(priKey);
        signature.update(data);
        return encryptBASE64(signature.sign());
    }

    /**
     * 校验数字签名
     *
     * @param data   加密数据
     * @param publicKey 公钥
     * @param sign   数字签名
     * @return 校验成功返回true 失败返回false
     * @throws Exception
     */
    public static boolean verify(byte[] data, String publicKey, String sign)
            throws Exception {
        // 解密由base64编码的公钥
        byte[] keyBytes = decryptBASE64(publicKey);
        // 构造X509EncodedKeySpec对象
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        // KEY_ALGORITHM 指定的加密算法
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        // 取公钥匙对象
        PublicKey pubKey = keyFactory.generatePublic(keySpec);
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        signature.initVerify(pubKey);
        signature.update(data);
        // 验证签名是否正常
        return signature.verify(decryptBASE64(sign));
    }

    public static byte[] decryptByPrivateKey(byte[] data, String key) throws Exception{
        // 对密钥解密
        byte[] keyBytes = decryptBASE64(key);
        // 取得私钥
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
        // 对数据解密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        return cipher.doFinal(data);
    }

    /**
     * 解密<br>
     * 用私钥解密
     *
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] decryptByPrivateKey(String data, String key)
            throws Exception {
        return decryptByPrivateKey(decryptBASE64(data),key);
    }

    /**
     * 解密<br>
     * 用公钥解密
     *
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] decryptByPublicKey(byte[] data, String key)
            throws Exception {
        // 对密钥解密
        byte[] keyBytes = decryptBASE64(key);
        // 取得公钥
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key publicKey = keyFactory.generatePublic(x509KeySpec);
        // 对数据解密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, publicKey);
        return cipher.doFinal(data);
    }

    /**
     * 加密<br>
     * 用公钥加密
     *
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] encryptByPublicKey(String data, String key)
            throws Exception {
        // 对公钥解密
        byte[] keyBytes = decryptBASE64(key);
        // 取得公钥
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key publicKey = keyFactory.generatePublic(x509KeySpec);
        // 对数据加密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        return cipher.doFinal(data.getBytes());
    }

    /**
     * 加密<br>
     * 用私钥加密
     *
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] encryptByPrivateKey(byte[] data, String key)
            throws Exception {
        // 对密钥解密
        byte[] keyBytes = decryptBASE64(key);
        // 取得私钥
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
        // 对数据加密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);
        return cipher.doFinal(data);
    }

    /**
     * 取得私钥
     *
     * @param keyMap
     * @return
     * @throws Exception
     */
    public static String getPrivateKey(Map<String, Key> keyMap)
            throws Exception {
        Key key = (Key) keyMap.get(PRIVATE_KEY);
        return encryptBASE64(key.getEncoded());
    }

    /**
     * 取得公钥
     *
     * @param keyMap
     * @return
     * @throws Exception
     */
    public static String getPublicKey(Map<String, Key> keyMap)
            throws Exception {
        Key key = keyMap.get(PUBLIC_KEY);
        return encryptBASE64(key.getEncoded());
    }

    /**
     * 初始化密钥
     *
     * @return
     * @throws Exception
     */
    public static Map<String, Key> initKey() throws Exception {
        KeyPairGenerator keyPairGen = KeyPairGenerator
                .getInstance(KEY_ALGORITHM);
        keyPairGen.initialize(1024);
        KeyPair keyPair = keyPairGen.generateKeyPair();
        Map<String, Key> keyMap = new HashMap(2);
        keyMap.put(PUBLIC_KEY, keyPair.getPublic());// 公钥
        keyMap.put(PRIVATE_KEY, keyPair.getPrivate());// 私钥
        return keyMap;
    }
}


RSACoderTest

package com.zzhua.rsa2;

import org.junit.Before;
import org.junit.Test;

import java.security.Key;
import java.util.Map;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

public class RSACoderTest {

  private String publicKey;
  private String privateKey;

  @Before
  public void setUp() throws Exception {
    Map<String, Key> keyMap = RSACoder.initKey();
    publicKey = RSACoder.getPublicKey(keyMap);
    privateKey = RSACoder.getPrivateKey(keyMap);
    System.err.println("公钥: \n\r" + publicKey);
    System.err.println("私钥: \n\r" + privateKey);
  }

  @Test
  public void test() throws Exception {
    System.err.println("公钥加密——私钥解密");
    String inputStr = "abc";
    byte[] encodedData = RSACoder.encryptByPublicKey(inputStr, publicKey);
    byte[] decodedData = RSACoder.decryptByPrivateKey(encodedData,privateKey);
    String outputStr = new String(decodedData);
    System.err.println("加密前: " + inputStr + "\n\r" + "解密后: " + outputStr);
    assertEquals(inputStr, outputStr);
  }

  @Test
  public void testSign() throws Exception {
    System.err.println("私钥加密——公钥解密");
    String inputStr = "sign";
    byte[] data = inputStr.getBytes();
    byte[] encodedData = RSACoder.encryptByPrivateKey(data, privateKey);
    byte[] decodedData = RSACoder.decryptByPublicKey(encodedData, publicKey);
    String outputStr = new String(decodedData);
    System.err.println("加密前: " + inputStr + "\n\r" + "解密后: " + outputStr);
    assertEquals(inputStr, outputStr);
    System.err.println("私钥签名——公钥验证签名");
    // 产生签名
    String sign = RSACoder.sign(encodedData, privateKey);
    System.err.println("签名:" + sign);
    // 验证签名
    boolean status = RSACoder.verify(encodedData, publicKey, sign);
    System.err.println("状态:" + status);
    assertTrue(status);
  }
}

js示例

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>使用jsencrypt执行OpenSSL的RSA加密,解密</title>
</head>
<!--引入jsencrypt.js-->
<script src="https://cdn.bootcss.com/jsencrypt/3.0.0-beta.1/jsencrypt.js"></script>
<script type="text/javascript">
    /*//公钥
    var PUBLIC_KEY = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDpznfYaSCz50hEp28u3BWR23MMLcpfH3TVmcRbHz9J6xgmDbhP5erjs7qkSbcHNo2EtNzTiBO7wD6JaOHVSBKsuNXqVoNZT2sYvrNCJAT79rm9qKGh1yjBf0soLuHiBYYxOi2G2aY1AUr8MIzjFEsagIUnN/Rhdo4YKc45tSi3+QIDAQAB';
    //私钥
    var PRIVATE_KEY = 'MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAOnOd9hpILPnSESnby7cFZHbcwwtyl8fdNWZxFsfP0nrGCYNuE/l6uOzuqRJtwc2jYS03NOIE7vAPolo4dVIEqy41epWg1lPaxi+s0IkBPv2ub2ooaHXKMF/Sygu4eIFhjE6LYbZpjUBSvwwjOMUSxqAhSc39GF2jhgpzjm1KLf5AgMBAAECgYEA5Boc7jNSRnIEHYbEgBETsiNJEL6zyy3jTGkiGkxX8IO+IZINGVYUXWYBVzrbp9vfIXNaZb1Ck0+xM1nxyaTxIVewXHdSeoWpqMb+0Gt6HApLr3b7dWTlcTGm8AEnniL6thpE5NCuUoLPxJPjAnCxMVZzivDg3TyDNhEnBMGecckCQQD/4XQlMhog2NEa3AXRjBacQw6cU3yUAntRo3r3eqzzdX+QE84Um73AEeS/BE2WtFjSoPpeLNY9WInlwk9N/jJLAkEA6ephGfqemAJCMS3n61J8ENVYLV+kGINKuOzlpY8zbTTDvfa3K3rFFeyIJ3B8v3AqxDiu+Z580/ksxyUsJvJ0SwJAA2KVKcTO6a5UndlZTltfFTQh5lmIZWDfBsZ14v5BeXsNc/d/G3CwAvF5qDlDWYILRsYQadyH/QnF0T9P00VQnwJANJ4KVaOwhRUM+q8O2jplugujmCFJclImPs7bIZDCyq/x0AttTJSDPNlGD0kYZp++nwD5KyFhhvUoA2vzMJedXQJBAKNWvohLKS+BuuwjOIRJ7sFLnaXxlShp7GcTVs1cJ5krN9beHNzaZPtjDBKlDyvd3GxH/cFdy+F5WChMNsO0j6I=';
    //使用公钥加密
    var encrypt = new JSEncrypt();
    encrypt.setPublicKey( PUBLIC_KEY );
    var str = 'device001'
    var encrypted = encrypt.encrypt(str);
    console.log('加密前数据:%o', str);
    console.log('加密后数据:%o', encrypted);
    //使用私钥解密
    var decrypt = new JSEncrypt();
    decrypt.setPrivateKey(PRIVATE_KEY);
    var uncrypted = decrypt.decrypt(encrypted);
    console.log('解密后数据:%o', uncrypted);*/

    var PUBLIC_KEY = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCLVWtmmXadwWbKAuvXWLzCY3A844s6eJ1I19JTEmMrbmaQP4hC6/4ks6Ix+BJPF/ikpVDie6gBg4qsSbrBjckA8AvflYU0ixw0rEzd+tv2o0d+afZEJdIW2SL/+78FUuGdu7ChYeUX9DLEM8dScIdWYoVREey0ei+H9dIQcLyiswIDAQAB';

    var PRIVATE_KEY = 'MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAItVa2aZdp3BZsoC69dYvMJjcDzjizp4nUjX0lMSYytuZpA/iELr/iSzojH4Ek8X+KSlUOJ7qAGDiqxJusGNyQDwC9+VhTSLHDSsTN362/ajR35p9kQl0hbZIv/7vwVS4Z27sKFh5Rf0MsQzx1Jwh1ZihVER7LR6L4f10hBwvKKzAgMBAAECgYAPXWURlFzDOr+WCUpuned63DJVVJZW5VQa40nbRUzQTkVbJNZm4tVMwM5jCkMim7ccmOpZf19gg1v4ccz5aSRAHpZ4ZwbUI4D1eHUygXeiWkGsY4oPfRiMRB/Rv3Fsd4HlaMt4Cxkg0cxvg4FwknoPGHsUBDBWXntiQhtuO9BtOQJBAOp9TuFi2B+vo6YU4YtLfk27C6tORknV0sDicbkvp+NQCez0bU4oaHiooz5uIt/YL1ofbdb03AFJcfR0a2JkCi0CQQCYHX8Lp9P1o9y+SXNlrSs5CExx/Ev1/AFVov/+OThZxVU5/93WjlHvC0TX/A6Ey5Oep6934fhS3Q/3URfRJcxfAkA2J/qv00RXDRmeofP1V9oz2Z84UTuqkde69JGPU5JSzYl9UHZuNqbqNwh8wrMLP8Kv7dJQcvzczzmiW8DxWGmBAkBWx50O/TPC0zS/qg+XVe9unflendyH/LiWLmN0mRg4vocci4f3O0Iq6Xbg8P8nayxQOsGz1spgG5VcNnsr6jBpAkEA5VwKRVtRxr5ibHZEHL6vHyhvnaXQaTNOjZiAdjt5iG67PX93+nvHHhmwOrvGrsQizznbe+HwrEWPIdI0jYQSvw==';

    var encrypt = new JSEncrypt();
    encrypt.setPublicKey(PUBLIC_KEY);

    console.log(encrypt.encrypt('device002'))
	// 加密结果如:QoDEtpouVY+6F309w6NBlnSEXvFMtwPyFMk77I6RvtN8GL1fxWf1ZDt9r2QVgVHJLAZ4PkzfNIxzsbseD8PyNYIogVTC43LjIeVJklVAIjBvIr3IW28GcFAzEqGKR/WuubxFXmqmER/ixVJyYBuEuGMYPklrqAq5ZHC5YF7eN9Q=
	
	// 解密:System.out.println(new String(RSACoder.decryptByPrivateKey(
	// "QoDEtpouVY+6F309w6NBlnSEXvFMtwPyFMk77I6RvtN8GL1fxWf1ZDt9r2QVgVHJLAZ4PkzfNIxzsbseD8PyNYIogVTC43LjIeVJklVAIjBvIr3IW28GcFAzEqGKR/WuubxFXmqmER/ixVJyYBuEuGMYPklrqAq5ZHC5YF7eN9Q=", 
	// "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAItVa2aZdp3BZsoC69dYvMJjcDzjizp4nUjX0lMSYytuZpA/iELr/iSzojH4Ek8X+KSlUOJ7qAGDiqxJusGNyQDwC9+VhTSLHDSsTN362/ajR35p9kQl0hbZIv/7vwVS4Z27sKFh5Rf0MsQzx1Jwh1ZihVER7LR6L4f10hBwvKKzAgMBAAECgYAPXWURlFzDOr+WCUpuned63DJVVJZW5VQa40nbRUzQTkVbJNZm4tVMwM5jCkMim7ccmOpZf19gg1v4ccz5aSRAHpZ4ZwbUI4D1eHUygXeiWkGsY4oPfRiMRB/Rv3Fsd4HlaMt4Cxkg0cxvg4FwknoPGHsUBDBWXntiQhtuO9BtOQJBAOp9TuFi2B+vo6YU4YtLfk27C6tORknV0sDicbkvp+NQCez0bU4oaHiooz5uIt/YL1ofbdb03AFJcfR0a2JkCi0CQQCYHX8Lp9P1o9y+SXNlrSs5CExx/Ev1/AFVov/+OThZxVU5/93WjlHvC0TX/A6Ey5Oep6934fhS3Q/3URfRJcxfAkA2J/qv00RXDRmeofP1V9oz2Z84UTuqkde69JGPU5JSzYl9UHZuNqbqNwh8wrMLP8Kv7dJQcvzczzmiW8DxWGmBAkBWx50O/TPC0zS/qg+XVe9unflendyH/LiWLmN0mRg4vocci4f3O0Iq6Xbg8P8nayxQOsGz1spgG5VcNnsr6jBpAkEA5VwKRVtRxr5ibHZEHL6vHyhvnaXQaTNOjZiAdjt5iG67PX93+nvHHhmwOrvGrsQizznbe+HwrEWPIdI0jYQSvw=="))
	// );


</script>

</html>

DES

示例一

js

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!-- vue项目中引入var CryptoJS = require("crypto-js"); -->
    <script src="https://cdn.bootcdn.net/ajax/libs/crypto-js/4.1.1/core.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/crypto-js/4.1.1/cipher-core.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/crypto-js/4.1.1/mode-ecb.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/crypto-js/4.1.1/tripledes.min.js"></script>
</head>
<body>



</body>
<script>
    //加密的私钥
    var key = '1qaz@WSX';//自定义

    // DES加密
    function encryptByDES(message) {//传入加密的内容
        //把私钥转换成16进制的字符串
        var keyHex = CryptoJS.enc.Utf8.parse(key);
        //模式为ECB padding为Pkcs7
        var encrypted = CryptoJS.DES.encrypt(message, keyHex, {
            mode: CryptoJS.mode.ECB,
            padding: CryptoJS.pad.Pkcs7
        });
        //加密出来是一个16进制的字符串
        return encrypted.ciphertext.toString();
    }

    console.log(encryptByDES("device001")) // 2c9a133b2f5deb4adde2ca280a464ee8
    // 解密:System.out.println(DESUtils.decryption("2c9a133b2f5deb4adde2ca280a464ee8", "1qaz@WSX"));
</script>
</html>

java

package com.zzhua.des;

import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.Locale;

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


public class DESUtils {

    /**
     * DES解密
     *
     * @param secretData 密码字符串
     * @param secretKey  解密密钥
     * @return 原始字符串
     * @throws Exception
     */
    private static final String DES_ALGORITHM = "DES";

    public static String decryption(String secretData, String secretKey) throws Exception {
        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance("DES/ECB/NoPadding");
            cipher.init(Cipher.DECRYPT_MODE, generateKey(secretKey));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            throw new Exception("NoSuchAlgorithmException", e);
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
            throw new Exception("NoSuchPaddingException", e);
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {

            byte[] buf = cipher.doFinal(hexStr2Bytes(secretData));
            int num = 0;
            for (byte b: buf) {
                String name = b+"";
                if (name.length() == 1) {
                    num++;
                }
            }

            byte[] bytes = new byte[buf.length-num];
            for (int i =0; i < buf.length; i++) {
                String name = buf[i]+"";
                if (name.length() != 1) {
                    bytes[i] = buf[i];
                }
            }

            return new String(bytes, "utf-8");

        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("IllegalBlockSizeException", e);
        }
    }

    public static byte[] hexStr2Bytes(String src) {
        /*对输入值进行规范化整理*/
        src = src.trim().replace(" ", "").toUpperCase(Locale.US);
        //处理值初始化
        int m = 0, n = 0;
        int iLen = src.length() / 2; //计算长度
        byte[] ret = new byte[iLen]; //分配存储空间

        for (int i = 0; i < iLen; i++) {
            m = i * 2 + 1;
            n = m + 1;
            ret[i] = (byte) (Integer.decode("0X" + src.substring(i * 2, m) + src.substring(m, n)) & 0xFF);
        }
        return ret;
    }

    /**
     * 获得秘密密钥
     *
     * @param secretKey
     * @return
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException
     */
    private static SecretKey generateKey(String secretKey)
            throws Exception {
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES_ALGORITHM);
        DESKeySpec keySpec = new DESKeySpec(secretKey.getBytes());
        keyFactory.generateSecret(keySpec);
        return keyFactory.generateSecret(keySpec);
    }
}

示例2

参照:https://www.jianshu.com/p/24691c8d722c

js

var CryptoJS = require("crypto-js");

    const secretKey = "q9rx*a.SjzH"; 

    var afterEncrypt = CryptoJS.DES.encrypt(
      "device_001",
      CryptoJS.enc.Utf8.parse(secretKey),
      {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7,
      }
    ).toString();

    console.log(afterEncrypt); // 1XyZG40XBRbt/9HGiyAPaUcVfFa7SJ+c

    var afterDecrypt = CryptoJS.DES.decrypt(
      afterEncrypt,
      CryptoJS.enc.Utf8.parse(secretKey),
      {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7,
      }
    ).toString(CryptoJS.enc.Utf8);

    console.log(afterDecrypt); //device_001
  },

java

package com.zzhua.des2;


import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.*;
import javax.crypto.spec.DESKeySpec;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;
import java.security.spec.InvalidKeySpecException;
import java.util.Base64;

public class DesCipherUtil {

    private DesCipherUtil() {
        throw new AssertionError("No DesCipherUtil instances for you!");
    }

    static {
        // add BC provider
        Security.addProvider(new BouncyCastleProvider());
    }

    /**
     * 加密
     *
     * @param encryptText 需要加密的信息
     * @param key 加密密钥
     * @return 加密后Base64编码的字符串
     */
    public static String encrypt(String encryptText, String key) {

        if (encryptText == null || key == null) {
            throw new IllegalArgumentException("encryptText or key must not be null");
        }

        try {
            DESKeySpec desKeySpec = new DESKeySpec(key.getBytes());
            SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey secretKey = secretKeyFactory.generateSecret(desKeySpec);

            Cipher cipher = Cipher.getInstance("DES/ECB/PKCS7Padding", "BC");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            byte[] bytes = cipher.doFinal(encryptText.getBytes(Charset.forName("UTF-8")));
            return Base64.getEncoder().encodeToString(bytes);

        } catch (NoSuchAlgorithmException | InvalidKeyException | InvalidKeySpecException | NoSuchPaddingException
            | BadPaddingException | NoSuchProviderException | IllegalBlockSizeException e) {
            throw new RuntimeException("encrypt failed", e);
        }

    }

    /**
     * 解密
     *
     * @param decryptText 需要解密的信息
     * @param key 解密密钥,经过Base64编码
     * @return 解密后的字符串
     */
    public static  String decrypt(String decryptText, String key) {

        if (decryptText == null || key == null) {
            throw new IllegalArgumentException("decryptText or key must not be null");
        }

        try {
            DESKeySpec desKeySpec = new DESKeySpec(key.getBytes());
            SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey secretKey = secretKeyFactory.generateSecret(desKeySpec);

            Cipher cipher = Cipher.getInstance("DES/ECB/PKCS7Padding", "BC");
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            byte[] bytes = cipher.doFinal(Base64.getDecoder().decode(decryptText));
            return new String(bytes, Charset.forName("UTF-8"));

        } catch (NoSuchAlgorithmException | InvalidKeyException | InvalidKeySpecException | NoSuchPaddingException
            | BadPaddingException | NoSuchProviderException | IllegalBlockSizeException e) {
            throw new RuntimeException("decrypt failed", e);
        }
    }

    public static void main(String[] args) {
        String fromWeb = "7aokwkzN+gxMdyOFAUEBVg==";
        String key = "q9rx*a.SjzH";
        String afterDecrypt = DesCipherUtil.decrypt(fromWeb, key);
        System.out.println(afterDecrypt);//q9rx*a.SjzH

        System.out.println(DesCipherUtil.encrypt("device_001", key));

    }
}



  移动开发 最新文章
Vue3装载axios和element-ui
android adb cmd
【xcode】Xcode常用快捷键与技巧
Android开发中的线程池使用
Java 和 Android 的 Base64
Android 测试文字编码格式
微信小程序支付
安卓权限记录
知乎之自动养号
【Android Jetpack】DataStore
上一篇文章      下一篇文章      查看所有文章
加:2022-03-17 22:19:09  更:2022-03-17 22:21:53 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/24 18:44:50-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码