-
BASE64加密/解密
示例:
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class Base64Util {
public static void main(String[] args) throws Exception{ String xml = "ceshi测试123"; byte[] bytes = xml.getBytes(); String mw = Base64Util.encryptBASE64(bytes); System.out.println("密文:"+mw); byte[] ywb = Base64Util.decryBASE64(mw); String yw = new String(ywb); System.out.println("原文:"+yw);
}
/***
* BASE64解密
* @param key
* @return
* @throws Exception
*/
public static byte[] decryBASE64(String key) throws Exception{
return (new BASE64Decoder()).decodeBuffer(key);
}
/***
* BASE64加密
* @param key
* @return
* @throws Exception
*/
public static String encryptBASE64(byte[] key) throws Exception{
return (new BASE64Encoder()).encode(key);
}
}
-
MD5(Message Digest Algorithm)加密
示例:貌似只能加密不能解密
import java.security.MessageDigest;
public class MD5Util {
public static final String KEY_MD5 = "MD5";
/***
* MD5加密(生成唯一的MD5值)
* @param data
* @return
* @throws Exception
*/
public static byte[] encryMD5(byte[] data) throws Exception {
MessageDigest md5 = MessageDigest.getInstance(KEY_MD5);
md5.update(data);
return md5.digest();
}
}
3.DES(Data Encryption Standard)对称加密/解密
示例:
import java.security.Key;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class DesUtil {
private static Key key;
private static String KEY_STR="myKey";
private static String CHARSETNAME="UTF-8";
private static String ALGORITHM="DES";
static {
try {
//生成DES算法对象
KeyGenerator generator=KeyGenerator.getInstance(ALGORITHM);
//运用SHA1安全策略
SecureRandom secureRandom=SecureRandom.getInstance("SHA1PRNG");
//设置上密钥种子
secureRandom.setSeed(KEY_STR.getBytes());
//初始化基于SHA1的算法对象
generator.init(secureRandom);
//生成密钥对象
key=generator.generateKey();
generator=null;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/***
* 获取加密的信息
* @param str
* @return
*/
public static String getEncryptString(String str) {
//基于BASE64编码,接收byte[]并转换成String
BASE64Encoder encoder = new BASE64Encoder();
try {
//按utf8编码
byte[] bytes = str.getBytes(CHARSETNAME);
//获取加密对象
Cipher cipher = Cipher.getInstance(ALGORITHM);
//初始化密码信息
cipher.init(Cipher.ENCRYPT_MODE, key);
//加密
byte[] doFinal = cipher.doFinal(bytes);
//byte[]to encode好的String 并返回
return encoder.encode(doFinal);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/***
* 获取解密之后的信息
* @param str
* @return
*/
public static String getDecryptString(String str) {
BASE64Decoder decoder = new BASE64Decoder();
try {
//将字符串decode成byte[]
byte[] bytes = decoder.decodeBuffer(str);
//获取解密对象
Cipher cipher = Cipher.getInstance(ALGORITHM);
//初始化解密信息
cipher.init(Cipher.DECRYPT_MODE, key);
//解密
byte[] doFial = cipher.doFinal(bytes);
return new String(doFial, CHARSETNAME);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
4.AES(Advanced Encryption Standard) 加密/解密
示例:
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class AESUtil {
public static final String algorithm = "AES";
// AES/CBC/NOPaddin
// AES 默认模式
// 使用CBC模式, 在初始化Cipher对象时, 需要增加参数, 初始化向量IV : IvParameterSpec iv = new
// IvParameterSpec(key.getBytes());
// NOPadding: 使用NOPadding模式时, 原文长度必须是8byte的整数倍
public static final String transformation = "AES/CBC/NOPadding";
public static final String key = "1234567812345678";
/***
* 加密
* @param original 需要加密的参数(注意必须是16位)
* @return
* @throws Exception
*/
public static String encryptByAES(String original) throws Exception {
// 获取Cipher
Cipher cipher = Cipher.getInstance(transformation);
// 生成密钥
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), algorithm);
// 指定模式(加密)和密钥
// 创建初始化向量
IvParameterSpec iv = new IvParameterSpec(key.getBytes());
cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv);
// cipher.init(Cipher.ENCRYPT_MODE, keySpec);
// 加密
byte[] bytes = cipher.doFinal(original.getBytes());
return Base64Util.encryptBASE64(bytes);
}
/**
* 解密
* @param encrypted 需要解密的参数
* @return
* @throws Exception
*/
public static String decryptByAES(String encrypted) throws Exception {
// 获取Cipher
Cipher cipher = Cipher.getInstance(transformation);
// 生成密钥
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), algorithm);
// 指定模式(解密)和密钥
// 创建初始化向量
IvParameterSpec iv = new IvParameterSpec(key.getBytes());
cipher.init(Cipher.DECRYPT_MODE, keySpec, iv);
// cipher.init(Cipher.DECRYPT_MODE, keySpec);
// 解密
byte[] bytes = cipher.doFinal(Base64Util.decryBASE64(encrypted));
return new String(bytes);
}
}
5.HMAC(Hash Message Authentication Code,散列消息鉴别码)
示例:
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class HMACUtil {
public static final String KEY_MAC = "HmacMD5";
/***
* 初始化HMAC密钥
* @return
* @throws Exception
*/
public static String initMacKey() throws Exception{
KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_MAC);
SecretKey secreKey = keyGenerator.generateKey();
return Base64Util.encryptBASE64(secreKey.getEncoded());
}
/**
* HMAC加密
* @param data
* @param key
* @return
* @throws Exception
*/
public static byte[] encryHMAC(byte[] data, String key) throws Exception{
SecretKey secreKey = new SecretKeySpec(Base64Util.decryBASE64(key), KEY_MAC);
Mac mac = Mac.getInstance(secreKey.getAlgorithm());
mac.init(secreKey);
return mac.doFinal();
}
}
6.恺撒加密
public class KaisaUtil {
/***
* 使用凯撒加密方式加密数据
* @param orignal 原文
* @param key 密钥
* @return 加密后的字符
*/
private static String encryptKaisa(String orignal, int key) {
//将字符串转换为数组
char[] chars = orignal.toCharArray();
StringBuffer buffer = new StringBuffer();
//遍历数组
for(char aChar : chars) {
//获取字符的ASCII编码
int asciiCode = aChar;
//偏移数据
asciiCode += key;
//将偏移后的数据转为字符
char result = (char)asciiCode;
//拼接数据
buffer.append(result);
}
return buffer.toString();
}
/**
* 使用凯撒加密方式解密数据
*
* @param encryptedData :密文
* @param key :密钥
* @return : 源数据
*/
private static String decryptKaiser(String encryptedData, int key) {
// 将字符串转为字符数组
char[] chars = encryptedData.toCharArray();
StringBuilder sb = new StringBuilder();
// 遍历数组
for (char aChar : chars) {
// 获取字符的ASCII编码
int asciiCode = aChar;
// 偏移数据
asciiCode -= key;
// 将偏移后的数据转为字符
char result = (char) asciiCode;
// 拼接数据
sb.append(result);
}
return sb.toString();
}
public static void main(String[] args) {
String str = "open fire";
String encode = encryptKaisa(str, 3);
System.out.println("加密后:"+encode);
String decode = decryptKaiser(encode, 3);
System.out.println("解密后:"+decode);
}
}
7.SHA(Secure Hash Algorithm,安全散列算法)
示例:
import java.security.MessageDigest;
public class SHAUtil {
public static final String KEY_SHA = "SHA";
public static final String ALGORITHM = "SHA-256";
/***
* SHA加密(比MD5更安全)
* @param data
* @return
* @throws Exception
*/
public static byte[] encryptSHA(byte[] data) throws Exception{
MessageDigest sha = MessageDigest.getInstance(KEY_SHA);
sha.update(data);
return sha.digest();
}
public static String SHAEncrypt(final String content) {
try {
MessageDigest sha = MessageDigest.getInstance(KEY_SHA);
byte[] sha_byte = sha.digest(content.getBytes());
StringBuffer hexValue = new StringBuffer();
for (byte b : sha_byte) {
//将其中的每个字节转成十六进制字符串:byte类型的数据最高位是符号位,通过和0xff进行与操作,转换为int类型的正整数。
String toHexString = Integer.toHexString(b & 0xff);
hexValue.append(toHexString.length() == 1 ? "0" + toHexString : toHexString);
}
return hexValue.toString();
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
//SHA-256加密
public static String SHA256Encrypt(String sourceStr) {
MessageDigest md = null;
try {
md = MessageDigest.getInstance(ALGORITHM);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
if (null != md) {
md.update(sourceStr.getBytes());
String digestStr = getDigestStr(md.digest());
return digestStr;
}
return null;
}
private static String getDigestStr(byte[] origBytes) {
String tempStr = null;
StringBuilder stb = new StringBuilder();
for (int i = 0; i < origBytes.length; i++) {
tempStr = Integer.toHexString(origBytes[i] & 0xff);
if (tempStr.length() == 1) {
stb.append("0");
}
stb.append(tempStr);
}
return stb.toString();
}
}
8.RSA 加密/解密
示例:
import com.sun.org.apache.xml.internal.security.utils.Base64;
import javax.crypto.Cipher;
import org.apache.commons.io.FileUtils;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.nio.charset.Charset;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
public class RsaUtil {
/**
* 生成密钥对并保存在本地文件中
*
* @param algorithm : 算法
* @param pubPath : 公钥保存路径
* @param priPath : 私钥保存路径
* @throws Exception
*/
private static void generateKeyToFile(String algorithm, String pubPath, String priPath) throws Exception {
// 获取密钥对生成器
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithm);
// 获取密钥对
KeyPair keyPair = keyPairGenerator.generateKeyPair();
// 获取公钥
PublicKey publicKey = keyPair.getPublic();
// 获取私钥
PrivateKey privateKey = keyPair.getPrivate();
// 获取byte数组
byte[] publicKeyEncoded = publicKey.getEncoded();
byte[] privateKeyEncoded = privateKey.getEncoded();
// 进行Base64编码
String publicKeyString = Base64.encode(publicKeyEncoded);
String privateKeyString = Base64.encode(privateKeyEncoded);
// 保存文件
FileUtils.writeStringToFile(new File(pubPath), publicKeyString, Charset.forName("UTF-8"));
FileUtils.writeStringToFile(new File(priPath), privateKeyString, Charset.forName("UTF-8"));
}
/**
* 从文件中加载公钥
*
* @param algorithm : 算法
* @param filePath : 文件路径
* @return : 公钥
* @throws Exception
*/
private static PublicKey loadPublicKeyFromFile(String algorithm, String filePath) throws Exception {
// 将文件内容转为字符串
String keyString = FileUtils.readFileToString(new File(filePath), Charset.forName("UTF-8"));
return loadPublicKeyFromString(algorithm, keyString);
}
/**
* 从字符串中加载公钥
*
* @param algorithm : 算法
* @param keyString : 公钥字符串
* @return : 公钥
* @throws Exception
*/
private static PublicKey loadPublicKeyFromString(String algorithm, String keyString) throws Exception {
// 进行Base64解码
byte[] decode = Base64.decode(keyString);
// 获取密钥工厂
KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
// 构建密钥规范
X509EncodedKeySpec keyspec = new X509EncodedKeySpec(decode);
// 获取公钥
return keyFactory.generatePublic(keyspec);
}
/**
* 从文件中加载私钥
*
* @param algorithm : 算法
* @param filePath : 文件路径
* @return : 私钥
* @throws Exception
*/
private static PrivateKey loadPrivateKeyFromFile(String algorithm, String filePath) throws Exception {
// 将文件内容转为字符串
String keyString = FileUtils.readFileToString(new File(filePath), Charset.forName("UTF-8"));
return loadPrivateKeyFromString(algorithm, keyString);
}
/**
* 从字符串中加载私钥
*
* @param algorithm : 算法
* @param keyString : 私钥字符串
* @return : 私钥
* @throws Exception
*/
private static PrivateKey loadPrivateKeyFromString(String algorithm, String keyString) throws Exception {
// 进行Base64解码
byte[] decode = Base64.decode(keyString);
// 获取密钥工厂
KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
// 构建密钥规范
PKCS8EncodedKeySpec keyspec = new PKCS8EncodedKeySpec(decode);
// 生成私钥
return keyFactory.generatePrivate(keyspec);
}
/**
* 使用密钥加密数据
*
* @param algorithm : 算法
* @param input : 原文
* @param key : 密钥
* @param maxEncryptSize : 最大加密长度(需要根据实际情况进行调整)
* @return : 密文
* @throws Exception
*/
private static String encrypt(String algorithm, String input, Key key, int maxEncryptSize) throws Exception {
// 获取Cipher对象
Cipher cipher = Cipher.getInstance(algorithm);
// 初始化模式(加密)和密钥
cipher.init(Cipher.ENCRYPT_MODE, key);
// 将原文转为byte数组
byte[] data = input.getBytes();
// 总数据长度
int total = data.length;
// 输出流
ByteArrayOutputStream baos = new ByteArrayOutputStream();
decodeByte(maxEncryptSize, cipher, data, total, baos);
// 对密文进行Base64编码
return Base64.encode(baos.toByteArray());
}
/**
* 解密数据
*
* @param algorithm : 算法
* @param encrypted : 密文
* @param key : 密钥
* @param maxDecryptSize : 最大解密长度(需要根据实际情况进行调整)
* @return : 原文
* @throws Exception
*/
private static String decrypt(String algorithm, String encrypted, Key key, int maxDecryptSize) throws Exception {
// 获取Cipher对象
Cipher cipher = Cipher.getInstance(algorithm);
// 初始化模式(解密)和密钥
cipher.init(Cipher.DECRYPT_MODE, key);
// 由于密文进行了Base64编码, 在这里需要进行解码
byte[] data = Base64.decode(encrypted);
// 总数据长度
int total = data.length;
// 输出流
ByteArrayOutputStream baos = new ByteArrayOutputStream();
decodeByte(maxDecryptSize, cipher, data, total, baos);
// 输出原文
return baos.toString();
}
/**
* 分段处理数据
*
* @param maxSize : 最大处理能力
* @param cipher : Cipher对象
* @param data : 要处理的byte数组
* @param total : 总数据长度
* @param baos : 输出流
* @throws Exception
*/
private static void decodeByte(int maxSize, Cipher cipher, byte[] data, int total, ByteArrayOutputStream baos) throws Exception {
// 偏移量
int offset = 0;
// 缓冲区
byte[] buffer;
// 如果数据没有处理完, 就一直继续
while (total - offset > 0) {
// 如果剩余的数据 >= 最大处理能力, 就按照最大处理能力来加密数据
if (total - offset >= maxSize) {
// 加密数据
buffer = cipher.doFinal(data, offset, maxSize);
// 偏移量向右侧偏移最大数据能力个
offset += maxSize;
} else {
// 如果剩余的数据 < 最大处理能力, 就按照剩余的个数来加密数据
buffer = cipher.doFinal(data, offset, total - offset);
// 偏移量设置为总数据长度, 这样可以跳出循环
offset = total;
}
// 向输出流写入数据
baos.write(buffer);
}
}
}
9.PBE 加密/解密
示例:
import java.security.Key;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
public class PBEUtil {
public static final String ALGORITHM = "PBEWITHMD5andDES";
public static final int ITERATION_COUNT = 100;
public static byte[] initSalt() throws Exception{
//实例化安全随机数
SecureRandom random = new SecureRandom();
return random.generateSeed(8);
}
/***
* 转换密钥
* @param password 密码
* @return 密钥
* @throws Exception
*/
private static Key toKey(String password) throws Exception{
//密钥材料
PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
//实例化
SecretKeyFactory factory = SecretKeyFactory.getInstance(ALGORITHM);
//生成密钥
return factory.generateSecret(keySpec);
}
/***
* 加密
* @param data 待加密数据
* @param password 密钥
* @param salt
* @return
* @throws Exception
*/
public static byte[] encrypt(byte[] data, String password, byte[] salt) throws Exception{
//转换密钥
Key key = toKey(password);
//实例化PBE参数材料
PBEParameterSpec spec = new PBEParameterSpec(salt, ITERATION_COUNT);
//实例化
Cipher cipher = Cipher.getInstance(ALGORITHM);
//初始化
cipher.init(Cipher.ENCRYPT_MODE, key, spec);
return cipher.doFinal(data);
}
/***
* 解密
* @param data 待解密数据
* @param password 密钥
* @param salt
* @return
* @throws Exception
*/
public static byte[] decrypt(byte[] data, String password, byte[] salt) throws Exception{
//转换密钥
Key key = toKey(password);
//实例化PBE参数材料
PBEParameterSpec spec = new PBEParameterSpec(salt, ITERATION_COUNT);
//实例化
Cipher cipher = Cipher.getInstance(ALGORITHM);
//初始化
cipher.init(Cipher.DECRYPT_MODE, key, spec);
//执行操作
return cipher.doFinal(data);
}
private static String showByteArray(byte[] data) {
if(null == data) {
return null;
}
StringBuilder sb = new StringBuilder();
for(byte b : data) {
sb.append(b).append(",");
}
sb.deleteCharAt(sb.length()-1);
sb.append("");
return sb.toString();
}
public static void main(String[] args) throws Exception{
byte[] salt = initSalt();
System.out.println("salt:"+showByteArray(salt));
String password = "1111";
System.out.println("口令:"+password);
String data = "PBE数据";
System.out.println("加密前数据:String:"+data);
System.out.println("加密前数据:byte[]:"+showByteArray(data.getBytes()));
byte[] encryptData = encrypt(data.getBytes(), password, salt);
System.out.println("加密后数据:byte[]:"+showByteArray(encryptData));
byte[] decryptData = decrypt(encryptData, password, salt);
System.out.println("解密后数据: byte[]:"+showByteArray(decryptData));
System.out.println("解密后数据: string:"+new String(decryptData));
}
}
本篇文章是某位网友整理的,感觉很好就先把重点摘抄过来了,感谢