java 加密工具类(MD5、RSA、AES等加密方式)
1.加密工具类encryption
MD5加密
- import org.apache.commons.codec.digest.DigestUtils;
- /**
- * MD5加密组件
- *
- * @author wbw
- * @version 1.0
- * @since 1.0
- */
- public abstract class MD5Util {
- /**
- * MD5加密
- *
- * @param data
- * 待加密数据
- * @return byte[] 消息摘要
- *
- * @throws Exception
- */
- public static byte[] encodeMD5(String data) throws Exception {
- // 执行消息摘要
- return DigestUtils.md5(data);
- }
- /**
- * MD5加密
- *
- * @param data
- * 待加密数据
- * @return byte[] 消息摘要
- *
- * @throws Exception
- */
- public static String encodeMD5Hex(String data) {
- // 执行消息摘要
- return DigestUtils.md5Hex(data);
- }
- }
import org.apache.commons.codec.digest.DigestUtils; /**
- MD5加密组件
- @author wbw
- @version 1.0
- @since 1.0
*/
public abstract class MD5Util { /**- MD5加密
- @param data
待加密数据
@return byte[] 消息摘要
@throws Exception
*/
public static byte[] encodeMD5(String data) throws Exception {// 执行消息摘要
return DigestUtils.md5(data);
}
/**
- MD5加密
- @param data
待加密数据
- @return byte[] 消息摘要
- @throws Exception
*/
public static String encodeMD5Hex(String data) {
// 执行消息摘要
return DigestUtils.md5Hex(data);
}
}
AES加密:
- import javax.crypto.Cipher;
- import javax.crypto.spec.SecretKeySpec;
- public class AESUtil {
- private static final String KEY_AES = "AES";
- public static String encrypt(String src, String key) throws Exception {
- if (key == null || key.length() != 16) {
- throw new Exception("key不满足条件");
- }
- byte[] raw = key.getBytes();
- SecretKeySpec skeySpec = new SecretKeySpec(raw, KEY_AES);
- Cipher cipher = Cipher.getInstance(KEY_AES);
- cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
- byte[] encrypted = cipher.doFinal(src.getBytes());
- return byte2hex(encrypted);
- }
- public static String decrypt(String src, String key) throws Exception {
- if (key == null || key.length() != 16) {
- throw new Exception("key不满足条件");
- }
- byte[] raw = key.getBytes();
- SecretKeySpec skeySpec = new SecretKeySpec(raw, KEY_AES);
- Cipher cipher = Cipher.getInstance(KEY_AES);
- cipher.init(Cipher.DECRYPT_MODE, skeySpec);
- byte[] encrypted1 = hex2byte(src);
- byte[] original = cipher.doFinal(encrypted1);
- String originalString = new String(original);
- return originalString;
- }
- public static byte[] hex2byte(String strhex) {
- if (strhex == null) {
- return null;
- }
- int l = strhex.length();
- if (l % 2 == 1) {
- return null;
- }
- byte[] b = new byte[l / 2];
- for (int i = 0; i != l / 2; i++) {
- b[i] = (byte) Integer.parseInt(strhex.substring(i * 2, i * 2 + 2),
- 16);
- }
- return b;
- }
- public static String byte2hex(byte[] b) {
- String hs = "";
- String stmp = "";
- for (int n = 0; n < b.length; n++) {
- stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
- if (stmp.length() == 1) {
- hs = hs + "0" + stmp;
- } else {
- hs = hs + stmp;
- }
- }
- return hs.toUpperCase();
- }
- }
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec; public class AESUtil {private static final String KEY_AES = "AES"; public static String encrypt(String src, String key) throws Exception {
if (key == null || key.length() != 16) {
throw new Exception("key不满足条件");
}
byte[] raw = key.getBytes();
SecretKeySpec skeySpec = new SecretKeySpec(raw, KEY_AES);
Cipher cipher = Cipher.getInstance(KEY_AES);
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(src.getBytes());
return byte2hex(encrypted);
} public static String decrypt(String src, String key) throws Exception {
if (key == null || key.length() != 16) {
throw new Exception("key不满足条件");
}
byte[] raw = key.getBytes();
SecretKeySpec skeySpec = new SecretKeySpec(raw, KEY_AES);
Cipher cipher = Cipher.getInstance(KEY_AES);
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] encrypted1 = hex2byte(src);
byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original);
return originalString;
} public static byte[] hex2byte(String strhex) {
if (strhex == null) {
return null;
}
int l = strhex.length();
if (l % 2 == 1) {
return null;
}
byte[] b = new byte[l / 2];
for (int i = 0; i != l / 2; i++) {
b[i] = (byte) Integer.parseInt(strhex.substring(i * 2, i * 2 + 2),
16);
}
return b;
} public static String byte2hex(byte[] b) {
String hs = "";
String stmp = "";
for (int n = 0; n < b.length; n++) {
stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
if (stmp.length() == 1) {
hs = hs + "0" + stmp;
} else {
hs = hs + stmp;
}
}
return hs.toUpperCase();
}
}
Base64加密:
- import org.apache.commons.codec.binary.Base64;
- /**
- * Base64组件
- *
- * @author wbw
- * @version 1.0
- * @since 1.0
- */
- public abstract class Base64Util {
- /**
- * 字符编码
- */
- public final static String ENCODING = "UTF-8";
- /**
- * Base64编码
- *
- * @param data 待编码数据
- * @return String 编码数据
- * @throws Exception
- */
- public static String encode(String data) throws Exception {
- // 执行编码
- byte[] b = Base64.encodeBase64(data.getBytes(ENCODING));
- return new String(b, ENCODING);
- }
- /**
- * Base64安全编码<br>
- * 遵循RFC 2045实现
- *
- * @param data
- * 待编码数据
- * @return String 编码数据
- *
- * @throws Exception
- */
- public static String encodeSafe(String data) throws Exception {
- // 执行编码
- byte[] b = Base64.encodeBase64(data.getBytes(ENCODING), true);
- return new String(b, ENCODING);
- }
- /**
- * Base64解码
- *
- * @param data 待解码数据
- * @return String 解码数据
- * @throws Exception
- */
- public static String decode(String data) throws Exception {
- // 执行解码
- byte[] b = Base64.decodeBase64(data.getBytes(ENCODING));
- return new String(b, ENCODING);
- }
- }
import org.apache.commons.codec.binary.Base64; /**
- Base64组件
- @author wbw
- @version 1.0
- @since 1.0
*/
public abstract class Base64Util { /**- 字符编码
*/
public final static String ENCODING = "UTF-8";
- Base64编码
- @param data 待编码数据
- @return String 编码数据
- @throws Exception
*/
public static String encode(String data) throws Exception { // 执行编码
byte[] b = Base64.encodeBase64(data.getBytes(ENCODING)); return new String(b, ENCODING);
}
- Base64安全编码<br>
- 遵循RFC 2045实现
- @param data
待编码数据
@return String 编码数据
@throws Exception
*/
public static String encodeSafe(String data) throws Exception {// 执行编码
byte[] b = Base64.encodeBase64(data.getBytes(ENCODING), true);return new String(b, ENCODING);
}
/**
Base64解码
@param data 待解码数据
@return String 解码数据
@throws Exception
*/
public static String decode(String data) throws Exception {// 执行解码
byte[] b = Base64.decodeBase64(data.getBytes(ENCODING));return new String(b, ENCODING);
}
- 字符编码
}
DES加密:
- import java.security.Key;
- import java.security.SecureRandom;
- import java.security.Security;
- import javax.crypto.Cipher;
- import javax.crypto.KeyGenerator;
- import javax.crypto.SecretKey;
- import javax.crypto.SecretKeyFactory;
- import javax.crypto.spec.DESKeySpec;
- import org.apache.commons.codec.binary.Base64;
- import org.bouncycastle.jce.provider.BouncyCastleProvider;
- /**
- * DES安全编码组件
- *
- * @author wbw
- * @version 1.0
- */
- public abstract class DESUtil {
- static{
- Security.insertProviderAt(new BouncyCastleProvider(), 1);
- }
- /**
- * 密钥算法 <br>
- * Java 6 只支持56bit密钥 <br>
- * Bouncy Castle 支持64bit密钥
- */
- public static final String KEY_ALGORITHM = "DES";
- /**
- * 加密/解密算法 / 工作模式 / 填充方式
- */
- public static final String CIPHER_ALGORITHM = "DES/ECB/PKCS5PADDING";
- /**
- * 转换密钥
- *
- * @param key
- * 二进制密钥
- * @return Key 密钥
- * @throws Exception
- */
- private static Key toKey(byte[] key) throws Exception {
- // 实例化DES密钥材料
- DESKeySpec dks = new DESKeySpec(key);
- // 实例化秘密密钥工厂
- SecretKeyFactory keyFactory = SecretKeyFactory
- .getInstance(KEY_ALGORITHM);
- // 生成秘密密钥
- SecretKey secretKey = keyFactory.generateSecret(dks);
- return secretKey;
- }
- /**
- * 解密
- *
- * @param data
- * 待解密数据
- * @param key
- * 密钥
- * @return byte[] 解密数据
- * @throws Exception
- */
- public static byte[] decrypt(byte[] data, byte[] key) throws Exception {
- // 还原密钥
- Key k = toKey(key);
- // 实例化
- Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
- // 初始化,设置为解密模式
- cipher.init(Cipher.DECRYPT_MODE, k);
- // 执行操作
- return cipher.doFinal(data);
- }
- /**
- * 加密
- *
- * @param data
- * 待加密数据
- * @param key
- * 密钥
- * @return byte[] 加密数据
- * @throws Exception
- */
- public static byte[] encrypt(byte[] data, byte[] key) throws Exception {
- // 还原密钥
- Key k = toKey(key);
- // 实例化
- Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
- // 初始化,设置为加密模式
- cipher.init(Cipher.ENCRYPT_MODE, k);
- // 执行操作
- return cipher.doFinal(data);
- }
- /**
- * 生成密钥 <br>
- * Java 6 只支持56bit密钥 <br>
- * Bouncy Castle 支持64bit密钥 <br>
- *
- * @return byte[] 二进制密钥
- * @throws Exception
- */
- public static byte[] initKey() throws Exception {
- /*
- * 实例化密钥生成器
- *
- * 若要使用64bit密钥注意替换 将下述代码中的KeyGenerator.getInstance(CIPHER_ALGORITHM);
- * 替换为KeyGenerator.getInstance(CIPHER_ALGORITHM, "BC");
- */
- KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
- /*
- * 初始化密钥生成器 若要使用64bit密钥注意替换 将下述代码kg.init(56); 替换为kg.init(64);
- */
- kg.init(56, new SecureRandom());
- // 生成秘密密钥
- SecretKey secretKey = kg.generateKey();
- // 获得密钥的二进制编码形式
- return secretKey.getEncoded();
- }
- public static byte[] initKey(String seed) throws Exception {
- KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
- SecureRandom secureRandom = new SecureRandom(new Base64().decode(seed));
- kg.init(secureRandom);
- SecretKey secretKey = kg.generateKey();
- return secretKey.getEncoded();
- }
- }
import java.security.Key;
import java.security.SecureRandom;
import java.security.Security; import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec; import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider; /**
- DES安全编码组件
- @author wbw
- @version 1.0
/
public abstract class DESUtil {
static{
Security.insertProviderAt(new BouncyCastleProvider(), 1);
}
/*- 密钥算法 <br>
- Java 6 只支持56bit密钥 <br>
- Bouncy Castle 支持64bit密钥
*/
public static final String KEY_ALGORITHM = "DES";
- 加密/解密算法 / 工作模式 / 填充方式
*/
public static final String CIPHER_ALGORITHM = "DES/ECB/PKCS5PADDING";
- 转换密钥
- @param key
二进制密钥
@return Key 密钥
@throws Exception
*/
private static Key toKey(byte[] key) throws Exception {// 实例化DES密钥材料
DESKeySpec dks = new DESKeySpec(key);// 实例化秘密密钥工厂
SecretKeyFactory keyFactory = SecretKeyFactory
.getInstance(KEY_ALGORITHM);// 生成秘密密钥
SecretKey secretKey = keyFactory.generateSecret(dks);return secretKey;
}
/**
解密
@param data
待解密数据
@param key
密钥
@return byte[] 解密数据
@throws Exception
*/
public static byte[] decrypt(byte[] data, byte[] key) throws Exception {// 还原密钥
Key k = toKey(key);// 实例化
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);// 初始化,设置为解密模式
cipher.init(Cipher.DECRYPT_MODE, k);// 执行操作
return cipher.doFinal(data);
}
/**
加密
@param data
待加密数据
@param key
密钥
@return byte[] 加密数据
@throws Exception
*/
public static byte[] encrypt(byte[] data, byte[] key) throws Exception {// 还原密钥
Key k = toKey(key);// 实例化
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);// 初始化,设置为加密模式
cipher.init(Cipher.ENCRYPT_MODE, k);// 执行操作
return cipher.doFinal(data);
}
/**
生成密钥 <br>
Java 6 只支持56bit密钥 <br>
Bouncy Castle 支持64bit密钥 <br>
@return byte[] 二进制密钥
@throws Exception
*/
public static byte[] initKey() throws Exception {/*
- 实例化密钥生成器
- 若要使用64bit密钥注意替换 将下述代码中的KeyGenerator.getInstance(CIPHER_ALGORITHM);
- 替换为KeyGenerator.getInstance(CIPHER_ALGORITHM, "BC");
*/
KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
/*
- 初始化密钥生成器 若要使用64bit密钥注意替换 将下述代码kg.init(56); 替换为kg.init(64);
*/
kg.init(56, new SecureRandom());
// 生成秘密密钥
SecretKey secretKey = kg.generateKey();// 获得密钥的二进制编码形式
return secretKey.getEncoded();
}
public static byte[] initKey(String seed) throws Exception {
KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
SecureRandom secureRandom = new SecureRandom(new Base64().decode(seed));
kg.init(secureRandom);
SecretKey secretKey = kg.generateKey();
return secretKey.getEncoded();
}
}
RSA加密:
- import java.io.ByteArrayOutputStream;
- import java.security.Key;
- import java.security.KeyFactory;
- import java.security.KeyPair;
- import java.security.KeyPairGenerator;
- import java.security.PrivateKey;
- import java.security.PublicKey;
- import java.security.SecureRandom;
- import java.security.Security;
- import java.security.interfaces.RSAPrivateKey;
- import java.security.interfaces.RSAPublicKey;
- import java.security.spec.PKCS8EncodedKeySpec;
- import java.security.spec.X509EncodedKeySpec;
- import java.util.HashMap;
- import java.util.Map;
- import java.util.UUID;
- import javax.crypto.Cipher;
- import org.bouncycastle.jce.provider.BouncyCastleProvider;
- import org.bouncycastle.util.encoders.Base64;
- /**
- * RSA安全编码组件
- *
- * @author wbw
- * @version 1.0
- */
- public class RSAUtil {
- /**
- * 非对称加密密钥算法
- */
- public static final String KEY_ALGORITHM_RSA = "RSA";
- /**
- * 公钥
- */
- private static final String RSA_PUBLIC_KEY = "RSAPublicKey";
- /**
- * 私钥
- */
- private static final String RSA_PRIVATE_KEY = "RSAPrivateKey";
- /**
- * RSA密钥长度
- * 默认1024位,
- * 密钥长度必须是64的倍数,
- * 范围在512至65536位之间。
- */
- private static final int KEY_SIZE = 1024;
- static{
- Security.insertProviderAt(new BouncyCastleProvider(), 1);
- }
- /**
- * 私钥解密
- *
- * @param data
- * 待解密数据
- * @param key
- * 私钥
- * @return byte[] 解密数据
- * @throws Exception
- */
- public static byte[] decryptByPrivateKey(byte[] data, byte[] key)
- throws Exception {
- // 取得私钥
- PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key);
- KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM_RSA);
- // 生成私钥
- PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
- // 对数据解密
- Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
- cipher.init(Cipher.DECRYPT_MODE, privateKey);
- int blockSize = cipher.getBlockSize();
- if(blockSize>0){
- ByteArrayOutputStream bout = new ByteArrayOutputStream(64);
- int j = 0;
- while (data.length - j * blockSize > 0) {
- bout.write(cipher.doFinal(data, j * blockSize, blockSize));
- j++;
- }
- return bout.toByteArray();
- }
- return cipher.doFinal(data);
- }
- /**
- * 公钥解密
- *
- * @param data
- * 待解密数据
- * @param key
- * 公钥
- * @return byte[] 解密数据
- * @throws Exception
- */
- public static byte[] decryptByPublicKey(byte[] data, byte[] key)
- throws Exception {
- // 取得公钥
- X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);
- KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM_RSA);
- // 生成公钥
- PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);
- // 对数据解密
- Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
- cipher.init(Cipher.DECRYPT_MODE, publicKey);
- return cipher.doFinal(data);
- }
- /**
- * 公钥加密
- *
- * @param data
- * 待加密数据
- * @param key
- * 公钥
- * @return byte[] 加密数据
- * @throws Exception
- */
- public static byte[] encryptByPublicKey(byte[] data, byte[] key)
- throws Exception {
- // 取得公钥
- X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);
- KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM_RSA);
- PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);
- // 对数据加密
- Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
- cipher.init(Cipher.ENCRYPT_MODE, publicKey);
- int blockSize = cipher.getBlockSize();
- if(blockSize>0){
- int outputSize = cipher.getOutputSize(data.length);
- int leavedSize = data.length % blockSize;
- int blocksSize = leavedSize != 0 ? data.length / blockSize + 1
- : data.length / blockSize;
- byte[] raw = new byte[outputSize * blocksSize];
- int i = 0,remainSize=0;
- while ((remainSize = data.length - i * blockSize) > 0) {
- int inputLen = remainSize > blockSize?blockSize:remainSize;
- cipher.doFinal(data, i * blockSize, inputLen, raw, i * outputSize);
- i++;
- }
- return raw;
- }
- return cipher.doFinal(data);
- }
- /**
- * 私钥加密
- *
- * @param data
- * 待加密数据
- * @param key
- * 私钥
- * @return byte[] 加密数据
- * @throws Exception
- */
- public static byte[] encryptByPrivateKey(byte[] data, byte[] key)
- throws Exception {
- // 取得私钥
- PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key);
- KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM_RSA);
- // 生成私钥
- PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
- // 对数据加密
- Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
- cipher.init(Cipher.ENCRYPT_MODE, privateKey);
- int blockSize = cipher.getBlockSize();
- if(blockSize>0){
- int outputSize = cipher.getOutputSize(data.length);
- int leavedSize = data.length % blockSize;
- int blocksSize = leavedSize != 0 ? data.length / blockSize + 1
- : data.length / blockSize;
- byte[] raw = new byte[outputSize * blocksSize];
- int i = 0,remainSize=0;
- while ((remainSize = data.length - i * blockSize) > 0) {
- int inputLen = remainSize > blockSize?blockSize:remainSize;
- cipher.doFinal(data, i * blockSize, inputLen, raw, i * outputSize);
- i++;
- }
- return raw;
- }
- return cipher.doFinal(data);
- }
- /**
- * 取得私钥
- *
- * @param keyMap
- * 密钥Map
- * @return key 私钥
- * @throws Exception
- */
- public static Key getPrivateKey(Map<String, Key> keyMap)
- throws Exception {
- return keyMap.get(RSA_PRIVATE_KEY);
- }
- /**
- * 取得私钥
- *
- * @param keyMap
- * 密钥Map
- * @return byte[] 私钥
- * @throws Exception
- */
- public static byte[] getPrivateKeyByte(Map<String, Key> keyMap)
- throws Exception {
- return keyMap.get(RSA_PRIVATE_KEY).getEncoded();
- }
- /**
- * 取得公钥
- *
- * @param keyMap
- * 密钥Map
- * @return key 公钥
- * @throws Exception
- */
- public static Key getPublicKey(Map<String, Key> keyMap)
- throws Exception {
- return keyMap.get(RSA_PUBLIC_KEY);
- }
- /**
- * 取得公钥
- *
- * @param keyMap
- * 密钥Map
- * @return byte[] 公钥
- * @throws Exception
- */
- public static byte[] getPublicKeyByte(Map<String, Key> keyMap)
- throws Exception {
- return keyMap.get(RSA_PUBLIC_KEY).getEncoded();
- }
- /**
- * 初始化密钥
- * @param byte[] seed 种子
- * @return Map 密钥Map
- * @throws Exception
- */
- public static Map<String,Key> initKey(byte[] seed)throws Exception{
- // 实例化密钥对生成器
- KeyPairGenerator keyPairGen = KeyPairGenerator
- .getInstance(KEY_ALGORITHM_RSA);
- // 初始化密钥对生成器
- keyPairGen.initialize(KEY_SIZE, new SecureRandom(seed) );
- // 生成密钥对
- KeyPair keyPair = keyPairGen.generateKeyPair();
- // 公钥
- RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
- // 私钥
- RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
- // 封装密钥
- Map<String, Key> keyMap = new HashMap<String, Key>(2);
- keyMap.put(RSA_PUBLIC_KEY, publicKey);
- keyMap.put(RSA_PRIVATE_KEY, privateKey);
- return keyMap;
- }
- /**
- * 初始化密钥
- * @param seed 种子
- * @return Map 密钥Map
- * @throws Exception
- */
- public static Map<String,Key> initKey(String seed)throws Exception{
- return initKey(seed.getBytes());
- }
- /**
- * 初始化密钥
- *
- * @return Map 密钥Map
- * @throws Exception
- */
- public static Map<String, Key> initKey() throws Exception {
- return initKey(UUID.randomUUID().toString().getBytes());
- }
- public static PublicKey getPublicRSAKey(String key) throws Exception {
- X509EncodedKeySpec x509 = new X509EncodedKeySpec(Base64.decode(key));
- KeyFactory kf = KeyFactory.getInstance(KEY_ALGORITHM_RSA);
- return kf.generatePublic(x509);
- }
- public static PrivateKey getPrivateRSAKey(String key) throws Exception {
- PKCS8EncodedKeySpec pkgs8 = new PKCS8EncodedKeySpec(Base64.decode(key));
- KeyFactory kf = KeyFactory.getInstance(KEY_ALGORITHM_RSA);
- return kf.generatePrivate(pkgs8);
- }
- }
import java.io.ByteArrayOutputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Security;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID; import javax.crypto.Cipher; import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Base64; /**
- RSA安全编码组件
- @author wbw
- @version 1.0
/
public class RSAUtil {
/*- 非对称加密密钥算法
*/
public static final String KEY_ALGORITHM_RSA = "RSA";
- 公钥
*/
private static final String RSA_PUBLIC_KEY = "RSAPublicKey";
- 私钥
*/
private static final String RSA_PRIVATE_KEY = "RSAPrivateKey";
- RSA密钥长度
- 默认1024位,
- 密钥长度必须是64的倍数,
- 范围在512至65536位之间。
*/
private static final int KEY_SIZE = 1024;
Security.insertProviderAt(new BouncyCastleProvider(), 1);
}
/**- 私钥解密
- @param data
待解密数据
@param key
私钥
@return byte[] 解密数据
@throws Exception
*/
public static byte[] decryptByPrivateKey(byte[] data, byte[] key)
throws Exception {// 取得私钥
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key);KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM_RSA);
// 生成私钥
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);// 对数据解密
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());cipher.init(Cipher.DECRYPT_MODE, privateKey);
int blockSize = cipher.getBlockSize();
if(blockSize>0){
ByteArrayOutputStream bout = new ByteArrayOutputStream(64);
int j = 0;
while (data.length - j * blockSize > 0) {
bout.write(cipher.doFinal(data, j * blockSize, blockSize));
j++;
}
return bout.toByteArray();
}
return cipher.doFinal(data);
}
/**
公钥解密
@param data
待解密数据
@param key
公钥
@return byte[] 解密数据
@throws Exception
*/
public static byte[] decryptByPublicKey(byte[] data, byte[] key)
throws Exception {// 取得公钥
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM_RSA);
// 生成公钥
PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);// 对数据解密
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());cipher.init(Cipher.DECRYPT_MODE, publicKey);
return cipher.doFinal(data);
}
/**
公钥加密
@param data
待加密数据
@param key
公钥
@return byte[] 加密数据
@throws Exception
*/
public static byte[] encryptByPublicKey(byte[] data, byte[] key)
throws Exception {// 取得公钥
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM_RSA);
PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);
// 对数据加密
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());cipher.init(Cipher.ENCRYPT_MODE, publicKey);
int blockSize = cipher.getBlockSize();
if(blockSize>0){
int outputSize = cipher.getOutputSize(data.length);
int leavedSize = data.length % blockSize;
int blocksSize = leavedSize != 0 ? data.length / blockSize + 1
: data.length / blockSize;
byte[] raw = new byte[outputSize * blocksSize];
int i = 0,remainSize=0;
while ((remainSize = data.length - i * blockSize) > 0) {
int inputLen = remainSize > blockSize?blockSize:remainSize;
cipher.doFinal(data, i * blockSize, inputLen, raw, i * outputSize);
i++;
}
return raw;
}
return cipher.doFinal(data);
}
/**
私钥加密
@param data
待加密数据
@param key
私钥
@return byte[] 加密数据
@throws Exception
*/
public static byte[] encryptByPrivateKey(byte[] data, byte[] key)
throws Exception {// 取得私钥
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key);KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM_RSA);
// 生成私钥
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);// 对数据加密
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());cipher.init(Cipher.ENCRYPT_MODE, privateKey);
int blockSize = cipher.getBlockSize();
if(blockSize>0){
int outputSize = cipher.getOutputSize(data.length);
int leavedSize = data.length % blockSize;
int blocksSize = leavedSize != 0 ? data.length / blockSize + 1
: data.length / blockSize;
byte[] raw = new byte[outputSize * blocksSize];
int i = 0,remainSize=0;
while ((remainSize = data.length - i * blockSize) > 0) {
int inputLen = remainSize > blockSize?blockSize:remainSize;
cipher.doFinal(data, i * blockSize, inputLen, raw, i * outputSize);
i++;
}
return raw;
}
return cipher.doFinal(data);
}
/**
- 取得私钥
- @param keyMap
密钥Map
- @return key 私钥
- @throws Exception
*/
public static Key getPrivateKey(Map<String, Key> keyMap)
throws Exception {
return keyMap.get(RSA_PRIVATE_KEY);
}
/**
- 取得私钥
- @param keyMap
密钥Map
- @return byte[] 私钥
- @throws Exception
*/
public static byte[] getPrivateKeyByte(Map<String, Key> keyMap)
throws Exception {
return keyMap.get(RSA_PRIVATE_KEY).getEncoded();
}
/**
- 取得公钥
- @param keyMap
密钥Map
- @return key 公钥
- @throws Exception
*/
public static Key getPublicKey(Map<String, Key> keyMap)
throws Exception {
return keyMap.get(RSA_PUBLIC_KEY);
}
/**
- 取得公钥
- @param keyMap
密钥Map
- @return byte[] 公钥
- @throws Exception
*/
public static byte[] getPublicKeyByte(Map<String, Key> keyMap)
throws Exception {
return keyMap.get(RSA_PUBLIC_KEY).getEncoded();
}
/**
初始化密钥
@param byte[] seed 种子
@return Map 密钥Map
@throws Exception
*/
public static Map<String,Key> initKey(byte[] seed)throws Exception{
// 实例化密钥对生成器
KeyPairGenerator keyPairGen = KeyPairGenerator
.getInstance(KEY_ALGORITHM_RSA);// 初始化密钥对生成器
keyPairGen.initialize(KEY_SIZE, new SecureRandom(seed) );// 生成密钥对
KeyPair keyPair = keyPairGen.generateKeyPair();// 公钥
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();// 私钥
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();// 封装密钥
Map<String, Key> keyMap = new HashMap<String, Key>(2);keyMap.put(RSA_PUBLIC_KEY, publicKey);
keyMap.put(RSA_PRIVATE_KEY, privateKey);return keyMap;
}
/**
- 初始化密钥
- @param seed 种子
- @return Map 密钥Map
- @throws Exception
*/
public static Map<String,Key> initKey(String seed)throws Exception{
return initKey(seed.getBytes());
}
/**
- 初始化密钥
- @return Map 密钥Map
- @throws Exception
*/
public static Map<String, Key> initKey() throws Exception {
return initKey(UUID.randomUUID().toString().getBytes());
}
public static PublicKey getPublicRSAKey(String key) throws Exception {
X509EncodedKeySpec x509 = new X509EncodedKeySpec(Base64.decode(key));
KeyFactory kf = KeyFactory.getInstance(KEY_ALGORITHM_RSA);
return kf.generatePublic(x509);
}public static PrivateKey getPrivateRSAKey(String key) throws Exception {
PKCS8EncodedKeySpec pkgs8 = new PKCS8EncodedKeySpec(Base64.decode(key));
KeyFactory kf = KeyFactory.getInstance(KEY_ALGORITHM_RSA);
return kf.generatePrivate(pkgs8);
} - 非对称加密密钥算法
}
java 加密工具类(MD5、RSA、AES等加密方式)的更多相关文章
- Java 关于密码处理的工具类[MD5编码][AES加密/解密]
项目中又遇到了加密问题,又去翻了半天,然后做测试,干脆就把常用的两类小结一下. 1.第一种所谓的MD5加密 其实也不算加密,只是基于Hash算法的不可逆编码而已,等于说,一旦经过MD5处理,是不可能从 ...
- Java AES 加密工具类
package com.microwisdom.utils; import java.security.NoSuchAlgorithmException; import java.security.S ...
- Java常用工具类之MD5加密
package com.wazn.learn.util; import java.security.MessageDigest; /** * MD5加密工具类 * <功能详细描述> * * ...
- 加密工具类 - CryptoUtils.java
加密工具类,包含MD5,BASE64,SHA,CRC32的加密与解密方法. 源码如下:(点击下载 - CryptoUtils.java.commons-io-2.4.jar.commons-code ...
- android开发MD5加密工具类(一)
MD5加密工具类整理: package com.gzcivil.utils; import java.io.UnsupportedEncodingException; import java.secu ...
- wemall app商城源码android开发MD5加密工具类
wemall-mobile是基于WeMall的android app商城,只需要在原商城目录下上传接口文件即可完成服务端的配置,客户端可定制修改.本文分享android开发MD5加密工具类主要代码,供 ...
- java MD5Utils 加密工具类
package com.sicdt.library.core.utils; import java.io.File; import java.io.FileInputStream; import ja ...
- AES采用CBC模式128bit加密工具类
写在前面 安全测试ECB模式过于简单需要改为CBC模式加密以下为工具类及测试 AESUtils.java package com.sgcc.mobile.utils; import sun.misc. ...
- spring自带的MD5加密工具类
Spring 自带的md5加密工具类,本来打算自己找一个工具类的,后来想起来Spring有自带的,就翻了翻 //导入包import org.springframework.util.DigestUti ...
随机推荐
- 剑指offer(50)数组中重复的数字
题目描述 在一个长度为n的数组里的所有数字都在0到n-1的范围内. 数组中某些数字是重复的,但不知道有几个数字是重复的.也不知道每个数字重复几次.请找出数组中任意一个重复的数字. 例如,如果输入长度为 ...
- luoguP1850 换教室
luoguP1850 换教室 链接 https://www.luogu.org/problemnew/show/P1850 思路 状态很显然就是f[n][k][0/1] 前i次,用了k次机会,当前是在 ...
- 论文笔记:A Structured Self-Attentive Sentence Embedding
A Structured Self-Attentive Sentence Embedding ICLR 2017 2018-08-19 14:07:29 Paper:https://arxiv.org ...
- Java三种注释
单行注释:// 注释内容 多行注释:/*... 注释内容....*/ 文本注释:/**.. 注释内容....*/ 这种注释可以用来自动地生成文档.在JDK中有个 ...
- Verification of Model Transformations A Survey of the State-of-the-Art 模型转换的验证 对现状的调查
模型驱动工程范式认为软件开发生命周期由工件(需求规范.分析和设计文档.测试套件.源代码)支持,这些工件是表示要构建的系统不同视图的模型.存在一个由模型转换驱动的(半)自动构造过程,从系统的抽象模型开始 ...
- JS模态框 简单案例
演示: <!doctype html> <html lang="en"> <head> <meta charset="UTF-8 ...
- MongoDB基本操作(包括插入、修改、子节点排序等)
一.基本操作 1.新增文章 db.article.insert({title:"今天天气很好",content:"我们一起去春游",_id:1}) 2.新增一条 ...
- LeetCode--038--报数(java)
报数序列是一个整数序列,按照其中的整数的顺序进行报数,得到下一个数.其前五项如下: 1. 1 2. 11 3. 21 4. 1211 5. 111221 1 被读作 "one 1" ...
- BFS 路径记录
有一迷宫 N*M,要求输出可通行的最短路径. 可以先倒着 BFS 一遍迷宫,这样 dis[] 数组储存的就是各点到迷宫终点的最短距离. 然后再从起点开始 BFS 一遍 dis[] ,只要满足 dis[ ...
- Bootstrap框架整理
bootstrap框架的介绍 栅格系统 bootstrap框架把整个浏览器的宽度分为12列,并能适配各种屏幕的尺寸大小进行相应的匹配,达到调节页面大小的效果. 首先需要放置一个容器div,class= ...