更新了加密算法类

This commit is contained in:
ZCShou 2020-09-13 18:00:56 +08:00
parent 457c1bfad0
commit 982e3173dc
4 changed files with 334 additions and 68 deletions

Binary file not shown.

View File

@ -1,56 +1,49 @@
package com.zcshou.utils;
import android.util.Base64;
import org.jetbrains.annotations.NotNull;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Random;
// https://blog.csdn.net/yuzhiqiang_1993/article/details/88657793
// https://www.jianshu.com/p/fe02af0933ef
public class AESUtils {
/* AES秘钥支持128bit/192bit/256bit三种长度的秘钥一个字节等于8bit
* 因此支持生成的字符串的长度应该是 16/24/32
* */
// 16 字节 AES秘钥长度128bit
public static final int KEY_LENGTH_16 = 16;
// 24 字节 AES秘钥长度192bit
public static final int KEY_LENGTH_24 = 24;
// 32 字节 AES秘钥长度256bit
public static final int KEY_LENGTH_32 = 32;
private static String cipherMode = "AES/ECB/PKCS5Padding";//算法/模式/补码方式
/* AES秘钥支持128bit/192bit/256bit三种长度的秘钥一个字节等于8bit
* 因此支持生成的字符串的长度应该是 16/24/32
* */
private static int keyLength = 24;
public static void main(String[] args) {
/*构建一个随机密码*/
String key = getRandomKey(keyLength);
System.out.println("随机生成的key" + key);
String data = "{'fig':1,'message':'登录成功'}";
try {
String encriptData = AESUtils.encrypt(data, key);
System.out.println("加密后的数据:" + encriptData);
String decryptData = decrypt(encriptData, key);
System.out.println("解密后的数据:" + decryptData);
} catch (Exception e) {
e.printStackTrace();
}
}
// public static void main(String[] args) {
//
// /*构建一个随机密码*/
// String key = getRandomKey(24);
// System.out.println("随机生成的key" + key);
//
// String data = "{'fig':1,'message':'登录成功'}";
//
// try {
// String encriptData = AESUtils.encrypt(data, key);
// System.out.println("加密后的数据:" + encriptData);
//
// String decryptData = decrypt(encriptData, key);
//
// System.out.println("解密后的数据:" + decryptData);
//
// } catch (Exception e) {
// e.printStackTrace();
// }
//
// }
/**
@ -60,6 +53,7 @@ public class AESUtils {
public static String getRandomKey(int length) {
if (length != KEY_LENGTH_16 && length != KEY_LENGTH_24 && length != KEY_LENGTH_32) {
System.out.println("长度必须为16/24/32");
return null;
}
@ -71,6 +65,7 @@ public class AESUtils {
stringBuilder.append(str.charAt(number));
}
return stringBuilder.toString();
}
@ -84,6 +79,7 @@ public class AESUtils {
int length = key.length();
if (length != KEY_LENGTH_16 && length != KEY_LENGTH_24 && length != KEY_LENGTH_32) {
System.out.println("长度必须为16/24/32");
return null;
}
@ -93,7 +89,7 @@ public class AESUtils {
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
return Arrays.toString(Base64.encode(encrypted, Base64.DEFAULT));
return Base64.encode(encrypted);
}
@ -101,12 +97,12 @@ public class AESUtils {
* @param data 需要解密的数据
* @param key 解密用的key
* @return 解密后的数据
* @throws Exception 异常
*/
public static String decrypt(String data, @NotNull String key) throws Exception {
public static String decrypt(String data, @NotNull String key) {
try {
int length = key.length();
if (length != KEY_LENGTH_16 && length != KEY_LENGTH_24 && length != KEY_LENGTH_32) {
System.out.println("长度必须为16/24/32");
return null;
}
@ -114,7 +110,7 @@ public class AESUtils {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance(cipherMode);
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] encrypted = Base64.decode(data, Base64.DEFAULT);//先用base64解密
byte[] encrypted = Base64.decode(data);//先用base64解密
try {
byte[] original = cipher.doFinal(encrypted);
return new String(original, StandardCharsets.UTF_8);
@ -128,4 +124,4 @@ public class AESUtils {
}
}
}
}

View File

@ -0,0 +1,268 @@
package com.zcshou.utils;
public final class Base64 {
private static final int BASELENGTH = 128;
private static final int LOOKUPLENGTH = 64;
private static final int TWENTYFOURBITGROUP = 24;
private static final int EIGHTBIT = 8;
private static final int SIXTEENBIT = 16;
private static final int FOURBYTE = 4;
private static final int SIGN = -128;
private static char PAD = '=';
private static byte[] base64Alphabet = new byte[BASELENGTH];
private static char[] lookUpBase64Alphabet = new char[LOOKUPLENGTH];
static {
for (int i = 0; i < BASELENGTH; ++i) {
base64Alphabet[i] = -1;
}
for (int i = 'Z'; i >= 'A'; i--) {
base64Alphabet[i] = (byte) (i - 'A');
}
for (int i = 'z'; i >= 'a'; i--) {
base64Alphabet[i] = (byte) (i - 'a' + 26);
}
for (int i = '9'; i >= '0'; i--) {
base64Alphabet[i] = (byte) (i - '0' + 52);
}
base64Alphabet['+'] = 62;
base64Alphabet['/'] = 63;
for (int i = 0; i <= 25; i++) {
lookUpBase64Alphabet[i] = (char) ('A' + i);
}
for (int i = 26, j = 0; i <= 51; i++, j++) {
lookUpBase64Alphabet[i] = (char) ('a' + j);
}
for (int i = 52, j = 0; i <= 61; i++, j++) {
lookUpBase64Alphabet[i] = (char) ('0' + j);
}
lookUpBase64Alphabet[62] = (char) '+';
lookUpBase64Alphabet[63] = (char) '/';
}
private static boolean isWhiteSpace(char octect) {
return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9);
}
private static boolean isPad(char octect) {
return (octect == PAD);
}
private static boolean isData(char octect) {
return (octect < BASELENGTH && base64Alphabet[octect] != -1);
}
/**
* Encodes hex octects into Base64
*
* @param binaryData
* Array containing binaryData
* @return Encoded Base64 array
*/
public static String encode(byte[] binaryData) {
if (binaryData == null) {
return null;
}
int lengthDataBits = binaryData.length * EIGHTBIT;
if (lengthDataBits == 0) {
return "";
}
int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP;
int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP;
int numberQuartet = fewerThan24bits != 0 ? numberTriplets + 1
: numberTriplets;
char encodedData[] = null;
encodedData = new char[numberQuartet * 4];
byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0;
int encodedIndex = 0;
int dataIndex = 0;
for (int i = 0; i < numberTriplets; i++) {
b1 = binaryData[dataIndex++];
b2 = binaryData[dataIndex++];
b3 = binaryData[dataIndex++];
l = (byte) (b2 & 0x0f);
k = (byte) (b1 & 0x03);
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2)
: (byte) ((b1) >> 2 ^ 0xc0);
byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4)
: (byte) ((b2) >> 4 ^ 0xf0);
byte val3 = ((b3 & SIGN) == 0) ? (byte) (b3 >> 6)
: (byte) ((b3) >> 6 ^ 0xfc);
encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];
encodedData[encodedIndex++] = lookUpBase64Alphabet[(l << 2) | val3];
encodedData[encodedIndex++] = lookUpBase64Alphabet[b3 & 0x3f];
}
// form integral number of 6-bit groups
if (fewerThan24bits == EIGHTBIT) {
b1 = binaryData[dataIndex];
k = (byte) (b1 & 0x03);
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2)
: (byte) ((b1) >> 2 ^ 0xc0);
encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex++] = lookUpBase64Alphabet[k << 4];
encodedData[encodedIndex++] = PAD;
encodedData[encodedIndex++] = PAD;
} else if (fewerThan24bits == SIXTEENBIT) {
b1 = binaryData[dataIndex];
b2 = binaryData[dataIndex + 1];
l = (byte) (b2 & 0x0f);
k = (byte) (b1 & 0x03);
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2)
: (byte) ((b1) >> 2 ^ 0xc0);
byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4)
: (byte) ((b2) >> 4 ^ 0xf0);
encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];
encodedData[encodedIndex++] = lookUpBase64Alphabet[l << 2];
encodedData[encodedIndex++] = PAD;
}
return new String(encodedData);
}
/**
* Decodes Base64 data into octects
*
* @param encoded
* string containing Base64 data
* @return Array containind decoded data.
*/
public static byte[] decode(String encoded) {
if (encoded == null) {
return null;
}
char[] base64Data = encoded.toCharArray();
// remove white spaces
int len = removeWhiteSpace(base64Data);
if (len % FOURBYTE != 0) {
return null;// should be divisible by four
}
int numberQuadruple = (len / FOURBYTE);
if (numberQuadruple == 0) {
return new byte[0];
}
byte decodedData[] = null;
byte b1 = 0, b2 = 0, b3 = 0, b4 = 0;
char d1 = 0, d2 = 0, d3 = 0, d4 = 0;
int i = 0;
int encodedIndex = 0;
int dataIndex = 0;
decodedData = new byte[(numberQuadruple) * 3];
for (; i < numberQuadruple - 1; i++) {
if (!isData((d1 = base64Data[dataIndex++]))
|| !isData((d2 = base64Data[dataIndex++]))
|| !isData((d3 = base64Data[dataIndex++]))
|| !isData((d4 = base64Data[dataIndex++]))) {
return null;
}// if found "no data" just return null
b1 = base64Alphabet[d1];
b2 = base64Alphabet[d2];
b3 = base64Alphabet[d3];
b4 = base64Alphabet[d4];
decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);
}
if (!isData((d1 = base64Data[dataIndex++]))
|| !isData((d2 = base64Data[dataIndex++]))) {
return null;// if found "no data" just return null
}
b1 = base64Alphabet[d1];
b2 = base64Alphabet[d2];
d3 = base64Data[dataIndex++];
d4 = base64Data[dataIndex++];
if (!isData((d3)) || !isData((d4))) {// Check if they are PAD characters
if (isPad(d3) && isPad(d4)) {
if ((b2 & 0xf) != 0)// last 4 bits should be zero
{
return null;
}
byte[] tmp = new byte[i * 3 + 1];
System.arraycopy(decodedData, 0, tmp, 0, i * 3);
tmp[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
return tmp;
} else if (!isPad(d3) && isPad(d4)) {
b3 = base64Alphabet[d3];
if ((b3 & 0x3) != 0)// last 2 bits should be zero
{
return null;
}
byte[] tmp = new byte[i * 3 + 2];
System.arraycopy(decodedData, 0, tmp, 0, i * 3);
tmp[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
tmp[encodedIndex] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
return tmp;
} else {
return null;
}
} else { // No PAD e.g 3cQl
b3 = base64Alphabet[d3];
b4 = base64Alphabet[d4];
decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);
}
return decodedData;
}
/**
* remove WhiteSpace from MIME containing encoded Base64 data.
*
* @param data
* the byte array of base64 data (with WS)
* @return the new length
*/
private static int removeWhiteSpace(char[] data) {
if (data == null) {
return 0;
}
// count characters that's not whitespace
int newSize = 0;
int len = data.length;
for (int i = 0; i < len; i++) {
if (!isWhiteSpace(data[i])) {
data[newSize++] = data[i];
}
}
return newSize;
}
}

View File

@ -1,6 +1,5 @@
package com.zcshou.utils;
import android.util.Base64;
import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
@ -9,12 +8,9 @@ import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
// https://blog.csdn.net/yuzhiqiang_1993/article/details/88657793
// https://www.jianshu.com/p/fe02af0933ef
public class RSAUtils {
public static final int KEY_LENGTH_1024 = 1024;
@ -75,7 +71,7 @@ public class RSAUtils {
// String data = "测试提交数据";
//
// byte[] publicEncryptBytes = RSAUtils.encryptByPublicKey(data.getBytes(), publicKey);
// System.out.println("公钥加密后的数据:" + Arrays.toString(Base64.encode(publicEncryptBytes, Base64.DEFAULT)));
// System.out.println("公钥加密后的数据:" + Base64.encode(publicEncryptBytes));
// byte[] privatDecryptBytes = RSAUtils.decryptByPrivateKey(publicEncryptBytes, privateKey);
// System.out.println("私钥解密后的数据:" + new String(privatDecryptBytes));
//
@ -83,9 +79,9 @@ public class RSAUtils {
// System.out.println("--------------------");
//
// byte[] privateKeyEncryptBytes = RSAUtils.encryptByPrivateKey(data.getBytes(), privateKey);
// System.out.println("私钥加密后的数据:" + Arrays.toString(Base64.encode(privateKeyEncryptBytes, Base64.DEFAULT)));
// System.out.println("私钥加密后的数据:" + Base64.encode(privateKeyEncryptBytes));
//
// String singnData = Arrays.toString(RSAUtils.sign(data.getBytes(), privateKey));
// String singnData = RSAUtils.sign(data.getBytes(), privateKey);
// System.out.println("私钥签名后的数据:" + singnData);
//
//
@ -104,10 +100,13 @@ public class RSAUtils {
/**
* @param keySize 生成的秘钥长度 一般为1024或2048
* @return s
* @throws Exception 异常
* @return
* * @throws Exception 异常
*/
public static Map<String, Object> genKeyPair(int keySize) throws Exception {
if (keySize != KEY_LENGTH_1024 && keySize != KEY_LENGTH_2048) {
return null;
}
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
keyPairGen.initialize(keySize);
KeyPair keyPair = keyPairGen.generateKeyPair();
@ -117,6 +116,9 @@ public class RSAUtils {
keyMap.put(PUBLIC_KEY, publicKey);
keyMap.put(PRIVATE_KEY, privateKey);
System.out.println("publicKey" + Base64.encode(publicKey.getEncoded()));
System.out.println("privateKey" + Base64.encode(privateKey.getEncoded()));
return keyMap;
}
@ -127,18 +129,18 @@ public class RSAUtils {
* @param data 已加密的数据
* @param privateKey 私钥
* @return 对已加密数据生成的签名
* @throws Exception 异常
* * @throws Exception 异常
*/
public static byte[] sign(byte[] data, String privateKey) throws Exception {
byte[] keyBytes = Base64.decode(privateKey, Base64.DEFAULT);
public static String sign(byte[] data, String privateKey) throws Exception {
byte[] keyBytes = Base64.decode(privateKey);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initSign(privateK);
signature.update(data);
return Base64.encode(signature.sign(), Base64.DEFAULT);
return Base64.encode(signature.sign());
}
@ -149,17 +151,17 @@ public class RSAUtils {
* @param publicKey 公钥
* @param sign 签名之后的数据
* @return 验签是否成功
* @throws Exception 异常
* * @throws Exception 异常
*/
public static boolean verify(byte[] data, String publicKey, String sign) throws Exception {
byte[] keyBytes = Base64.decode(publicKey, Base64.DEFAULT);
byte[] keyBytes = Base64.decode(publicKey);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
PublicKey publicK = keyFactory.generatePublic(keySpec);
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initVerify(publicK);
signature.update(data);
return signature.verify(Base64.decode(sign.getBytes(), Base64.DEFAULT));
return signature.verify(Base64.decode(sign));
}
@ -169,13 +171,14 @@ public class RSAUtils {
* @param encryptedData 使用公钥加密过的数据
* @param privateKey 私钥
* @return 解密后的数据
* @throws Exception 异常
* * @throws Exception 异常
*/
public static byte[] decryptByPrivateKey(byte[] encryptedData, String privateKey) throws Exception {
byte[] keyBytes = Base64.decode(privateKey, Base64.DEFAULT);
byte[] keyBytes = Base64.decode(privateKey);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
//Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, privateK);
@ -208,10 +211,10 @@ public class RSAUtils {
* @param encryptedData 使用私钥加密过的数据
* @param publicKey 公钥
* @return 解密后的数据
* @throws Exception 异常
* * @throws Exception 异常
*/
public static byte[] decryptByPublicKey(byte[] encryptedData, String publicKey) throws Exception {
byte[] keyBytes = Base64.decode(publicKey, Base64.DEFAULT);
byte[] keyBytes = Base64.decode(publicKey);
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key publicK = keyFactory.generatePublic(x509KeySpec);
@ -245,10 +248,10 @@ public class RSAUtils {
* @param data 需要加密的数据
* @param publicKey 公钥
* @return 使用公钥加密后的数据
* @throws Exception 异常
* * @throws Exception 异常
*/
public static byte[] encryptByPublicKey(byte[] data, String publicKey) throws Exception {
byte[] keyBytes = Base64.decode(publicKey, Base64.DEFAULT);
byte[] keyBytes = Base64.decode(publicKey);
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key publicK = keyFactory.generatePublic(x509KeySpec);
@ -283,10 +286,10 @@ public class RSAUtils {
* @param data 待加密的数据
* @param privateKey 私钥
* @return 使用私钥加密后的数据
* @throws Exception 异常
* * @throws Exception 异常
*/
public static byte[] encryptByPrivateKey(byte[] data, String privateKey) throws Exception {
byte[] keyBytes = Base64.decode(privateKey, Base64.DEFAULT);
byte[] keyBytes = Base64.decode(privateKey);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
@ -319,14 +322,13 @@ public class RSAUtils {
*
* @param keyMap 生成的秘钥对
* @return 私钥
* @throws Exception 异常
*/
public static String getPrivateKey(Map<String, Object> keyMap) throws Exception {
public static String getPrivateKey(Map<String, Object> keyMap) {
Key key = (Key) keyMap.get(PRIVATE_KEY);
if (key == null) {
return null;
} else {
return Arrays.toString(Base64.encode(key.getEncoded(), Base64.DEFAULT));
return Base64.encode(key.getEncoded());
}
}
@ -336,14 +338,14 @@ public class RSAUtils {
*
* @param keyMap 生成的秘钥对
* @return 公钥
* @throws Exception 异常
*/
public static String getPublicKey(Map<String, Object> keyMap) throws Exception {
public static String getPublicKey(Map<String, Object> keyMap) {
Key key = (Key) keyMap.get(PUBLIC_KEY);
if (key == null) {
return null;
} else {
return Arrays.toString(Base64.encode(key.getEncoded(), Base64.DEFAULT));
return Base64.encode(key.getEncoded());
}
}
}
}