java中安全加密/解密

//常见的加密协议
1,base64加密,从现在的加密技术来看,这种加密技术都不好意思说算是加密技术。

2,对称加密(DES):全称:Data Encryption Standard。采用单钥密码系统的加密方法,同一个密码可以同时作用信息的加密和解密。解密和解密都是同一个密码,因此传输这个
密码的过程必须相当安全。优点:计算量小,加密速度快,加密效率高。缺点:很容易被暴力破解

3,3DES3DES,也就是"triple DES",中文名“三重数据加密算法”,对每一个数据模块应用三次DES加密算法。只是增加了DES的长度来避免暴力破解。并不是全新的算法。

4,AESAES,全称:Advanced Encryption Standard,中文高级加密标准。非常的强大,是美国的一种区块加密标准。强安全性,高性能,高效率,易用,灵活等

5,非对称加密。非对称加密方式需要两个密钥来进行加密和解密。分别是公钥和私钥,并且公钥和私钥必须是一对的才能解密,反之,亦然。这是已经是非常安全的加密方式了
5.1,RSA加密。
5.2, DH算法。
5.3, 数字签名证书(更加高级的加密方式)

实例:
实现过程:
生成密钥对->获取公玥->转成PublicKey对象->公玥加密->转成base64码
生成密钥对->获取私玥->PrivateKey对象->私玥解密->转成bytes

//RSA加密类RSAUtil
public class RSAUtil{
//生成密钥对
public static KeyPair getKeyPair() throws Exception {
	KeyPairGenerater keyPairGenerater = new KeyPairGenterater();
	keyPairGenerater.initialize(2048);
	KeyPair keyPair = keyPairGenerater.generateKeyPair();
	return keyPair;
}
//获取公钥(base64编码)
public static String getPublicKey(KeyPair keyPair){
	PublicKey publicKey =keyPair.getPublic();
	byte[] bytes = new publicKey.getEncoded();
	return byte2Base64(bytes);
}
//获取私钥(base64编码)
public static String getPrivateKey(KeyPair keyPair){
	PrivateKey publicKey =keyPair.getPrivate();
	byte[] bytes = new publicKey.getEncoded();
	return byte2Base64(bytes);		
}
//将Base64编码后的公钥转换成PublicKey对象
Public static PublicKey string2PublicKey(String pubstr) throws Exception{
	byte[] keyBytes = base642Byte(pubstr);
	X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
	KeyFactory keyFactory = keyFactory.getInstance("RSA");
	PublicKey publicKey = keyFacTory.generatePublic(keySpec);
	return publicKey;
}
//将Base64编码后的私钥转换成PrivateKey对象
Public static PublicKey string2PublicKey(String pubstr) throws Exception{
	byte[] keyBytes = base642Byte(pubstr);
	PKCS8EncodeKeySpec keySpec = new PKCS8EncodeKeySpec(keyBytes);
	KeyFactory keyFactory = keyFactory.getInstance("RSA");
	PrivateKey privateKey = keyFacTory.generatePrivate(keySpec);
	return privateKey;
}
//公钥加密
public static byte[] publicEncrypt(byte[] content,PublicKey publicKey) throws Exception{
	Ciper ciper = Ciper.getInstance("RSA");
	ciper.init(Ciper.ENCRYPT_MODE,publicKey);
	byte[] bytes =ciper.doFinal(content);
	return bytes;
}
//私钥解密
public static byte[] privateEncrypt(byte[] content,PrivateKey privateKey) throws Exception{
	Ciper ciper = Ciper.getInstance("RSA");
	ciper.init(Ciper.ENCRYPT_MODE,privateKey);
	byte[] bytes =ciper.doFinal(content);
	return bytes;
}
//字节数组转Base64编码	
public static String byte2Base64(byte[] bytes){
	BASE64Encoder encoder=new BASE64Encoder();
	return encoder.encode(bytes);
}
//Base64编码转字节数组
public static String Base642byte(String base64Key) throws IOExcption{
	BASE64Decoder decoder=new BASE64Decoder();
	return decoder.encode(base64Key);
}

}

猜你喜欢

转载自blog.csdn.net/weixin_42603009/article/details/86761066