目录
- Java对称加密
- Cipher实现对称加密
- base64加解密
- 对称加密与非对称加密
- 对称加密
- 非对称加密
Java对称加密
Cipher实现对称加密
public class EncrypDES { | |
// 字符串默认键值 | |
private static String strDefaultKey = "asdasdasdasdzcxczxczx"; | |
//加密工具 | |
private Cipher encryptCipher = null; | |
// 解密工具 | |
private Cipher decryptCipher = null; | |
/** | |
* 默认构造方法,使用默认密钥 | |
*/ | |
public EncrypDES() throws Exception { | |
this(strDefaultKey); | |
} | |
/** | |
* 指定密钥构造方法 | |
* @param strKey 指定的密钥 | |
* @throws Exception | |
*/ | |
public EncrypDES(String strKey) throws Exception { | |
// Security.addProvider(new com.sun.crypto.provider.SunJCE()); | |
Key key = getKey(strKey.getBytes()); | |
encryptCipher = Cipher.getInstance("DES"); | |
encryptCipher.init(Cipher.ENCRYPT_MODE, key); | |
decryptCipher = Cipher.getInstance("DES"); | |
decryptCipher.init(Cipher.DECRYPT_MODE, key); | |
} | |
/** | |
* 将byte数组转换为表示进制值的字符串, 如:byte[]{8,18}转换为:0813,和public static byte[] | |
* | |
* hexStrByteArr(String strIn) 互为可逆的转换过程 | |
* | |
* @param arrB 需要转换的byte数组 | |
* @return 转换后的字符串 | |
* @throws Exception 本方法不处理任何异常,所有异常全部抛出 | |
*/ | |
public static String byteArrHexStr(byte[] arrB) throws Exception { | |
int iLen = arrB.length; | |
// 每个byte用个字符才能表示,所以字符串的长度是数组长度的2倍 | |
StringBuffer sb = new StringBuffer(iLen *); | |
for (int i =; i < iLen; i++) { | |
int intTmp = arrB[i]; | |
// 把负数转换为正数 | |
while (intTmp <) { | |
intTmp = intTmp +; | |
} | |
// 小于F的数需要在前面补0 | |
if (intTmp <) { | |
sb.append(""); | |
} | |
sb.append(Integer.toString(intTmp,)); | |
} | |
return sb.toString(); | |
} | |
/** | |
* 将表示进制值的字符串转换为byte数组,和public static String byteArr2HexStr(byte[] arrB) | |
* 互为可逆的转换过程 | |
* @param strIn 需要转换的字符串 | |
* @return 转换后的byte数组 | |
*/ | |
public static byte[] hexStrByteArr(String strIn) throws Exception { | |
byte[] arrB = strIn.getBytes(); | |
int iLen = arrB.length; | |
// 两个字符表示一个字节,所以字节数组长度是字符串长度除以 | |
byte[] arrOut = new byte[iLen /]; | |
for (int i =; i < iLen; i = i + 2) { | |
String strTmp = new String(arrB, i,); | |
arrOut[i /] = (byte) Integer.parseInt(strTmp, 16); | |
} | |
return arrOut; | |
} | |
/** | |
* | |
* 加密字节数组 | |
* @param arrB 需加密的字节数组 | |
* @return 加密后的字节数组 | |
*/ | |
public byte[] encrypt(byte[] arrB) throws Exception { | |
return encryptCipher.doFinal(arrB); | |
} | |
/** | |
* 加密字符串 | |
* @param strIn 需加密的字符串 | |
* @return 加密后的字符串 | |
*/ | |
public String encrypt(String strIn) throws Exception { | |
return byteArrHexStr(encrypt(strIn.getBytes())); | |
} | |
/** | |
* 解密字节数组 | |
* @param arrB 需解密的字节数组 | |
* @return 解密后的字节数组 | |
*/ | |
public byte[] decrypt(byte[] arrB) throws Exception { | |
return decryptCipher.doFinal(arrB); | |
} | |
/** | |
* 解密字符串 | |
* @param strIn 需解密的字符串 | |
* @return 解密后的字符串 | |
*/ | |
public String decrypt(String strIn) throws Exception { | |
return new String(decrypt(hexStrByteArr(strIn))); | |
} | |
/** | |
* 从指定字符串生成密钥,密钥所需的字节数组长度为位 不足8位时后面补0,超出8位只取前8位 | |
* @param arrBTmp 构成该字符串的字节数组 | |
* @return 生成的密钥 | |
*/ | |
private Key getKey(byte[] arrBTmp) throws Exception { | |
// 创建一个空的位字节数组(默认值为0) | |
byte[] arrB = new byte[]; | |
// 将原始字节数组转换为位 | |
for (int i =; i < arrBTmp.length && i < arrB.length; i++) { | |
arrB[i] = arrBTmp[i]; | |
} | |
// 生成密钥 | |
Key key = new javax.crypto.spec.SecretKeySpec(arrB, "DES"); | |
return key; | |
} | |
public static void main(String[] args) { | |
try { | |
String msg = "hello Cipher"; | |
EncrypDES des = new EncrypDES();// 使用默认密钥 | |
System.out.println("加密前的字符:" + msg); | |
System.out.println("加密后的字符:" + des.encrypt(msg1)); | |
System.out.println("解密后的字符:" + des.decrypt(des1.encrypt(msg1))); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
} |
运行main方法后得出结果是:
base64加解密
public class EncryptUtil { | |
/** | |
* BASE解密 | |
* @throws Exception | |
*/ | |
public static byte[] decryptBASE(String key) throws Exception { | |
return (new BASEDecoder()).decodeBuffer(key); | |
} | |
/** | |
* BASE加密 | |
*/ | |
public static String encryptBASE(byte[] key) throws Exception { | |
return (new BASEEncoder()).encodeBuffer(key); | |
} | |
public static void main(String[] args) throws Exception { | |
String ss = "b43bbde94982b71efad47eed9f82-234234324-123456"; | |
String encryptBASE = encryptBASE64(ss.getBytes()); | |
System.out.println(encryptBASE); | |
byte[] bytes = decryptBASE(encryptBASE64); | |
System.out.println(new String(bytes)); | |
} | |
} |
运行main方法得出的:
对称加密与非对称加密
加密方式大致分为两种,对称加密和非对称加密。对称加密是最快速、最简单的一种加密方式,加密(encryption)与解密(decryption)用的是同样的密钥(secret key)。非对称加密为数据的加密与解密提供了一个非常安全的方法,它使用了一对密钥,公钥(public key)和私钥(private key)。私钥只能由一方安全保管,不能外泄,而公钥则可以发给任何请求它的人。因此安全性大大提高。
对称加密
所谓对称加密算法即:加密和解密使用相同密钥的算法。常见的有DES、3DES、AES、PBE等加密算法,这几种算法安全性依次是逐渐增强的。
DES加密
DES是一种对称加密算法,是一种非常简便的加密算法,但是密钥长度比较短。DES加密算法出自IBM的研究,后来被美国正式采用,之后开始广泛流传,但是近些年使用越来越少,因为DES使用56位密钥,以现代计算能力,24小时内即可被破解。虽然如此,在某些简单应用中,我们还是可以使用DES加密算法.简单的DES加密算法实现:
import java.security.NoSuchAlgorithmException; | |
import java.security.SecureRandom; | |
import java.security.spec.InvalidKeySpecException; | |
import java.util.logging.Level; | |
import java.util.logging.Logger; | |
import javax.crypto.Cipher; | |
import javax.crypto.KeyGenerator; | |
import javax.crypto.SecretKey; | |
import javax.crypto.SecretKeyFactory; | |
import javax.crypto.spec.SecretKeySpec; | |
import org.apache.commons.codec.binary.Base; | |
public class DESUtil { | |
private static final String KEY_ALGORITHM = "DES"; | |
private static final String DEFAULT_CIPHER_ALGORITHM = "DES/ECB/PKCSPadding";// 默认的加密算法 | |
/** | |
* DES 加密操作 | |
* | |
* @param content | |
* 待加密内容 | |
* @param key | |
* 加密密钥 | |
* @return 返回Base转码后的加密数据 | |
*/ | |
public static String encrypt(String content, String key) { | |
try { | |
Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);// 创建密码器 | |
byte[] byteContent = content.getBytes("utf-"); | |
//初始化为加密模式的密码器 | |
//方法一 | |
//cipher.init(Cipher.DECRYPT_MODE, getSecretKey(key)); | |
//方法二 | |
cipher.init(Cipher.ENCRYPT_MODE, getSecretKeySpec(key)); | |
byte[] result = cipher.doFinal(byteContent);// 加密 | |
return Base.encodeBase64String(result);// 通过Base64转码返回 | |
} catch (Exception ex) { | |
Logger.getLogger(DESUtil.class.getName()).log(Level.SEVERE, null, ex); | |
} | |
return null; | |
} | |
/** | |
* DES 解密操作 | |
* | |
* @param content | |
* @param key | |
* @return | |
*/ | |
public static String decrypt(String content, String key) { | |
try { | |
// 实例化 | |
Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM); | |
// 使用密钥初始化,设置为解密模式 | |
//方法一 | |
//cipher.init(Cipher.DECRYPT_MODE, getSecretKey(key)); | |
//方法二 | |
cipher.init(Cipher.DECRYPT_MODE, getSecretKeySpec(key)); | |
// 执行操作 | |
byte[] result = cipher.doFinal(Base.decodeBase64(content)); | |
return new String(result, "utf-"); | |
} catch (Exception ex) { | |
Logger.getLogger(DESUtil.class.getName()).log(Level.SEVERE, null, ex); | |
} | |
return null; | |
} | |
/** | |
* 生成加密秘钥 | |
* | |
* @return | |
*/ | |
private static SecretKey getSecretKey(final String key) { | |
try { | |
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), KEY_ALGORITHM); | |
SecretKey sk = SecretKeyFactory.getInstance(KEY_ALGORITHM).generateSecret(keySpec); | |
return sk; | |
} catch (InvalidKeySpecException e) { | |
e.printStackTrace(); | |
} catch (NoSuchAlgorithmException e) { | |
e.printStackTrace(); | |
} | |
return null; | |
} | |
/** | |
* 生成加密秘钥 | |
* | |
* @return | |
*/ | |
private static SecretKeySpec getSecretKeySpec(final String key) { | |
// 返回生成指定算法密钥生成器的 KeyGenerator 对象 | |
KeyGenerator kg = null; | |
try { | |
kg = KeyGenerator.getInstance(KEY_ALGORITHM); | |
// DES 要求密钥长度为 | |
kg.init(, new SecureRandom(key.getBytes())); | |
// 生成一个密钥 | |
SecretKey secretKey = kg.generateKey(); | |
return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);// 转换为DES专用密钥 | |
} catch (NoSuchAlgorithmException ex) { | |
Logger.getLogger(DESUtil.class.getName()).log(Level.SEVERE, null, ex); | |
} | |
return null; | |
} | |
public static void main(String[] args) { | |
String content = "hello,您好"; | |
String key = "sde@f98H*^hsff%dfs$r344&df8543*er"; | |
System.out.println("content:" + content); | |
String s = DESUtil.encrypt(content, key); | |
System.out.println("s:" + s1); | |
System.out.println("s:" + DESUtil.decrypt(s1, key)); | |
} | |
} |
3DES加密
3DES是一种对称加密算法,在 DES 的基础上,使用三重数据加密算法,对数据进行加密,它相当于是对每个数据块应用三次 DES 加密算法。由于计算机运算能力的增强,原版 DES 密码的密钥长度变得容易被暴力 破 解;3DES 即是设计用来提供一种相对简单的方法,即通过增加 DES 的密钥长度来避免类似的攻击,而不是设计一种全新的块密码算法这样来说,破解的概率就小了很多。缺点由于使用了三重数据加密算法,可能会比较耗性能。简单的3DES加密算法实现:
import java.security.NoSuchAlgorithmException; | |
import java.security.SecureRandom; | |
import java.security.spec.InvalidKeySpecException; | |
import java.util.logging.Level; | |
import java.util.logging.Logger; | |
import javax.crypto.Cipher; | |
import javax.crypto.KeyGenerator; | |
import javax.crypto.SecretKey; | |
import javax.crypto.SecretKeyFactory; | |
import javax.crypto.spec.SecretKeySpec; | |
import org.apache.commons.codec.binary.Base; | |
public class TripDESUtil { | |
private static final String KEY_ALGORITHM = "DESede"; | |
private static final String DEFAULT_CIPHER_ALGORITHM = "DESede/ECB/PKCSPadding";// 默认的加密算法 | |
/** | |
* DESede 加密操作 | |
* | |
* @param content | |
* 待加密内容 | |
* @param key | |
* 加密密钥 | |
* @return 返回Base转码后的加密数据 | |
*/ | |
public static String encrypt(String content, String key) { | |
try { | |
Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);// 创建密码器 | |
byte[] byteContent = content.getBytes("utf-"); | |
//初始化为加密模式的密码器 | |
//方法一 | |
//cipher.init(Cipher.DECRYPT_MODE, getSecretKey(key)); | |
//方法二 | |
cipher.init(Cipher.ENCRYPT_MODE, getSecretKeySpec(key)); | |
byte[] result = cipher.doFinal(byteContent);// 加密 | |
return Base.encodeBase64String(result);// 通过Base64转码返回 | |
} catch (Exception ex) { | |
Logger.getLogger(TripDESUtil.class.getName()).log(Level.SEVERE, null, ex); | |
} | |
return null; | |
} | |
/** | |
* DESede 解密操作 | |
* | |
* @param content | |
* @param key | |
* @return | |
*/ | |
public static String decrypt(String content, String key) { | |
try { | |
// 实例化 | |
Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM); | |
// 使用密钥初始化,设置为解密模式 | |
//方法一 | |
//cipher.init(Cipher.DECRYPT_MODE, getSecretKey(key)); | |
//方法二 | |
cipher.init(Cipher.DECRYPT_MODE, getSecretKeySpec(key)); | |
// 执行操作 | |
byte[] result = cipher.doFinal(Base.decodeBase64(content)); | |
return new String(result, "utf-"); | |
} catch (Exception ex) { | |
Logger.getLogger(TripDESUtil.class.getName()).log(Level.SEVERE, null, ex); | |
} | |
return null; | |
} | |
/** | |
* 生成加密秘钥 | |
* | |
* @return | |
*/ | |
private static SecretKey getSecretKey(final String key) { | |
try { | |
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), KEY_ALGORITHM); | |
SecretKey sk = SecretKeyFactory.getInstance(KEY_ALGORITHM).generateSecret(keySpec); | |
return sk; | |
} catch (InvalidKeySpecException e) { | |
e.printStackTrace(); | |
} catch (NoSuchAlgorithmException e) { | |
e.printStackTrace(); | |
} | |
return null; | |
} | |
/** | |
* 生成加密秘钥 | |
* | |
* @return | |
*/ | |
private static SecretKeySpec getSecretKeySpec(final String key) { | |
// 返回生成指定算法密钥生成器的 KeyGenerator 对象 | |
KeyGenerator kg = null; | |
try { | |
kg = KeyGenerator.getInstance(KEY_ALGORITHM); | |
// DESede | |
kg.init(new SecureRandom(key.getBytes())); | |
// 生成一个密钥 | |
SecretKey secretKey = kg.generateKey(); | |
return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);// 转换为DESede专用密钥 | |
} catch (NoSuchAlgorithmException ex) { | |
Logger.getLogger(TripDESUtil.class.getName()).log(Level.SEVERE, null, ex); | |
} | |
return null; | |
} | |
public static void main(String[] args) { | |
String content = "hello,您好"; | |
String key = "sde@f98H*^hsff%dfs$r344&df8543*er"; | |
System.out.println("content:" + content); | |
String s = TripDESUtil.encrypt(content, key); | |
System.out.println("s:" + s1); | |
System.out.println("s:" + TripDESUtil.decrypt(s1, key)); | |
} | |
} |
AES加密
AES是一种对称加密算法,在 DES 的基础上,使用三重数据加密算法,对数据进行加密,它相当于是对每个数据块应用三次 DES 加密算法。由于计算机运算能力的增强,原版 DES 密码的密钥长度变得容易被暴力 破解;3DES 即是设计用来提供一种相对简单的方法,即通过增加 DES 的密钥长度来避免类似的攻击,而不是设计一种全新的块密码算法这样来说,破解的概率就小了很多。缺点由于使用了三重数据加密算法,可能会比较耗性能。简单的AES加密算法实现:
import java.security.NoSuchAlgorithmException; | |
import java.security.SecureRandom; | |
import java.security.spec.InvalidKeySpecException; | |
import java.util.logging.Level; | |
import java.util.logging.Logger; | |
import javax.crypto.Cipher; | |
import javax.crypto.KeyGenerator; | |
import javax.crypto.SecretKey; | |
import javax.crypto.SecretKeyFactory; | |
import javax.crypto.spec.SecretKeySpec; | |
import org.apache.commons.codec.binary.Base; | |
public class AESUtil { | |
private static final String KEY_ALGORITHM = "AES"; | |
private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCSPadding";//默认的加密算法 | |
/** | |
* AES 加密操作 | |
* | |
* @param content 待加密内容 | |
* @param key 加密密钥 | |
* @return 返回Base转码后的加密数据 | |
*/ | |
public static String encrypt(String content, String key) { | |
try { | |
Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);// 创建密码器 | |
byte[] byteContent = content.getBytes("utf-"); | |
//初始化为加密模式的密码器 | |
//方法一 | |
//cipher.init(Cipher.DECRYPT_MODE, getSecretKey(key)); | |
//方法二 | |
cipher.init(Cipher.ENCRYPT_MODE, getSecretKeySpec(key)); | |
byte[] result = cipher.doFinal(byteContent);// 加密 | |
return Base.encodeBase64String(result);//通过Base64转码返回 | |
} catch (Exception ex) { | |
Logger.getLogger(AESUtil.class.getName()).log(Level.SEVERE, null, ex); | |
} | |
return null; | |
} | |
/** | |
* AES 解密操作 | |
* | |
* @param content | |
* @param key | |
* @return | |
*/ | |
public static String decrypt(String content, String key) { | |
try { | |
//实例化 | |
Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM); | |
// 使用密钥初始化,设置为解密模式 | |
//方法一 | |
//cipher.init(Cipher.DECRYPT_MODE, getSecretKey(key)); | |
//方法二 | |
cipher.init(Cipher.DECRYPT_MODE, getSecretKeySpec(key)); | |
//执行操作 | |
byte[] result = cipher.doFinal(Base.decodeBase64(content)); | |
return new String(result, "utf-"); | |
} catch (Exception ex) { | |
Logger.getLogger(AESUtil.class.getName()).log(Level.SEVERE, null, ex); | |
} | |
return null; | |
} | |
/** | |
* 生成加密秘钥 | |
* | |
* @return | |
*/ | |
private static SecretKey getSecretKey(final String key) { | |
try { | |
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), KEY_ALGORITHM); | |
SecretKey sk = SecretKeyFactory.getInstance(KEY_ALGORITHM).generateSecret(keySpec); | |
return sk; | |
} catch (InvalidKeySpecException e) { | |
e.printStackTrace(); | |
} catch (NoSuchAlgorithmException e) { | |
e.printStackTrace(); | |
} | |
return null; | |
} | |
/** | |
* 生成加密秘钥 | |
* | |
* @return | |
*/ | |
private static SecretKeySpec getSecretKeySpec(final String key) { | |
//返回生成指定算法密钥生成器的 KeyGenerator 对象 | |
KeyGenerator kg = null; | |
try { | |
kg = KeyGenerator.getInstance(KEY_ALGORITHM); | |
//AES 要求密钥长度为 | |
kg.init(, new SecureRandom(key.getBytes())); | |
//生成一个密钥 | |
SecretKey secretKey = kg.generateKey(); | |
return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);// 转换为AES专用密钥 | |
} catch (NoSuchAlgorithmException ex) { | |
Logger.getLogger(AESUtil.class.getName()).log(Level.SEVERE, null, ex); | |
} | |
return null; | |
} | |
public static void main(String[] args) { | |
String content = "hello,您好"; | |
String key = "sde@f98H*^hsff%dfs$r344&df8543*er"; | |
System.out.println("content:" + content); | |
String s = AESUtil.encrypt(content, key); | |
System.out.println("s:" + s1); | |
System.out.println("s:"+AESUtil.decrypt(s1, key)); | |
} | |
} |
非对称加密
非对称加密算法需要两个密钥:公开密钥(publickey)和私有密钥(privatekey)。公开密钥与私有密钥是一对,如果用公开密钥对数据进行加密,只有用对应的私有密钥才能解密;如果用私有密钥对数据进行加密,那么只有用对应的公开密钥才能解密。一般公钥是公开的,私钥是自己保存。因为加密和解密使用的是两个不同的密钥,所以这种算法叫作非对称加密算法。安全性相对对称加密来说更高,是一种高级加密方式。
RSA加密
RSA是一种非对称加密算法.RSA有两个密钥,一个是公开的,称为公开密钥;一个是私密的,称为私密密钥。公开密钥是对大众公开的,私密密钥是服务器私有的,两者不能互推得出。用公开密钥对数据进行加密,私密密钥可解密;私密密钥对数据加密,公开密钥可解密。速度较对称加密慢。简单的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.Signature; | |
import java.security.interfaces.RSAPrivateKey; | |
import java.security.interfaces.RSAPublicKey; | |
import java.security.spec.PKCSEncodedKeySpec; | |
import java.security.spec.XEncodedKeySpec; | |
import java.util.HashMap; | |
import java.util.Map; | |
import javax.crypto.Cipher; | |
/** | |
* <p> | |
* RSA公钥/私钥/签名工具包 | |
* </p> | |
* <p> | |
* 字符串格式的密钥在未在特殊说明情况下都为BASE编码格式<br/> | |
* 由于非对称加密速度极其缓慢,一般文件不使用它来加密而是使用对称加密,<br/> | |
* 非对称加密算法可以用来对对称加密的密钥加密,这样保证密钥的安全也就保证了数据的安全 | |
* </p> | |
* | |
*/ | |
public class RSAUtils { | |
/** | |
* 加密算法RSA | |
*/ | |
public static final String KEY_ALGORITHM = "RSA"; | |
/** | |
* 签名算法 | |
*/ | |
public static final String SIGNATURE_ALGORITHM = "MDwithRSA"; | |
/** | |
* 获取公钥的key | |
*/ | |
private static final String PUBLIC_KEY = "RSAPublicKey"; | |
/** | |
* 获取私钥的key | |
*/ | |
private static final String PRIVATE_KEY = "RSAPrivateKey"; | |
/** | |
* RSA最大加密明文大小 | |
*/ | |
private static final int MAX_ENCRYPT_BLOCK =; | |
/** | |
* RSA最大解密密文大小 | |
*/ | |
private static final int MAX_DECRYPT_BLOCK =; | |
/** | |
* <p> | |
* 生成密钥对(公钥和私钥) | |
* </p> | |
* | |
* @return | |
* @throws Exception | |
*/ | |
public static Map<String, Object> genKeyPair() throws Exception { | |
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM); | |
keyPairGen.initialize(); | |
KeyPair keyPair = keyPairGen.generateKeyPair(); | |
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); | |
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); | |
Map<String, Object> keyMap = new HashMap<String, Object>(); | |
keyMap.put(PUBLIC_KEY, publicKey); | |
keyMap.put(PRIVATE_KEY, privateKey); | |
return keyMap; | |
} | |
/** | |
* <p> | |
* 用私钥对信息生成数字签名 | |
* </p> | |
* | |
* @param data 已加密数据 | |
* @param privateKey 私钥(BASE编码) | |
* | |
* @return | |
* @throws Exception | |
*/ | |
public static String sign(byte[] data, String privateKey) throws Exception { | |
byte[] keyBytes = BaseUtils.decode(privateKey); | |
PKCSEncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes); | |
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); | |
PrivateKey privateK = keyFactory.generatePrivate(pkcsKeySpec); | |
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM); | |
signature.initSign(privateK); | |
signature.update(data); | |
return BaseUtils.encode(signature.sign()); | |
} | |
/** | |
* <p> | |
* 校验数字签名 | |
* </p> | |
* | |
* @param data 已加密数据 | |
* @param publicKey 公钥(BASE编码) | |
* @param sign 数字签名 | |
* | |
* @return | |
* @throws Exception | |
* | |
*/ | |
public static boolean verify(byte[] data, String publicKey, String sign) | |
throws Exception { | |
byte[] keyBytes = BaseUtils.decode(publicKey); | |
XEncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes); | |
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); | |
PublicKey publicK = keyFactory.generatePublic(keySpec); | |
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM); | |
signature.initVerify(publicK); | |
signature.update(data); | |
return signature.verify(BaseUtils.decode(sign)); | |
} | |
/** | |
* <P> | |
* 私钥解密 | |
* </p> | |
* | |
* @param encryptedData 已加密数据 | |
* @param privateKey 私钥(BASE编码) | |
* @return | |
* @throws Exception | |
*/ | |
public static byte[] decryptByPrivateKey(byte[] encryptedData, String privateKey) | |
throws Exception { | |
byte[] keyBytes = BaseUtils.decode(privateKey); | |
PKCSEncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes); | |
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); | |
Key privateK = keyFactory.generatePrivate(pkcsKeySpec); | |
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); | |
cipher.init(Cipher.DECRYPT_MODE, privateK); | |
int inputLen = encryptedData.length; | |
ByteArrayOutputStream out = new ByteArrayOutputStream(); | |
int offSet =; | |
byte[] cache; | |
int i =; | |
// 对数据分段解密 | |
while (inputLen - offSet >) { | |
if (inputLen - offSet > MAX_DECRYPT_BLOCK) { | |
cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK); | |
} else { | |
cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet); | |
} | |
out.write(cache,, cache.length); | |
i++; | |
offSet = i * MAX_DECRYPT_BLOCK; | |
} | |
byte[] decryptedData = out.toByteArray(); | |
out.close(); | |
return decryptedData; | |
} | |
/** | |
* <p> | |
* 公钥解密 | |
* </p> | |
* | |
* @param encryptedData 已加密数据 | |
* @param publicKey 公钥(BASE编码) | |
* @return | |
* @throws Exception | |
*/ | |
public static byte[] decryptByPublicKey(byte[] encryptedData, String publicKey) | |
throws Exception { | |
byte[] keyBytes = BaseUtils.decode(publicKey); | |
XEncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); | |
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); | |
Key publicK = keyFactory.generatePublic(xKeySpec); | |
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); | |
cipher.init(Cipher.DECRYPT_MODE, publicK); | |
int inputLen = encryptedData.length; | |
ByteArrayOutputStream out = new ByteArrayOutputStream(); | |
int offSet =; | |
byte[] cache; | |
int i =; | |
// 对数据分段解密 | |
while (inputLen - offSet >) { | |
if (inputLen - offSet > MAX_DECRYPT_BLOCK) { | |
cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK); | |
} else { | |
cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet); | |
} | |
out.write(cache,, cache.length); | |
i++; | |
offSet = i * MAX_DECRYPT_BLOCK; | |
} | |
byte[] decryptedData = out.toByteArray(); | |
out.close(); | |
return decryptedData; | |
} | |
/** | |
* <p> | |
* 公钥加密 | |
* </p> | |
* | |
* @param data 源数据 | |
* @param publicKey 公钥(BASE编码) | |
* @return | |
* @throws Exception | |
*/ | |
public static byte[] encryptByPublicKey(byte[] data, String publicKey) | |
throws Exception { | |
byte[] keyBytes = BaseUtils.decode(publicKey); | |
XEncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); | |
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); | |
Key publicK = keyFactory.generatePublic(xKeySpec); | |
// 对数据加密 | |
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); | |
cipher.init(Cipher.ENCRYPT_MODE, publicK); | |
int inputLen = data.length; | |
ByteArrayOutputStream out = new ByteArrayOutputStream(); | |
int offSet =; | |
byte[] cache; | |
int i =; | |
// 对数据分段加密 | |
while (inputLen - offSet >) { | |
if (inputLen - offSet > MAX_ENCRYPT_BLOCK) { | |
cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK); | |
} else { | |
cache = cipher.doFinal(data, offSet, inputLen - offSet); | |
} | |
out.write(cache,, cache.length); | |
i++; | |
offSet = i * MAX_ENCRYPT_BLOCK; | |
} | |
byte[] encryptedData = out.toByteArray(); | |
out.close(); | |
return encryptedData; | |
} | |
/** | |
* <p> | |
* 私钥加密 | |
* </p> | |
* | |
* @param data 源数据 | |
* @param privateKey 私钥(BASE编码) | |
* @return | |
* @throws Exception | |
*/ | |
public static byte[] encryptByPrivateKey(byte[] data, String privateKey) | |
throws Exception { | |
byte[] keyBytes = BaseUtils.decode(privateKey); | |
PKCSEncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes); | |
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); | |
Key privateK = keyFactory.generatePrivate(pkcsKeySpec); | |
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); | |
cipher.init(Cipher.ENCRYPT_MODE, privateK); | |
int inputLen = data.length; | |
ByteArrayOutputStream out = new ByteArrayOutputStream(); | |
int offSet =; | |
byte[] cache; | |
int i =; | |
// 对数据分段加密 | |
while (inputLen - offSet >) { | |
if (inputLen - offSet > MAX_ENCRYPT_BLOCK) { | |
cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK); | |
} else { | |
cache = cipher.doFinal(data, offSet, inputLen - offSet); | |
} | |
out.write(cache,, cache.length); | |
i++; | |
offSet = i * MAX_ENCRYPT_BLOCK; | |
} | |
byte[] encryptedData = out.toByteArray(); | |
out.close(); | |
return encryptedData; | |
} | |
/** | |
* <p> | |
* 获取私钥 | |
* </p> | |
* | |
* @param keyMap 密钥对 | |
* @return | |
* @throws Exception | |
*/ | |
public static String getPrivateKey(Map<String, Object> keyMap) | |
throws Exception { | |
Key key = (Key) keyMap.get(PRIVATE_KEY); | |
return BaseUtils.encode(key.getEncoded()); | |
} | |
/** | |
* <p> | |
* 获取公钥 | |
* </p> | |
* | |
* @param keyMap 密钥对 | |
* @return | |
* @throws Exception | |
*/ | |
public static String getPublicKey(Map<String, Object> keyMap) throws Exception { | |
Key key = (Key) keyMap.get(PUBLIC_KEY); | |
return BaseUtils.encode(key.getEncoded()); | |
} | |
} | |
import java.io.ByteArrayInputStream; | |
import java.io.ByteArrayOutputStream; | |
import java.io.File; | |
import java.io.FileInputStream; | |
import java.io.FileOutputStream; | |
import java.io.InputStream; | |
import java.io.OutputStream; | |
import com.sun.org.apache.xml.internal.security.utils.Base; | |
public class BaseUtils { | |
/** | |
* 文件读取缓冲区大小 | |
*/ | |
private static final int CACHE_SIZE =; | |
/** | |
* <p> | |
* BASE字符串解码为二进制数据 | |
* </p> | |
* | |
* @param base | |
* @return | |
* @throws Exception | |
*/ | |
public static byte[] decode(String base) throws Exception { | |
return Base.decode(base64.getBytes()); | |
} | |
/** | |
* <p> | |
* 二进制数据编码为BASE字符串 | |
* </p> | |
* | |
* @param bytes | |
* @return | |
* @throws Exception | |
*/ | |
public static String encode(byte[] bytes) throws Exception { | |
return new String(Base.encode(bytes)); | |
} | |
/** | |
* <p> | |
* 将文件编码为BASE字符串 | |
* </p> | |
* <p> | |
* 大文件慎用,可能会导致内存溢出 | |
* </p> | |
* | |
* @param filePath | |
* 文件绝对路径 | |
* @return | |
* @throws Exception | |
*/ | |
public static String encodeFile(String filePath) throws Exception { | |
byte[] bytes = fileToByte(filePath); | |
return encode(bytes); | |
} | |
/** | |
* <p> | |
* BASE字符串转回文件 | |
* </p> | |
* | |
* @param filePath | |
* 文件绝对路径 | |
* @param base | |
* 编码字符串 | |
* @throws Exception | |
*/ | |
public static void decodeToFile(String filePath, String base) throws Exception { | |
byte[] bytes = decode(base); | |
byteArrayToFile(bytes, filePath); | |
} | |
/** | |
* <p> | |
* 文件转换为二进制数组 | |
* </p> | |
* | |
* @param filePath | |
* 文件路径 | |
* @return | |
* @throws Exception | |
*/ | |
public static byte[] fileToByte(String filePath) throws Exception { | |
byte[] data = new byte[]; | |
File file = new File(filePath); | |
if (file.exists()) { | |
FileInputStream in = new FileInputStream(file); | |
ByteArrayOutputStream out = new ByteArrayOutputStream(); | |
byte[] cache = new byte[CACHE_SIZE]; | |
int nRead =; | |
while ((nRead = in.read(cache)) != -) { | |
out.write(cache,, nRead); | |
out.flush(); | |
} | |
out.close(); | |
in.close(); | |
data = out.toByteArray(); | |
} | |
return data; | |
} | |
/** | |
* <p> | |
* 二进制数据写文件 | |
* </p> | |
* | |
* @param bytes | |
* 二进制数据 | |
* @param filePath | |
* 文件生成目录 | |
*/ | |
public static void byteArrayToFile(byte[] bytes, String filePath) throws Exception { | |
InputStream in = new ByteArrayInputStream(bytes); | |
File destFile = new File(filePath); | |
if (!destFile.getParentFile().exists()) { | |
destFile.getParentFile().mkdirs(); | |
} | |
destFile.createNewFile(); | |
OutputStream out = new FileOutputStream(destFile); | |
byte[] cache = new byte[CACHE_SIZE]; | |
int nRead =; | |
while ((nRead = in.read(cache)) != -) { | |
out.write(cache,, nRead); | |
out.flush(); | |
} | |
out.close(); | |
in.close(); | |
} | |
} |