Base加密解密、DES/AES对称加密
程序员文章站
2024-03-14 13:20:46
...
Cita 2020-07-24
1. Base64工具类
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
/**
* Base64加密解密工具类
*/
public class Base64 {
private static final char[] legalChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray();
public static String encode(byte[] data) {
int start = 0;
int len = data.length;
StringBuffer buf = new StringBuffer(data.length * 3 / 2);
int end = len - 3;
int i = start;
int n = 0;
while (i <= end) {
int d = ((((int) data[i]) & 0x0ff) << 16) | ((((int) data[i + 1]) & 0x0ff) << 8) | (((int) data[i + 2]) & 0x0ff);
buf.append(legalChars[(d >> 18) & 63]);
buf.append(legalChars[(d >> 12) & 63]);
buf.append(legalChars[(d >> 6) & 63]);
buf.append(legalChars[d & 63]);
i += 3;
if (n++ >= 14) {
n = 0;
buf.append(" ");
}
}
if (i == start + len - 2) {
int d = ((((int) data[i]) & 0x0ff) << 16) | ((((int) data[i + 1]) & 255) << 8);
buf.append(legalChars[(d >> 18) & 63]);
buf.append(legalChars[(d >> 12) & 63]);
buf.append(legalChars[(d >> 6) & 63]);
buf.append("=");
} else if (i == start + len - 1) {
int d = (((int) data[i]) & 0x0ff) << 16;
buf.append(legalChars[(d >> 18) & 63]);
buf.append(legalChars[(d >> 12) & 63]);
buf.append("==");
}
return buf.toString();
}
private static int decode(char c) {
if (c >= 'A' && c <= 'Z')
return ((int) c) - 65;
else if (c >= 'a' && c <= 'z')
return ((int) c) - 97 + 26;
else if (c >= '0' && c <= '9')
return ((int) c) - 48 + 26 + 26;
else
switch (c) {
case '+':
return 62;
case '/':
return 63;
case '=':
return 0;
default:
throw new RuntimeException("unexpected code: " + c);
}
}
/**
* @Description: 将给定的Base64编码字符串解码为新的字节数组,返回保存解码数据的字节数组。
*/
public static byte[] decode(String s) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
decode(s, bos);
} catch (IOException e) {
throw new RuntimeException();
}
byte[] decodedBytes = bos.toByteArray();
try {
bos.close();
bos = null;
} catch (IOException ex) {
System.err.println("Error while decoding BASE64: " + ex.toString());
}
return decodedBytes;
}
private static void decode(String s, OutputStream os) throws IOException {
int i = 0;
int len = s.length();
while (true) {
while (i < len && s.charAt(i) <= ' ')
i++;
if (i == len)
break;
int tri = (decode(s.charAt(i)) << 18) + (decode(s.charAt(i + 1)) << 12) + (decode(s.charAt(i + 2)) << 6) + (decode(s.charAt(i + 3)));
os.write((tri >> 16) & 255);
if (s.charAt(i + 2) == '=')
break;
os.write((tri >> 8) & 255);
if (s.charAt(i + 3) == '=')
break;
os.write(tri & 255);
i += 4;
}
}
public static void main(String[] args) throws UnsupportedEncodingException {
String content = "hello Base64";
System.out.println("加密之前:" + content);
// 加密
String jiami = Base64.encode(content.getBytes("utf-8"));
System.out.println("加密后的内容:" + jiami);
// 解密
String jiemi = new String(Base64.decode(jiami));
System.out.println("解密后的内容:" + jiemi);
}
}
2. DES数据加密标准(Data Encryption Standard)对称加密
概述:加密和解密都使用同一把**,这种加密方法称为对称加密
,也称为单**加密。简单理解为:加密和解密都是同一把钥匙。
简介:DES算法**总长度64位
,加密56位
+8位(即每个第8位都用作奇偶校验),作为校验码, 不参与加密运算
。
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
/**
* @detail DES对称加密
* @author Cita
*/
public class DES {
public static void main(String[] args) throws Exception {
/**
* 1. 明文
* 2. 提供原始**: 长度64位,8个字节(必须)
*/
String text = "hello DES";
String originKey = "a2c4e6g8";
// 加密
String cryptText = desEncript(text,originKey);
System.out.println("加密后:"+cryptText);
// 解密
String decipherText = descript(cryptText,originKey);
System.out.println("解密后:"+decipherText);
}
// 加密方式
public static final String MODE = "DES";
/**
* @Description: (加密)Cipher的DES算法
* @throws: NoSuchAlgorithmException: 填充异常(工作模式和填充模式)
* @throws:NoSuchPaddingException: 没有此算法异常
* @throws: InvalidKeyException: 无效的**异常
* @throws: IllegalBlockSizeException: 非法块大小异常
*/
private static String desEncript(String text,String originKey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
//1.获取加密算法工具类
Cipher cipher = Cipher.getInstance(MODE);
/**
* 2.对工具类对象进行初始化
* opmode: 加密/解密模式Cipher.ENCRYPT_MODE加密
* key: 对原始**处理之后的**
*/
SecretKeySpec key = new SecretKeySpec(originKey.getBytes(),MODE);
cipher.init(Cipher.ENCRYPT_MODE, key);
//3.用加密工具类对象对明文加密
byte[] doFinal = cipher.doFinal(text.getBytes());
//4.Base64.encode(doFinal);base64防止出现乱码
return Base64.encode(doFinal);
}
/**
* @Description DES 解密
*/
public static String descript(String text,String originKey)throws Exception {
//1.获取加密算法工具类
Cipher cipher = Cipher.getInstance(MODE);
//2.对工具类对象进行初始化Cipher.DECRYPT_MODE解密
Key key = new SecretKeySpec(originKey.getBytes(),MODE);
cipher.init(Cipher.DECRYPT_MODE, key);
//3.使用了base64防止乱码,要先base64解码
byte[] decode = Base64.decode(text);
//4.用加密工具类对象对解密
byte[] doFinal = cipher.doFinal(decode);
return new String(doFinal);
}
}
3. AES高级加密标准( Advanced Encryption Standard)对称加密
由于现在电脑的多线程解密时间更短出现了AES,是在DES的基础上把**提升到了16位进行加密。
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
/**
* @detail AES对称加密
* @author Cita
*/
public class AES {
public static void main(String[] args) throws Exception {
/**
* 1. 明文
* 2. 提供原始**: 长度128位,16个字节(必须)
*/
String text = "hello AES";
String originKey = "a2c4e6g8i9k0mlno";
// 加密
String cryptText = desEncript(text,originKey);
System.out.println("加密后:"+cryptText);
// 解密
String decipherText = descript(cryptText,originKey);
System.out.println("解密后:"+decipherText);
}
// 加密方式
public static final String MODE = "AES";
/**
* @Description: (加密)Cipher的AES算法
*/
private static String desEncript(String text,String originKey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
Cipher cipher = Cipher.getInstance(MODE);
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(originKey.getBytes(),MODE));
return Base64.encode(cipher.doFinal(text.getBytes()));
}
/**
* @Description AES 解密
*/
public static String descript(String text,String originKey)throws Exception {
Cipher cipher = Cipher.getInstance(MODE);
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(originKey.getBytes(),MODE));
return new String(cipher.doFinal(Base64.decode(text)));
}
}
上一篇: 歌星大奖赛