Java加密的常用的加密算法类型有三种
1单向加密:也就是不可逆的加密,例如MD5,SHA,HMAC
2对称加密:也就是加密方和解密方利用同一个秘钥对数据进行加密和解密,例如DES,PBE等等
3非对称加密:非对称加密分为公钥和秘钥,二者是非对称的,例如用私钥加密的内容需要使用公钥来解密,使用公钥加密的内容需要用私钥来解密,DSA,RSA…
关于keyGenerator,KeyPairGenerator,SecretKeyFactory的解析
keyGenerator:秘钥生成器,也就是更具算法类型随机生成一个秘钥,例如HMAC,所以这个大部分用在非可逆的算法中
SecretKeyFactory:秘密秘钥工厂,言外之意就是需要根据一个秘密(password)去生成一个秘钥,例如DES,PBE,所以大部分使用在对称加密中
KeyPairGenerator:秘钥对生成器,也就是可以生成一对秘钥,也就是公钥和私钥,所以大部分使用在非对称加密中
代码实现
秘钥生成方式
秘钥生成的时候只要SecureRandom种子不变,秘钥不变;
如果需要每次生成不同的秘钥,就可以使用系统自带的种子;
/*
* @Description:生成秘钥
* @Author:
* @Date:2019/8/8 15:27
*/
public class KeyGen {
/*****************************************************KeyGenerator生成秘钥*****************************************************************/
public static SecretKey keyGenerator(String password) throws Exception{
SecureRandom random =new SecureRandom(password.getBytes());
//返回生成指定算法的秘密密钥的 KeyGenerator 对象
KeyGenerator kg = KeyGenerator.getInstance("DES");
//初始化此密钥生成器,使其具有确定的密钥大小
kg.init(random);
//生成一个密钥
SecretKey secretKey = kg.generateKey();
return secretKey;
}
/*********************************************************SecretKeyFactory生成秘钥**********************************************************************************/
public static SecretKey secretKeyFactory(String password) throws Exception{
//实例化DES密钥规则
DESKeySpec dks = new DESKeySpec(password.getBytes());
//实例化密钥工厂
SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
//生成密钥
SecretKey secretKey = skf.generateSecret(dks);
return secretKey;
}
/**********************************************************KeyPairGenerator生成公钥私钥***********************************************************************************************************/
public static Map<String, byte[]> keyPairGeneratorByte(String password) throws IOException, NoSuchAlgorithmException {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
SecureRandom secureRandom = new SecureRandom(password.getBytes());
keyPairGenerator.initialize(1024, secureRandom);
KeyPair keyPair = keyPairGenerator.genKeyPair();
byte[] publicKeyBytes = keyPair.getPublic().getEncoded();
byte[] privateKeyBytes = keyPair.getPrivate().getEncoded();
Map<String, byte[]> map = new HashMap<String, byte[]>();
map.put("pub", publicKeyBytes);
map.put("pri", privateKeyBytes);
return map;
}
public static Map<String, Object> keyPairGenerator(String password) throws IOException, NoSuchAlgorithmException {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
SecureRandom secureRandom = new SecureRandom(password.getBytes());
keyPairGenerator.initialize(1024, secureRandom);
KeyPair keyPair = keyPairGenerator.genKeyPair();
byte[] publicKeyBytes = keyPair.getPublic().getEncoded();
byte[] privateKeyBytes = keyPair.getPrivate().getEncoded();
Map<String,Object> map = new HashMap<String, Object>();
map.put("pub", keyPair.getPublic());
map.put("pri", keyPair.getPrivate());
return map;
}
/*
* @Description:获取公钥
* @Param:[publicKey]
* @Date:2019/7/25 10:00
*/
public static PublicKey getPublicKey(byte[] publicKey) throws Exception {
X509EncodedKeySpec spec = new X509EncodedKeySpec(publicKey);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePublic(spec);
}
/*
* @Description:获取私钥
* @Param:[privateKey]
* @Date:2019/7/25 10:01
*/
public static PrivateKey getPrivateKey(byte[] privateKey) throws Exception {
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(privateKey);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePrivate(spec);
}
}
1、单向加密
/*
* @Description:单向加密
* @Author:
* @Date:2019/8/8 9:16
*/
public class DxjmUtils {
/*
* @Description:md5生成数据长度为16Byte,Sha生成20Byte,固定长度
* @Author:
* @Date:2019/8/8 9:58
*/
public static byte[] cactHash(byte[] bytes) {
byte[] _bytes = null;
try {
//可以选择MD5加密或SHA加密
MessageDigest md = MessageDigest.getInstance("SHA1");
//数据加密 下面两行代码相当用于md.digest(bytes)
md.update(bytes);
_bytes = md.digest();
} catch (NoSuchAlgorithmException ex) {
ex.printStackTrace();
}
return _bytes;
}
public static void main(String[] arg) throws Base64DecodingException {
String str="测试";
byte[] jmstr=cactHash(str.getBytes());
byte[] jmstr1=cactHash(str.getBytes());
System.out.println(Base64.encode(jmstr));
System.out.println(Base64.encode(jmstr1));
}
}
2、对称加密
/*
* @Description:对称加密
* @Author:
* @Date:2019/8/8 10:03
*/
public class DcjmUtils {
/*
* @Description:加密
* @Author:
* @Date:2019/8/8 15:36
*/
public static byte[] encrypt(byte[] data, Key key) throws Exception{
//实例化
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
//使用密钥初始化,设置为加密模式
cipher.init(Cipher.ENCRYPT_MODE, key);
//执行操作
return cipher.doFinal(data);
}
/*
* @Description:解密
* @Author:
* @Date:2019/8/8 15:38
*/
public static byte[] decrypt(byte[] data,Key key) throws Exception{
//实例化
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
//使用密钥初始化,设置为解密模式
cipher.init(Cipher.DECRYPT_MODE, key);
//执行操作
return cipher.doFinal(data);
}
public static void main(String[] arg) throws Exception {
String str="测试";
//密码不能小于8位否则报错 throw new InvalidKeyException("Wrong key size");
SecretKey key= KeyGen.secretKeyFactory("abcdefgiabcdefgi");
byte[] enStr=encrypt(str.getBytes(),key);
byte[] deStr=decrypt(enStr,key);
System.out.println(Base64.encode(key.getEncoded()));
System.out.println(Base64.encode(enStr));
System.out.println(new String(deStr));
}
}
3、非对称加密
/*
* @Description:非对称加密
* @Author:
* @Date:2019/8/8 16:25
*/
public class FdcjmUtils {
/*
* @Description:非对称公钥加密
* @Author:
* @Date:2019/8/8 16:26
*/
public static byte[] encryptByPublicKey(byte[] data, PublicKey publicKey)
throws Exception {
// 对数据加密
Cipher cipher = Cipher.getInstance(publicKey.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(data);
}
/*
* @Description:非对称私钥解密
* @Author:
* @Date:2019/8/8 16:29
*/
public static byte[] decrypt(byte data[], PrivateKey privateKey) throws Exception{
// 对数据解密
Cipher cipher = Cipher.getInstance(privateKey.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return cipher.doFinal(data);
}
public static void main(String[] arg) throws Exception {
Map<String, byte[]> map= KeyGen.keyPairGeneratorByte("abcdefg");
//不使用随机数加密,解密
String str="测试";
byte[] enStr= encryptByPublicKey(str.getBytes(),KeyGen.getPublicKey(map.get("pub")));
byte[] deStr= decrypt(enStr,KeyGen.getPrivateKey(map.get("pri")));
System.out.println(Base64.encode(enStr));
System.out.println(new String(deStr));
}
}