Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

补充一些金额转换方法以及强制创建文件方法(当目录不存在的时候先创建目录) #134

Open
wants to merge 12 commits into
base: master
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
增加加解密工具:PBE(Password-based encryption,基于密码验证)加解密、Diffie-Hellman算法加解密
zhanggh authored and haven.zhang committed Oct 24, 2018
commit ce93f934de3e0574f912dd786a589111758c29bb
Original file line number Diff line number Diff line change
@@ -122,7 +122,34 @@ public enum CipherAlgorithms {
RSA_ECB_PKCS1Padding("RSA/ECB/PKCS1Padding"),
RSA_ECB_OAEPWithSHA1("RSA/ECB/OAEPWithSHA-1AndMGF1Padding"),
RSA_ECB_OAEPWithSHA256("RSA/ECB/OAEPWithSHA-256AndMGF1Padding"),
RSA_ECB_NoPadding("RSA/ECB/NoPadding");
RSA_ECB_NoPadding("RSA/ECB/NoPadding"),

PBEWithSHAAndDES("PBEWithSHAAndDES"),
PBEWithHmacSHA256AndAES_128("PBEWithHmacSHA256AndAES_128"),
PBEWithMD5AndTripeDES("PBEWithMD5AndTripeDES"),
PBEWithSHA1AndDESede("PBEWithSHA1AndDESede"),
PBEWithSHA1AndIDEA_CBC("PBEWithSHA1AndIDEA-CBC"),
PBEWITHSHAANDRC2("PBEWITHSHAANDRC2"),
PBEWITHSHAANDRC4("PBEWITHSHAANDRC4"),
PBEWITHMD2ANDDES("PBEWITHMD2ANDDES"),

PBEWithSHAAndTwofish_CBC("PBEWithSHAAndTwofish-CBC"),
PBEWithSHAAnd40BitRC4("PBEWithSHAAnd40BitRC4"),
PBEWithSHAAnd128BitRC4("PBEWithSHAAnd128BitRC4"),
PBEWithSHAAnd40BitRC2_CBC("PBEWithSHAAnd40BitRC2-CBC"),
PBEWithSHAAnd128BitRC2_CBC("PBEWithSHAAnd128BitRC2-CBC"),
PBEWithSHAAnd3_KeyTripleDES_CBC ("PBEWithSHAAnd3-KeyTripleDES-CBC"),
PBEWithSHAAnd2_KeyTripleDES_CBC("PBEWithSHAAnd2-KeyTripleDES-CBC"),
PBEWithSHA1AndRC2("PBEWithSHA1AndRC2"),
PBEWithMD5AndDES("PBEWithMD5AndDES"),
PBEWithSHA1AndDES("PBEWithSHA1AndDES"),
PBEWITHSHA256AND256BITAES_CBC_BC("PBEWITHSHA256AND256BITAES-CBC-BC"),
PBEWITHSHA256AND192BITAES_CBC_BC("PBEWITHSHA256AND192BITAES-CBC-BC"),
PBEWITHSHA256AND128BITAES_CBC_BC("PBEWITHSHA256AND128BITAES-CBC-BC"),
PBEWITHSHAAND256BITAES_CBC_BC("PBEWITHSHAAND256BITAES-CBC-BC"),
PBEWITHSHAAND192BITAES_CBC_BC("PBEWITHSHAAND192BITAES-CBC-BC"),
PBEWITHSHAAND128BITAES_CBC_BC("PBEWITHSHAAND128BITAES-CBC-BC"),
PBEWithMD5AndRC2("PBEWithMD5AndRC2");

private String value;

Original file line number Diff line number Diff line change
@@ -14,7 +14,7 @@ public enum KeyGeneratorType {
HmacSHA512,
HmacMD5,
Blowfish,
ARCFOUR,
// ARCFOUR,
AES,
DES,
DESede;
90 changes: 86 additions & 4 deletions vjkit/src/main/java/com/vip/vjtools/vjkit/security/CryptoUtil.java
Original file line number Diff line number Diff line change
@@ -5,15 +5,15 @@
import java.security.spec.X509EncodedKeySpec;
import java.util.Arrays;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import com.vip.vjtools.vjkit.base.ExceptionUtil;
import com.vip.vjtools.vjkit.enums.CipherAlgorithms;
import com.vip.vjtools.vjkit.enums.KeyGeneratorType;
import com.vip.vjtools.vjkit.enums.SecretKeyType;
import com.vip.vjtools.vjkit.number.RandomUtil;
import com.vip.vjtools.vjkit.text.Charsets;
@@ -582,4 +582,86 @@ public static byte[] rsaDecrypt(byte[] input, byte[] key,byte[] iv,CipherAlgorit
}
}

/**
* pbe加密
* @param input 原始字节数组
* @param password pbe 字符串秘钥 可以任意长度
* @param salt 盐 Salt must be 8 bytes long
* @param algorithms 可选不同的加密工作模式/填充模式,具体见CipherAlgorithms枚举
* @return byte[] 加密结果
*/
public static byte[] pbeEncrypt(byte[] input, String password,byte[] salt,CipherAlgorithms algorithms){
try {
PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithms.getValue());
SecretKey secretKey = keyFactory.generateSecret(keySpec);
PBEParameterSpec paramSpec = new PBEParameterSpec(salt, 100);//100:iterationCount - the iteration count.
Cipher cipher = Cipher.getInstance(algorithms.getValue());
cipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec);
return cipher.doFinal(input);
} catch (GeneralSecurityException e) {
throw ExceptionUtil.unchecked(e);
}
}


/**
* pbe解密
* @param input 密文数组
* @param password pbe 字符串秘钥 可以任意长度
* @param salt 盐值 Salt must be 8 bytes long
* @param algorithms 可选不同的加密工作模式/填充模式,具体见CipherAlgorithms枚举
* @return byte[] 解密后明文结果
*/
public static byte[] pbeDecrypt(byte[] input, String password,byte[] salt,CipherAlgorithms algorithms){
try {
PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithms.getValue());
SecretKey secretKey = keyFactory.generateSecret(keySpec);
PBEParameterSpec paramSpec = new PBEParameterSpec(salt, 100);//100:iterationCount - the iteration count.
Cipher cipher = Cipher.getInstance(algorithms.getValue());
cipher.init(Cipher.DECRYPT_MODE, secretKey, paramSpec);
return cipher.doFinal(input);
} catch (GeneralSecurityException e) {
throw ExceptionUtil.unchecked(e);
}
}


/**
* DiffieHellman算法加密
* @param input 加密原文
* @param publicKey 对方公钥
* @param privateKey 我方私钥
* @param keyAlgorithms 生成的对称秘钥算法:仅支持 DES/DESede/AES
* @return byte[] 密文
* @throws Exception
*/
public static byte[] dhEncrypt(byte[] input,PublicKey publicKey,PrivateKey privateKey,KeyGeneratorType keyAlgorithms)
throws Exception {
SecretKey secretKey = KeyUtil.generateKey(publicKey, privateKey, keyAlgorithms);
// 数据解密
Cipher cipher = Cipher.getInstance(secretKey.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return cipher.doFinal(input);
}


/**
* DiffieHellman算法解密
* @param input 加密密文
* @param publicKey 对方公钥
* @param privateKey 我方私钥
* @param keyAlgorithms 生成的对称秘钥算法:仅支持 DES/DESede/AES
* @return byte[] 解密明文
* @throws Exception
*/
public static byte[] dhDencrypt(byte[] input,PublicKey publicKey,PrivateKey privateKey,KeyGeneratorType keyAlgorithms)
throws Exception {
SecretKey secretKey = KeyUtil.generateKey(publicKey, privateKey, keyAlgorithms);
// 数据解密
Cipher cipher = Cipher.getInstance(secretKey.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return cipher.doFinal(input);
}
}
41 changes: 41 additions & 0 deletions vjkit/src/main/java/com/vip/vjtools/vjkit/security/KeyUtil.java
Original file line number Diff line number Diff line change
@@ -9,15 +9,18 @@
import com.vip.vjtools.vjkit.enums.KeyStoreType;
import com.vip.vjtools.vjkit.io.IOUtil;

import javax.crypto.KeyAgreement;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.io.*;
import java.security.*;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Arrays;
import java.util.Enumeration;


@@ -271,6 +274,24 @@ public static KeyPair generateKeyPair(KeyPairAlgorithms algorithms, int keyLen)

}


/**
* �����ǶԳ���Կ��
* @param algorithms �ǶԳ���Կ�㷨
* @param parameterSpec cryptographic parameters
* @return
* @throws Exception
*/
public static KeyPair generateKeyPair(KeyPairAlgorithms algorithms, AlgorithmParameterSpec parameterSpec) throws Exception {
//��ö��� KeyPairGenerator
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(algorithms.name());
keyPairGen.initialize(parameterSpec);
//ͨ������ KeyPairGenerator ��ȡ����KeyPair
KeyPair keyPair = keyPairGen.generateKeyPair();
return keyPair;

}

/**
* rc Key length for ARCFOUR must be between 40 and 1024 bits
* ���ɶԳ���Կ,��ѡ����
@@ -283,6 +304,26 @@ public static byte[] generateKey(int keysize, KeyGeneratorType type) throws NoSu
return secretKey.getEncoded();
}

/**
* ����DiffieHellman�㷨���ضԳ���Կ
* @param publicKey ��Կ
* @param privateKey ˽Կ
* @param secretAlgorithms ָ�����ɵĶԳ���Կ�㷨 ������DES /DESede/ AES�ȵ�
* @throws Exception
*/
public static SecretKey generateKey(PublicKey publicKey,PrivateKey privateKey,KeyGeneratorType secretAlgorithms)
throws Exception {
System.setProperty("jdk.crypto.KeyAgreement.legacyKDF","true");
KeyFactory keyFactory = KeyFactory.getInstance(KeyFactoryAlgorithms.DiffieHellman.name());
KeyAgreement keyAgree = KeyAgreement.getInstance(keyFactory
.getAlgorithm());
keyAgree.init(privateKey);
keyAgree.doPhase(publicKey, true);
// ���ɱ�����Կ
SecretKey secretKey = keyAgree.generateSecret(secretAlgorithms.name());
return secretKey;
}

/**
* ����des�㷨����Կ������Ϊ8���ֽ�
* @return
Original file line number Diff line number Diff line change
@@ -11,11 +11,14 @@

import com.vip.vjtools.vjkit.text.EncodeUtil;

import javax.crypto.SecretKey;
import javax.crypto.interfaces.DHPublicKey;
import java.io.UnsupportedEncodingException;
import java.security.KeyPair;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import java.util.Arrays;
import java.util.Random;


public class CryptoUtilTest {
@@ -185,4 +188,70 @@ public void rsaTest() throws Exception {
assertThat(StringUtils.trimToEmpty(new String(output)).getBytes("UTF-8")).isEqualTo(input);

}

@Test
public void pebTest() throws UnsupportedEncodingException {
Security.addProvider(new BouncyCastleProvider());
byte[] input = "PEB test".getBytes("UTF-8");
String passwd = "1";
byte[] salt = new byte[8];
Random random = new Random();
random.nextBytes(salt);

//加密
byte[] output = CryptoUtil.pbeEncrypt(input, passwd, salt, CipherAlgorithms.PBEWithSHAAndTwofish_CBC);
System.out.println(EncodeUtil.encodeHex(output));

//解密
output = CryptoUtil.pbeDecrypt(output,passwd,salt,CipherAlgorithms.PBEWithSHAAndTwofish_CBC);
System.out.println(new String(output));
assertThat(output).isEqualTo(input);
}



@Test
public void dhTest() throws Exception {
//DiffieHellman算法加密
Security.addProvider(new BouncyCastleProvider());
byte[] input = "DiffieHellman test".getBytes("UTF-8");

//生成甲方秘钥对
KeyPair keyPair = KeyUtil.generateKeyPair(KeyPairAlgorithms.DiffieHellman, 512);
//根据甲方公钥生成乙方秘钥对
KeyPair keyPair2 = KeyUtil.generateKeyPair(KeyPairAlgorithms.DiffieHellman,
((DHPublicKey) keyPair.getPublic()).getParams());
//加密
byte[] output = CryptoUtil.dhEncrypt(input, keyPair.getPublic(), keyPair2.getPrivate(),KeyGeneratorType.AES);
System.out.println(EncodeUtil.encodeHex(output));

//解密
output = CryptoUtil.dhDencrypt(output, keyPair2.getPublic(), keyPair.getPrivate(), KeyGeneratorType.AES);
System.out.println(new String(output));
assertThat(output).isEqualTo(input);


//----------------------DiffieHellman加密方式2

//使用甲方公钥和乙方私钥生成的秘钥
SecretKey secretKey = KeyUtil.generateKey( keyPair.getPublic(), keyPair2.getPrivate(), KeyGeneratorType.AES);
//使用乙方公钥和甲方方私钥生成的秘钥
SecretKey secretKey2 = KeyUtil.generateKey( keyPair2.getPublic(), keyPair.getPrivate(), KeyGeneratorType.AES);
//双方生成的秘钥应该要相同
assertThat(secretKey2.getEncoded()).isEqualTo(secretKey.getEncoded());

System.out.println(EncodeUtil.encodeHex(secretKey.getEncoded()));
System.out.println(EncodeUtil.encodeHex(secretKey2.getEncoded()));

//加密
output = CryptoUtil.aesEncrypt(input, secretKey.getEncoded(), CipherAlgorithms.AES_ECB_ISO10126Padding);
System.out.println(EncodeUtil.encodeHex(output));

//解密
output = CryptoUtil.aesDecrypt(output, secretKey2.getEncoded(), CipherAlgorithms.AES_ECB_ISO10126Padding);
System.out.println(new String(output));
assertThat(output).isEqualTo(input);
}


}
Original file line number Diff line number Diff line change
@@ -4,8 +4,11 @@
import com.google.common.collect.Maps;
import com.vip.vjtools.vjkit.enums.KeyGeneratorType;
import com.vip.vjtools.vjkit.enums.KeyPairAlgorithms;
import com.vip.vjtools.vjkit.text.EncodeUtil;
import org.junit.Test;

import javax.crypto.SecretKey;
import javax.crypto.interfaces.DHPublicKey;
import java.security.KeyPair;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
@@ -66,6 +69,18 @@ public void generatePairKeyTest() throws Exception {
assertThat(keyPair.getPrivate()).isNotNull();
assertThat(keyPair.getPublic()).isNotNull();

KeyPair keyPair2 = KeyUtil.generateKeyPair(KeyPairAlgorithms.DiffieHellman,
((DHPublicKey) keyPair.getPublic()).getParams());

System.out.println(EncodeUtil.encodeBase64(keyPair2.getPrivate().getEncoded()));
System.out.println(EncodeUtil.encodeBase64(keyPair2.getPublic().getEncoded()));

// System.setProperty("jdk.crypto.KeyAgreement.legacyKDF","true");

SecretKey sceret = KeyUtil.generateKey(keyPair.getPublic(), keyPair2.getPrivate(), KeyGeneratorType.AES);

System.out.println(sceret.getAlgorithm());
System.out.println(EncodeUtil.encodeBase64(sceret.getEncoded()));
}

}