提交 fc18a7a1 编写于 作者: B blankj

see 08/14 log

上级 4cf74936
### 更新Log
#### 16/08/14 新增DES加密及单元检测
#### 16/08/13 新增MD2,SHA224,SHA256,SHA384,SHA512加密及单元测试,正折腾DES加密
#### 16/08/12 新增Base64和Html编码解码及他们的单元测试,新增TimeUtils单元测试,更新md
#### 16/08/11 新增SDCardUtils,UnitUtils,单元测试慢慢完善中
......
......@@ -8,12 +8,13 @@ package com.blankj.utilcode.utils;
* desc : 单位相关工具类
* </pre>
*/
public class UnitUtils {
public class ConstUtils {
private UnitUtils() {
private ConstUtils() {
throw new UnsupportedOperationException("u can't fuck me...");
}
/******************** 存储相关常量 ********************/
/**
* Byte与Byte的倍数
*/
......@@ -31,8 +32,7 @@ public class UnitUtils {
*/
public static final long GB = 1073741824;
/******************** 时间相关常量 ********************/
/**
* 毫秒与毫秒的倍数
*/
......@@ -53,4 +53,54 @@ public class UnitUtils {
* 天与毫秒的倍数
*/
public static final int DAY = 86400000;
/******************** DES加密相关常量 ********************/
/**
* DES加密为ECB、无填充
*/
public static final String DES_ECB_NO_PADDING = "DES/ECB/NoPadding";
/**
* DES加密为CBC、无填充
*/
public static final String DES_CBC_NO_PADDING = "DES/CBC/NoPadding";
/**
* DES加密为CFB、无填充
*/
public static final String DES_CFB_NO_PADDING = "DES/CFB/NoPadding";
/**
* DES加密为OFB、无填充
*/
public static final String DES_OFB_NO_PADDING = "DES/OFB/NoPadding";
/**
* DES加密为ECB、零填充
*/
public static final String DES_ECB_ZEROS_PADDING = "DES/ECB/ZerosPadding";
/**
* DES加密为CBC、零填充
*/
public static final String DES_CBC_ZEROS_PADDING = "DES/CBC/ZerosPadding";
/**
* DES加密为CFB、零填充
*/
public static final String DES_CFB_ZEROS_PADDING = "DES/CFB/ZerosPadding";
/**
* DES加密为OFB、零填充
*/
public static final String DES_OFB_ZEROS_PADDING = "DES/OFB/ZerosPadding";
/**
* DES加密为ECB、PKCS5Padding填充
*/
public static final String DES_ECB_PKCS5_PADDING = "DES/ECB/PKCS5Padding";
/**
* DES加密为CBC、PKCS5Padding填充
*/
public static final String DES_CBC_PKCS5_PADDING = "DES/CBC/PKCS5Padding";
/**
* DES加密为CFB、PKCS5Padding填充
*/
public static final String DES_CFB_PKCS5_PADDING = "DES/CFB/PKCS5Padding";
/**
* DES加密为OFB、PKCS5Padding填充
*/
public static final String DES_OFB_PKCS5_PADDING = "DES/OFB/PKCS5Padding";
}
......@@ -43,7 +43,7 @@ public class ConvertUtils {
throw new IllegalArgumentException("长度不是偶数");
}
char[] hexBytes = hexString.toUpperCase().toCharArray();
byte[] res = new byte[len / 2];
byte[] res = new byte[len >>> 1];
for (int i = 0; i < len; i += 2) {
res[i >> 1] = (byte) (hex2Dec(hexBytes[i]) << 4 | hex2Dec(hexBytes[i + 1]));
}
......@@ -59,10 +59,34 @@ public class ConvertUtils {
private static int hex2Dec(char hexChar) {
if (hexChar >= '0' && hexChar <= '9') {
return hexChar - '0';
} else if (hexChar >= 'A' && hexChar <= 'E') {
} else if (hexChar >= 'A' && hexChar <= 'F') {
return hexChar - 'A' + 10;
} else {
throw new IllegalArgumentException();
}
}
/**
* char转byte
*/
public static byte[] getBytes(char[] chars) {
int len = chars.length;
byte[] bytes = new byte[len];
for (int i = 0; i < len; i++) {
bytes[i] = (byte) (chars[i]);
}
return bytes;
}
/**
* byte转char
*/
public static char[] getChars(byte[] bytes) {
int len = bytes.length;
char[] chars = new char[len];
for (int i = 0; i < len; i++) {
chars[i] = (char) (bytes[i] & 0xff);
}
return chars;
}
}
......@@ -82,7 +82,7 @@ public class EncodeUtils {
* @param input 要编码的字符串
* @return Base64编码后的字符串
*/
public static String base64Encode(String input) {
public static byte[] base64Encode(String input) {
return base64Encode(input.getBytes());
}
......@@ -92,8 +92,28 @@ public class EncodeUtils {
* @param input 要编码的字节数组
* @return Base64编码后的字符串
*/
public static String base64Encode(byte[] input) {
return Base64.encodeToString(input, Base64.DEFAULT);
public static byte[] base64Encode(byte[] input) {
return Base64.encode(input, Base64.NO_WRAP);
}
/**
* Base64编码
*
* @param input 要编码的字节数组
* @return Base64编码后的字符串
*/
public static String base64Encode2String(byte[] input) {
return Base64.encodeToString(input, Base64.NO_WRAP);
}
/**
* Base64解码
*
* @param input 要解码的字符串
* @return Base64解码后的字符串
*/
public static byte[] base64Decode(String input) {
return Base64.decode(input, Base64.NO_WRAP);
}
/**
......@@ -102,8 +122,8 @@ public class EncodeUtils {
* @param input 要解码的字符串
* @return Base64解码后的字符串
*/
public static String base64Decode(String input) {
return new String(Base64.decode(input, Base64.DEFAULT));
public static byte[] base64Decode(byte[] input) {
return Base64.decode(input, Base64.NO_WRAP);
}
/**
......@@ -114,7 +134,7 @@ public class EncodeUtils {
* @return Base64URL安全编码后的字符串
*/
public static String base64UrlSafeEncode(String input) {
return Base64.encodeToString(input.getBytes(), Base64.URL_SAFE);
return new String(Base64.encode(input.getBytes(), Base64.URL_SAFE));
}
/**
......
package com.blankj.utilcode.utils;
import android.os.Build;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
......@@ -12,13 +10,12 @@ import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.SecretKeySpec;
import static com.blankj.utilcode.utils.ConvertUtils.bytes2HexString;
import static com.blankj.utilcode.utils.ConvertUtils.hexString2Bytes;
/**
* <pre>
......@@ -34,6 +31,7 @@ public class EncryptUtils {
throw new UnsupportedOperationException("u can't fuck me...");
}
/*********************** 哈希加密相关 ***********************/
/**
* MD2加密
*
......@@ -325,117 +323,150 @@ public class EncryptUtils {
return "";
}
private static byte[] iv = {1,2,3,4,5,6,7,8};
public static String encryptDES(String encryptString, String encryptKey) throws Exception {
IvParameterSpec zeroIv = new IvParameterSpec(iv);
SecretKeySpec key = new SecretKeySpec(encryptKey.getBytes(), "DES");
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
byte[] encryptedData = cipher.doFinal(encryptString.getBytes());
return new String(encryptedData);
}
public static String decryptDES(String decryptString, String decryptKey) throws Exception {
byte[] byteMi = decryptString.getBytes();
IvParameterSpec zeroIv = new IvParameterSpec(iv);
SecretKeySpec key = new SecretKeySpec(decryptKey.getBytes(), "DES");
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key, zeroIv);
byte decryptedData[] = cipher.doFinal(byteMi);
return new String(decryptedData);
}
/*********************** DES加密相关 ***********************/
/**
* 加密
* 生成密钥key对象
*
* @param key
* 密钥
* @param src
* 加密文本
* @return
* @param key 秘钥字节数组
* @return 秘钥对象
* @throws Exception
*/
public static String encrypt(String key, String src) throws Exception {
byte[] rawKey = getRawKey(key.getBytes());
byte[] result = encrypt(rawKey, src.getBytes());
return bytes2HexString(result);
private static SecretKey keyGenerator(byte[] key) throws Exception {
DESKeySpec desKey = new DESKeySpec(key);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
return keyFactory.generateSecret(desKey);
}
/**
* 解密
* DES加密后再经Base64编码
*
* @param key
* 密钥
* @param encrypted
* 待揭秘文本
* @return
* @throws Exception
* @param data 明文
* @param key 秘钥
* @param transformation 算法名称/加密模式/填充方式,详见ConstUtils之DES加密相关常量
* @return 经Base64编码后的密文
*/
public static String decrypt(String key, String encrypted) throws Exception {
byte[] rawKey = getRawKey(key.getBytes());
byte[] enc = hexString2Bytes(encrypted);
byte[] result = decrypt(rawKey, enc);
return new String(result);
public static byte[] encryptDESWithBase64(byte[] data, byte[] key, String transformation) {
return EncodeUtils.base64Encode(encryptDES(data, key, transformation));
}
/**
* 获取256位的加密密钥
* DES加密
*
* @param seed
* @return
* @throws Exception
* @param data 明文
* @param key 秘钥
* @param transformation 算法名称/加密模式/填充方式,详见ConstUtils之DES加密相关常量
* @return 密文
*/
private static byte[] getRawKey(byte[] seed) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom sr = null;
// 在4.2以上版本中,SecureRandom获取方式发生了改变
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN) {
sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
} else {
sr = SecureRandom.getInstance("SHA1PRNG");
public static byte[] encryptDES(byte[] data, byte[] key, String transformation) {
try {
SecretKey secretKey = keyGenerator(key);
Cipher cipher = Cipher.getInstance(transformation);
SecureRandom random = new SecureRandom();
cipher.init(Cipher.ENCRYPT_MODE, secretKey, random);
return cipher.doFinal(data);
} catch (Throwable e) {
e.printStackTrace();
}
sr.setSeed(seed);
// 256 bits or 128 bits,192bits
kgen.init(256, sr);
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
return raw;
return null;
}
/**
* 真正的加密过程
* DES解密带有Base64编码后的DES密文
*
* @param key
* @param src
* @return
* @throws Exception
* @param data 带有Base64编码后的DES密文
* @param key 秘钥
* @param transformation 算法名称/加密模式/填充方式,详见ConstUtils之DES加密相关常量
* @return 明文
*/
private static byte[] encrypt(byte[] key, byte[] src) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(src);
return encrypted;
public static byte[] decryptDESWithBase64(byte[] data, byte[] key, String transformation) {
return decryptDES(EncodeUtils.base64Decode(data), key, transformation);
}
/**
* 真正的解密过程
* DES解密
*
* @param key
* @param encrypted
* @return
* @throws Exception
* @param data 密文
* @param key 秘钥
* @param transformation 算法名称/加密模式/填充方式,详见ConstUtils之DES加密相关常量
* @return 明文
*/
private static byte[] decrypt(byte[] key, byte[] encrypted)
throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
public static byte[] decryptDES(byte[] data, byte[] key, String transformation) {
try {
SecretKey secretKey = keyGenerator(key);
Cipher cipher = Cipher.getInstance(transformation);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return cipher.doFinal(data);
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
/*********************** AES加密相关 ***********************/
public static byte[] decrypt(byte[] sSrc, String sKey) throws Exception {
try {
// 判断Key是否正确
if (sKey == null) {
System.out.print("Key为空null");
return null;
}
// 判断Key是否为16位
if (sKey.length() != 16) {
System.out.print("Key长度不是16位");
return null;
}
byte[] raw = sKey.getBytes("ASCII");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] encrypted1 = sSrc;
try {
byte[] original = cipher.doFinal(encrypted1);
return original;
} catch (Exception e) {
System.out.println(e.toString());
return null;
}
} catch (Exception ex) {
System.out.println(ex.toString());
return null;
}
}
// 判断Key是否正确
public static byte[] encrypt(byte[] sSrc, String sKey) throws Exception {
if (sKey == null) {
System.out.print("Key为空null");
return null;
}
// 判断Key是否为16位
if (sKey.length() != 16) {
System.out.print("Key长度不是16位");
return null;
}
byte[] raw = sKey.getBytes("ASCII");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(encrypted);
return decrypted;
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(sSrc);
return encrypted;
}
public static byte[] parseHexStr2Byte(String strhex) {
if (strhex == null) {
return null;
}
int l = strhex.length();
if (l % 2 == 1) {
return null;
}
byte[] b = new byte[l / 2];
for (int i = 0; i != l / 2; i++) {
b[i] = (byte) Integer.parseInt(strhex.substring(i * 2, i * 2 + 2),
16);
}
return b;
}
}
......@@ -5,7 +5,7 @@ import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import static com.blankj.utilcode.utils.UnitUtils.*;
import static com.blankj.utilcode.utils.ConstUtils.*;
/**
* <pre>
......
......@@ -45,13 +45,15 @@ public class EncodeUtilsTest {
}
@Test
public void testBase64Encode() throws Exception {
assertThat(base64Encode("blankj")).isEqualTo("Ymxhbmtq");
}
@Test
public void testBase64Decode() throws Exception {
assertThat(base64Decode("Ymxhbmtq")).isEqualTo("blankj");
public void testBase64EncodeAndDecode() throws Exception {
assertThat(base64Decode(base64Encode("blankj")))
.isEqualTo("blankj".getBytes());
assertThat(base64Decode(base64Encode2String("blankj".getBytes())))
.isEqualTo("blankj".getBytes());
assertThat(base64Encode2String("blankj".getBytes()))
.isEqualTo("Ymxhbmtq");
assertThat(base64Encode("blankj".getBytes()))
.isEqualTo("Ymxhbmtq".getBytes());
}
@Test
......
......@@ -116,31 +116,29 @@ public class EncryptUtilsTest {
String data = "0008DB3345AB0223";
String key = "6801020304050607";
String des = "1F7962581118F360";
byte[] bytesData = hexString2Bytes(data);
byte[] bytesKey = hexString2Bytes(key);
byte[] byteDes = hexString2Bytes(des);
@Test
public void testGetDES() throws Exception {
byte[] bytes = hexString2Bytes(data);
System.out.print((char) (0));
System.out.print((char) (8));
System.out.print((char) (219));
System.out.print((char) (51));
System.out.print((char) (69));
System.out.print((char) (171));
System.out.print((char) (2));
System.out.print((char) (35));
System.out.println();
for (int i = 0; i < bytes.length; i++) {
System.out.print((0xff & bytes[i]) + " ");
}
//00 08 DB 33 45 AB 02 23
//20 08 5F 33 45 5F 02 23
//00 08 219 51 69 171 2 35
System.out.println();
String d = new String(bytes);
String k = new String(hexString2Bytes(key));
System.out.println(d);
System.out.println(k);
assertThat(bytes2HexString(encryptDES(d, k).getBytes())).isEqualTo(new String(hexString2Bytes(des)));
public void testEncryptDESWithBase64() throws Exception {
assertThat(encryptDESWithBase64(bytesData, bytesKey, ConstUtils.DES_ECB_NO_PADDING))
.isEqualTo(EncodeUtils.base64Encode(byteDes));
}
@Test
public void testDecryptDESWithBase64() throws Exception {
assertThat(decryptDESWithBase64(EncodeUtils.base64Encode(byteDes), bytesKey, ConstUtils.DES_ECB_NO_PADDING))
.isEqualTo(bytesData);
}
@Test
public void testEncryptDES() throws Exception {
assertThat(encryptDES(bytesData, bytesKey, ConstUtils.DES_ECB_NO_PADDING)).isEqualTo(byteDes);
}
@Test
public void testDecryptDES() throws Exception {
assertThat(decryptDES(byteDes, bytesKey, ConstUtils.DES_ECB_NO_PADDING)).isEqualTo(bytesData);
}
}
\ No newline at end of file
......@@ -68,9 +68,9 @@ public class TimeUtilsTest {
@Test
public void testGetIntervalTime() throws Exception {
assertThat(getIntervalTime(timeString0, timeString1, UnitUtils.SEC)).isEqualTo(4210);
assertThat(getIntervalTime(myTimeString0, myTimeString1, UnitUtils.SEC, myFormat)).isEqualTo(4210);
assertThat(getIntervalTime(new Date(4210000), new Date(0), UnitUtils.SEC)).isEqualTo(4210);
assertThat(getIntervalTime(timeString0, timeString1, ConstUtils.SEC)).isEqualTo(4210);
assertThat(getIntervalTime(myTimeString0, myTimeString1, ConstUtils.SEC, myFormat)).isEqualTo(4210);
assertThat(getIntervalTime(new Date(4210000), new Date(0), ConstUtils.SEC)).isEqualTo(4210);
}
@Test
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册