加密解密
本次介绍比较常用的MD5加密,SHA1加密,RSA加密,AES加密的java实现方法,其中MD5和SHA1加密属于哈希散列算法加密,RSA属于非对称加密,AES属于对称加密。
散列算法的主要作用就是将某段信息加密生成对应的散列结果,这个散列结果是不可逆并且唯一的,不会有连个不同的信息生成相同的散列结果,这样就能用于验证信息是否被篡改过。
RSA算法的主要作用在于公钥加密的只有私钥能解密这样保证数据的安全,私钥加密的所有公钥都能解密,但是可以在内容附加对应的签名保证内容不会被修改
AES加密的主要作用就是实现正常的加密和解密,只有拥有密钥和偏移量信息的才能加解密,所以对应信息一定要保存好
MD5/SHA1算法java的实现
public static String getDigest(String msg) throws UnsupportedEncodingException, NoSuchAlgorithmException {
if(null == md5) {
md5= MessageDigest.getInstance("MD5");
//md5= MessageDigest.getInstance("SHA1");
}
byte[] byteArray=null;
byteArray=msg.getBytes("UTF-8");
byte[] md5Bytes=md5.digest(byteArray);
StringBuffer hexValue=new StringBuffer();
for(int i=0; i < md5Bytes.length; i++) {
int val=((int)md5Bytes[i]) & 0xff;
if(val < 16)
hexValue.append("0");
hexValue.append(Integer.toHexString(val));
}
return hexValue.toString();
}
主要就是先用MessageDigest加密明文信息生成的字节数组拿到密文字节数组,然后将其转为十六进制。另外还可以加盐加密,通过给明文拼接一串随机字符(盐值)再加密,会使加密过程更加安全,不过要注意保存好盐值。
RSA加密算法java实现
public static String data="hello world";
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
KeyPair keyPair=genKeyPair(1024);
//获取公钥,并以base64格式打印出来
PublicKey publicKey=keyPair.getPublic();
System.out.println("公钥:"+new String(Base64.getEncoder().encode(publicKey.getEncoded())));
//获取私钥,并以base64格式打印出来
PrivateKey privateKey=keyPair.getPrivate();
System.out.println("私钥:"+new String(Base64.getEncoder().encode(privateKey.getEncoded())));
//公钥加密
byte[] encryptedBytes=encrypt(data.getBytes(), publicKey);
System.out.println("加密后:"+new String(encryptedBytes));
//私钥解密
byte[] decryptedBytes=decrypt(encryptedBytes, privateKey);
System.out.println("解密后:"+new String(decryptedBytes));
}
//生成密钥对
public static KeyPair genKeyPair(int keyLength) throws Exception{
KeyPairGenerator keyPairGenerator=KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(1024);
return keyPairGenerator.generateKeyPair();
}
//公钥加密
public static byte[] encrypt(byte[] content, PublicKey publicKey) throws Exception{
Cipher cipher=Cipher.getInstance("RSA");//java默认"RSA"="RSA/ECB/PKCS1Padding"
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(content);
}
//私钥解密
public static byte[] decrypt(byte[] content, PrivateKey privateKey) throws Exception{
Cipher cipher=Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return cipher.doFinal(content);
}
AES加密java实现
// 加密
public static String Encrypt(String 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("utf-8");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");//"算法/模式/补码方式"
IvParameterSpec iv = new IvParameterSpec(cKey.getBytes());//使用CBC模式,需要一个向量iv,可增加加密算法的强度
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(sSrc.getBytes());
return new Base64().encode(encrypted);//此处使用BASE64做转码功能,同时能起到2次加密的作用。
}
// 解密
public static String Decrypt(String 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("utf-8");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec iv = new IvParameterSpec(cKey.getBytes());
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] encrypted1 = new Base64().decode(sSrc);//先用base64解密
try {
byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original);
return originalString;
} catch (Exception e) {
System.out.println(e.toString());
return null;
}
} catch (Exception ex) {
System.out.println(ex.toString());
return null;
}
}