瀏覽代碼

加密、解密

dsj 4 年之前
父節點
當前提交
d29071cc34

+ 1 - 1
README.md

@@ -5,4 +5,4 @@
 ### 目录清单
 
 > 1. UtilsDemo-Excel  Excel公用操作代码演示 ,包含导入、导出功能。
-> 2. UtilsDemo-Redis Redis 公用操作代码演示.
+> 2. UtilsDemo-Redis SecureEncryption 安全加密 .

UtilsDemo-Redis/.gitignore → UtilsDemo-SecureEncryption/.gitignore


+ 6 - 1
UtilsDemo-Redis/pom.xml

@@ -5,13 +5,18 @@
   <modelVersion>4.0.0</modelVersion>
 
   <groupId>org.example</groupId>
-  <artifactId>UtilsDemo-Redis</artifactId>
+  <artifactId>UtilsDemo-SecureEncryption</artifactId>
   <version>1.0-SNAPSHOT</version>
   <dependencies>
     <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-autoconfigure</artifactId>
     </dependency>
+    <dependency>
+      <groupId>commons-codec</groupId>
+      <artifactId>commons-codec</artifactId>
+      <version>1.13</version>
+    </dependency>
   </dependencies>
 
   <parent>

+ 2 - 2
UtilsDemo-Redis/src/main/java/com/example/RedisApplication.java

@@ -4,8 +4,8 @@ import org.springframework.boot.SpringApplication;
 import org.springframework.boot.autoconfigure.SpringBootApplication;
 
 @SpringBootApplication
-public class RedisApplication {
+public class SecureEncryptionApplication {
     public static void main(String[] args) {
-        SpringApplication.run(RedisApplication.class, args);
+        SpringApplication.run(SecureEncryptionApplication.class, args);
     }
 }

+ 125 - 0
UtilsDemo-SecureEncryption/src/main/java/com/example/utils/Des3Util.java

@@ -0,0 +1,125 @@
+package com.example.utils;
+
+/**
+ * @category Des3
+ *
+ * @author DSJ
+ * @version 1.0
+ * @since 1.0
+ */
+import javax.crypto.Cipher;
+import javax.crypto.SecretKeyFactory;
+import javax.crypto.spec.DESedeKeySpec;
+import javax.crypto.spec.IvParameterSpec;
+import java.security.Key;
+
+public class Des3Util {
+    private final static byte[] SKEYIV = { 'c', '@', 0, '%', 'I', '$', '&', 'm' };
+    /**
+     * ECB加密,不要IV
+     * @param key 密钥
+     * @param data 明文
+     * @return Base64编码的密文
+     * @throws Exception
+     */
+    public static byte[] des3EncodeECB(byte[] key, byte[] data)
+            throws Exception {
+        Key deskey = null;
+        DESedeKeySpec spec = new DESedeKeySpec(key);
+        SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
+        deskey = keyfactory.generateSecret(spec);
+        Cipher cipher = Cipher.getInstance("desede" + "/ECB/PKCS5Padding");
+        cipher.init(Cipher.ENCRYPT_MODE, deskey);
+        byte[] bOut = cipher.doFinal(data);
+        return bOut;
+    }
+
+    /**
+     * ECB解密,不要IV
+     * @param key 密钥
+     * @param data Base64编码的密文
+     * @return 明文
+     * @throws Exception
+     */
+    public static byte[] ees3DecodeECB(byte[] key, byte[] data)
+            throws Exception {
+        Key deskey = null;
+        DESedeKeySpec spec = new DESedeKeySpec(key);
+        SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
+        deskey = keyfactory.generateSecret(spec);
+        Cipher cipher = Cipher.getInstance("desede" + "/ECB/PKCS5Padding");
+        cipher.init(Cipher.DECRYPT_MODE, deskey);
+        byte[] bOut = cipher.doFinal(data);
+        return bOut;
+    }
+    /**
+     * CBC加密
+     * @param key 密钥
+     * @param keyiv IV
+     * @param data 明文
+     * @return Base64编码的密文
+     * @throws Exception
+     */
+    public static byte[] des3EncodeCBC(byte[] key, byte[] keyiv, byte[] data)
+            throws Exception {
+        Key deskey = null;
+        DESedeKeySpec spec = new DESedeKeySpec(key);
+        SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
+        deskey = keyfactory.generateSecret(spec);
+        Cipher cipher = Cipher.getInstance("desede" + "/CBC/PKCS5Padding");
+        IvParameterSpec ips = new IvParameterSpec(keyiv);
+        cipher.init(Cipher.ENCRYPT_MODE, deskey, ips);
+        byte[] bOut = cipher.doFinal(data);
+        return bOut;
+    }
+    /**
+     * CBC解密
+     * @param key 密钥
+     * @param keyiv IV
+     * @param data Base64编码的密文
+     * @return 明文
+     * @throws Exception
+     */
+    public static byte[] des3DecodeCBC(byte[] key, byte[] keyiv, byte[] data)
+            throws Exception {
+        Key deskey = null;
+        DESedeKeySpec spec = new DESedeKeySpec(key);
+        SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
+        deskey = keyfactory.generateSecret(spec);
+        Cipher cipher = Cipher.getInstance("desede" + "/CBC/PKCS5Padding");
+        IvParameterSpec ips = new IvParameterSpec(keyiv);
+        cipher.init(Cipher.DECRYPT_MODE, deskey, ips);
+        byte[] bOut = cipher.doFinal(data);
+        return bOut;
+    }
+
+
+
+    /**
+     *  CBC 加密
+     * @param key
+     * @param data
+     * @return
+     * @throws Exception
+     *
+     */
+    public static String des3EncodeCBCString(String key, String data) throws Exception{
+        byte[] bBuf =  des3EncodeCBC(key.getBytes("UTF-8"), SKEYIV, data.getBytes("UTF-8") );
+        return Hex.parseByte2HexStr(bBuf);
+    }
+
+
+    /**
+     *  CBC 解密
+     * @param key
+     * @param data
+     * @return
+     * @throws Exception
+     *
+     */
+    public static String des3DecodeCBCString(String key, String data) throws Exception{
+        byte[] bdata = Hex.parseHexStr2Byte(data);
+        byte[] bBuf =  des3DecodeCBC(key.getBytes("UTF-8"), SKEYIV, bdata );
+        return new String(bBuf, "UTF-8"); //Hex.encodeHexStr(bBuf);
+    }
+}

+ 130 - 0
UtilsDemo-SecureEncryption/src/main/java/com/example/utils/DesUtil.java

@@ -0,0 +1,130 @@
+package com.example.utils;
+
+import javax.crypto.Cipher;
+import javax.crypto.SecretKey;
+import javax.crypto.SecretKeyFactory;
+import javax.crypto.spec.DESKeySpec;
+import javax.crypto.spec.IvParameterSpec;
+import java.io.IOException;
+
+public class DesUtil {
+    public static final String IV = "@#c,m.t/"; //八位
+
+    /**
+     * Description 根据键值进行加密
+     * @param data
+     * @param key  加密键byte数组
+     * @return
+     * @throws Exception
+     */
+    public static String encrypt(String data, String key, String iv) throws Exception {
+        byte[] bt = encrypt(data.getBytes("utf-8"), key.getBytes("UTF-8"), iv.getBytes("UTF-8"));
+        //String strs = new BASE64Encoder().encode(bt);
+        String strs = parseByte2HexStr(bt) ;
+        return strs;
+    }
+
+    /**
+     * Description 根据键值进行解密
+     * @param data
+     * @param key  加密键byte数组
+     * @return
+     * @throws IOException
+     * @throws Exception
+     */
+    public static String decrypt(String data, String key, String iv) throws IOException,
+            Exception {
+        if (data == null)
+            return null;
+        byte[] buf = parseHexStr2Byte(data) ;
+        byte[] bt = decrypt(buf,key.getBytes("UTF-8"), iv.getBytes("UTF-8"));
+        return new String(bt,"UTF-8");
+    }
+
+    /**
+     * Description 根据键值进行加密
+     * @param data
+     * @param key  加密键byte数组
+     * @return
+     * @throws Exception
+     */
+    private static byte[] encrypt(byte[] data, byte[] key, byte[] iv) throws Exception {
+        DESKeySpec dks = new DESKeySpec(key);
+
+        // 一个SecretKey对象
+        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
+        SecretKey secretKey = keyFactory.generateSecret(dks);
+        // Cipher对象实际完成加密操作
+        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
+        // 用密匙初始化Cipher对象
+        IvParameterSpec param = new IvParameterSpec(iv);
+        cipher.init(Cipher.ENCRYPT_MODE, secretKey, param);
+
+        // 执行加密操作
+        byte encryptedData[] = cipher.doFinal(data);
+
+        return encryptedData;
+    }
+
+
+    /**
+     * Description 根据键值进行解密
+     * @param data
+     * @param key  加密键byte数组
+     * @return
+     * @throws Exception
+     */
+    private static byte[] decrypt(byte[] data, byte[] key, byte[] iv) throws Exception {
+        DESKeySpec dks = new DESKeySpec(key);
+
+        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
+        SecretKey secretKey = keyFactory.generateSecret(dks);
+
+        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
+        // 用密匙初始化Cipher对象
+        IvParameterSpec param = new IvParameterSpec(iv);
+        cipher.init(Cipher.DECRYPT_MODE, secretKey, param);
+
+        // 正式执行解密操作
+        byte decryptedData[] = cipher.doFinal(data);
+
+        return decryptedData;
+    }
+
+
+    /**
+     *
+     * 将16进制转换为二进制
+     * @param hexStr
+     * @return
+     */
+    public static byte[] parseHexStr2Byte(String hexStr) {
+        if (hexStr.length() < 1)
+            return null;
+        byte[] result = new byte[hexStr.length()/2];
+        for (int i = 0;i< hexStr.length()/2; i++) {
+            int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);
+            int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);
+            result[i] = (byte) (high * 16 + low);
+        }
+        return result;
+    }
+
+    /**
+     *
+     * 将二进制转换成16进制
+     * @param buf
+     * @return
+     */
+    public static String parseByte2HexStr(byte buf[]) {
+        StringBuffer sb = new StringBuffer();
+        for (int i = 0; i < buf.length; i++) {
+            String hex = Integer.toHexString(buf[i] & 0xFF);
+            if (hex.length() == 1) {
+                hex = '0' + hex;
+            }
+            sb.append(hex.toUpperCase());
+        }
+        return sb.toString();
+    }
+}

+ 80 - 0
UtilsDemo-SecureEncryption/src/main/java/com/example/utils/Encodes.java

@@ -0,0 +1,80 @@
+package com.example.utils;
+
+import org.apache.tomcat.util.codec.binary.Base64;
+
+import java.io.UnsupportedEncodingException;
+
+public class Encodes {
+    private static final String DEFAULT_URL_ENCODING = "UTF-8";
+    private static final char[] BASE62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray();
+
+    /**
+     * Hex编码.
+     */
+    public static String encodeHex(byte[] input) {
+        return new String(Hex.encodeHex(input));
+    }
+
+    /**
+     * Hex解码.
+     */
+    public static byte[] decodeHex(String input) throws Exception {
+            return Hex.decodeHex(input.toCharArray());
+    }
+
+    /**
+     * Base64编码.
+     */
+    public static String encodeBase64(byte[] input) {
+        return new String(Base64.encodeBase64(input));
+    }
+
+    /**
+     * Base64编码.
+     */
+    public static String encodeBase64(String input) {
+        try {
+            return new String(Base64.encodeBase64(input.getBytes(DEFAULT_URL_ENCODING)));
+        } catch (UnsupportedEncodingException e) {
+            return "";
+        }
+    }
+
+    /**
+     * Base64编码, URL安全(将Base64中的URL非法字符'+'和'/'转为'-'和'_', 见RFC3548).
+     */
+    public static String encodeUrlSafeBase64(byte[] input) {
+        return Base64.encodeBase64URLSafeString(input);
+    }
+
+
+    /**
+     * Base64解码.
+     */
+    public static byte[] decodeBase64(String input) {
+        return Base64.decodeBase64(input.getBytes());
+    }
+
+    /**
+     * Base64解码.
+     */
+    public static String decodeBase64String(String input) {
+        try {
+            return new String(Base64.decodeBase64(input.getBytes()),
+                    DEFAULT_URL_ENCODING);
+        } catch (UnsupportedEncodingException e) {
+            return "";
+        }
+    }
+
+    /**
+     * Base62编码。
+     */
+    public static String encodeBase62(byte[] input) {
+        char[] chars = new char[input.length];
+        for (int i = 0; i < input.length; i++) {
+            chars[i] = BASE62[((input[i] & 0xFF) % BASE62.length)];
+        }
+        return new String(chars);
+    }
+}

+ 203 - 0
UtilsDemo-SecureEncryption/src/main/java/com/example/utils/Hex.java

@@ -0,0 +1,203 @@
+package com.example.utils;
+
+/**
+ * @category 十六进制组件
+ *
+ * @author DSJ
+ * @version 1.0
+ * @since 1.0
+ */
+public class Hex {
+    /**
+     * 用于建立十六进制字符的输出的小写字符数组
+     */
+    private static final char[] DIGITS_LOWER = {'0', '1', '2', '3', '4', '5',
+            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
+
+    /**
+     * 用于建立十六进制字符的输出的大写字符数组
+     */
+    private static final char[] DIGITS_UPPER = {'0', '1', '2', '3', '4', '5',
+            '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
+
+    /**
+     * 将字节数组转换为十六进制字符数组
+     *
+     * @param data byte[]
+     * @return 十六进制char[]
+     */
+    public static char[] encodeHex(byte[] data) {
+        return encodeHex(data, true);
+    }
+
+    /**
+     * 将字节数组转换为十六进制字符数组
+     *
+     * @param data        byte[]
+     * @param toLowerCase <code>true</code> 传换成小写格式 , <code>false</code> 传换成大写格式
+     * @return 十六进制char[]
+     */
+    public static char[] encodeHex(byte[] data, boolean toLowerCase) {
+        return encodeHex(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER);
+    }
+
+    /**
+     * 将字节数组转换为十六进制字符数组
+     *
+     * @param data     byte[]
+     * @param toDigits 用于控制输出的char[]
+     * @return 十六进制char[]
+     */
+    protected static char[] encodeHex(byte[] data, char[] toDigits) {
+        int l = data.length;
+        char[] out = new char[l << 1];
+        // two characters form the hex value.
+        for (int i = 0, j = 0; i < l; i++) {
+            out[j++] = toDigits[(0xF0 & data[i]) >>> 4];
+            out[j++] = toDigits[0x0F & data[i]];
+        }
+        return out;
+    }
+
+    /**
+     * 将字节数组转换为十六进制字符串
+     *
+     * @param data byte[]
+     * @return 十六进制String
+     */
+    public static String encodeHexStr(byte[] data) {
+        return encodeHexStr(data, true);
+    }
+
+    public static String encodeHexString(byte[] data){
+        return encodeHexStr(data);
+    }
+
+    /**
+     * 将字节数组转换为十六进制字符串
+     *
+     * @param data        byte[]
+     * @param toLowerCase <code>true</code> 传换成小写格式 , <code>false</code> 传换成大写格式
+     * @return 十六进制String
+     */
+    public static String encodeHexStr(byte[] data, boolean toLowerCase) {
+        return encodeHexStr(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER);
+    }
+
+    /**
+     * 将字节数组转换为十六进制字符串
+     *
+     * @param data     byte[]
+     * @param toDigits 用于控制输出的char[]
+     * @return 十六进制String
+     */
+    protected static String encodeHexStr(byte[] data, char[] toDigits) {
+        return new String(encodeHex(data, toDigits));
+    }
+
+    /**
+     * 将十六进制字符数组转换为字节数组
+     *
+     * @param data 十六进制char[]
+     * @return byte[]
+     * @throws RuntimeException 如果源十六进制字符数组是一个奇怪的长度,将抛出运行时异常
+     */
+    public static byte[] decodeHex(char[] data) {
+
+        int len = data.length;
+
+        if ((len & 0x01) != 0) {
+            throw new RuntimeException("Odd number of characters.");
+        }
+
+        byte[] out = new byte[len >> 1];
+
+        // two characters form the hex value.
+        for (int i = 0, j = 0; j < len; i++) {
+            int f = toDigit(data[j], j) << 4;
+            j++;
+            f = f | toDigit(data[j], j);
+            j++;
+            out[i] = (byte) (f & 0xFF);
+        }
+
+        return out;
+    }
+
+
+    /**将二进制转换成16进制
+     * @param buf
+     * @return
+     */
+    public static String parseByte2HexStr(byte buf[]) {
+        StringBuffer sb = new StringBuffer();
+        for (int i = 0; i < buf.length; i++) {
+            String hex = Integer.toHexString(buf[i] & 0xFF);
+            if (hex.length() == 1) {
+                hex = '0' + hex;
+            }
+            sb.append(hex.toUpperCase());
+        }
+        return sb.toString();
+    }
+
+    /**将16进制转换为二进制
+     * @param hexStr
+     * @return
+     */
+    public static byte[] parseHexStr2Byte(String hexStr) {
+        if (hexStr.length() < 1)
+            return null;
+        byte[] result = new byte[hexStr.length()/2];
+        for (int i = 0;i< hexStr.length()/2; i++) {
+            int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);
+            int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);
+            result[i] = (byte) (high * 16 + low);
+        }
+        return result;
+    }
+
+    /**
+     * 将十六进制字符转换成一个整数
+     *
+     * @param ch    十六进制char
+     * @param index 十六进制字符在字符数组中的位置
+     * @return 一个整数
+     * @throws RuntimeException 当ch不是一个合法的十六进制字符时,抛出运行时异常
+     */
+    protected static int toDigit(char ch, int index) {
+        int digit = Character.digit(ch, 16);
+        if (digit == -1) {
+            throw new RuntimeException("Illegal hexadecimal character " + ch
+                    + " at index " + index);
+        }
+        return digit;
+    }
+
+//    public static void main(String[] args) {
+//        String srcStr = "qwer";
+//        String encodeStr = encodeHexStr(srcStr.getBytes());
+//        String decodeStr = new String(decodeHex(encodeStr.toCharArray()));
+//        System.out.println("before encode:" + srcStr);
+//        System.out.println("after encode:" + encodeStr);
+//        System.out.println("convert:" + decodeStr);
+//
+//        test();
+//    }
+
+    public static void  test() {
+        String hello = "asdfasdf你还要asdfasdfasdfasdfl";
+        try {
+            String hexString = Hex.encodeHexString(hello.getBytes("utf-8"));
+            String hexString2 = Hex.encodeHexString(hello.getBytes("ascii"));
+            String hexString3 = Hex.encodeHexString(hello.getBytes("gbk"));
+            String hexString4 = new String(Hex.encodeHex(hello.getBytes("utf-8"), false));
+            System.out.println(hexString);
+            System.out.println(hexString2);
+            System.out.println(hexString3);
+            System.out.println(hexString4);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+}

UtilsDemo-Redis/src/main/resources/application.yml → UtilsDemo-SecureEncryption/src/main/resources/application.yml


+ 1 - 1
pom.xml

@@ -19,7 +19,7 @@
 
   <modules>
     <module>UtilsDemo-Excel</module>
-    <module>UtilsDemo-Redis</module>
+    <module>UtilsDemo-SecureEncryption</module>
   </modules>
   <packaging>pom</packaging>