package com.neusoft.phone.xinhua.newsedit.common;
import android.annotation.SuppressLint;
import android.os.Build;
import android.util.Base64;
import android.util.Log;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
/**
* Created by taibs on 2016/11/1.
*/
public class EncryptUtil {
private final static String ALGORITHM_AES = "AES";
private final static String ALGORITHM_RSA = "RSA/ECB/PKCS1Padding";
private final static String AES_HEX = "0123456789ABCDEF";
private final static int AES_KEYSIZE = 256;
/// AES加密解密 Start
/**
* AES加密
*
* @param key 密钥
* @param src 加密文件
* @return
* @throws Exception
*/
public static byte[] AESEncrypt(String key, byte[] src) throws Exception {
byte[] rawKey = getAESRawKey(key.getBytes());
SecretKeySpec skeySpec = new SecretKeySpec(rawKey, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(src);
return encrypted;
}
/// AES加密解密 Start
/**
* AES加密大文件
*
* @param key 密钥
* @return
* @throws Exception
*/
public static void AESEncryptLargeFile(String key, String filePath) throws Exception {
FileInputStream fis = null;
FileOutputStream fos = null;
fis = new FileInputStream(filePath);
byte[] oldByte = new byte[(int) filePath.length()];
fis.read(oldByte); // 读取
byte[] newByte = AESDecrypt(key, oldByte);
Log.i("加密后:",""+newByte);
// 加密
fos = new FileOutputStream(filePath);
fos.write(newByte);
}
/**
* AES解密
*
* @param key 密钥
* @return
* @throws Exception
*/
public static void AESDecryptLargeFile(String key, String oldFile) throws Exception {
FileInputStream fis = null;
FileOutputStream fos = null;
byte[] oldByte = new byte[(int) oldFile.length()];
try {
fis = new FileInputStream(oldFile);
fis.read(oldByte);
byte[] newByte = AESDecrypt(key, oldByte);
// 解密
fos = new FileOutputStream(oldFile);
fos.write(newByte);
}catch (Exception e){}
}
/**
* AES加密
*
* @param key 密钥
* @param src 加密文本
* @return
* @throws Exception
*/
public static String AESEncrypt(String key, String src) throws Exception {
byte[] rawKey = getAESRawKey(key.getBytes());
SecretKeySpec skeySpec = new SecretKeySpec(rawKey, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(src.getBytes());
return toHex(encrypted);
}
/**
* AES解密
*
* @param key 密钥
* @param encrypted 待揭秘文件
* @return
* @throws Exception
*/
public static byte[] AESDecrypt(String key, byte[] encrypted) throws Exception {
byte[] rawKey = getAESRawKey(key.getBytes());
byte[] enc = encrypted;
SecretKeySpec skeySpec = new SecretKeySpec(rawKey, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(enc);
byte[] decrypted1 = cipher.doFinal(enc);
return decrypted;
}
/**
* AES解密
*
* @param key 密钥
* @param encrypted 待揭秘文本
* @return
* @throws Exception
*/
public static String AESDecrypt(String key, String encrypted) throws Exception {
byte[] rawKey = getAESRawKey(key.getBytes());
byte[] enc = toByte(encrypted);
SecretKeySpec skeySpec = new SecretKeySpec(rawKey, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(enc);
return new String(decrypted);
}
/**
* AES解密
*
* @param key 密钥
* @param encrypted 待揭秘文本
* @return
* @throws Exception
*/
public static byte[] AESDecrypt_byte(String key, String encrypted) throws Exception {
byte[] rawKey = getAESRawKey(key.getBytes());
byte[] enc = toByte(encrypted);
SecretKeySpec skeySpec = new SecretKeySpec(rawKey, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(enc);
return decrypted;
}
/**
* AES 获取256位的加密密钥
*
* @param seed
* @return
* @throws Exception
*/
@SuppressLint("TrulyRandom")
private static byte[] getAESRawKey(byte[] seed) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom sr = null;
// 在4.2以上版本中,SecureRandom获取方式发生了改变
if (android.os.Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN) {
sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
} else {
sr = SecureRandom.getInstance("SHA1PRNG");
}
sr.setSeed(seed);
// 256 bits or 128 bits,192bits
kgen.init(AES_KEYSIZE, sr);
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
return raw;
}
public static String toHex(String txt) {
return toHex(txt.getBytes());
}
public static String fromHex(String hex) {
return new String(toByte(hex));
}
public static byte[] toByte(String hexString) {
int len = hexString.length() / 2;
byte[] result = new byte[len];
for (int i = 0; i < len; i++)
result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2),
16).byteValue();
return result;
}
public static String toHex(byte[] buf) {
if (buf == null)
return "";
StringBuffer result = new StringBuffer(2 * buf.length);
for (int i = 0; i < buf.length; i++) {
appendHex(result, buf[i]);
}
return result.toString();
}
private static void appendHex(StringBuffer sb, byte b) {
sb.append(AES_HEX.charAt((b >> 4) & 0x0f)).append(AES_HEX.charAt(b & 0x0f));
}
/// AES加密解密 End
/// RSA加密解密 Start
/**
* 随机生成RSA密钥对(默认密钥长度为1024)
*
* @return
*/
public static KeyPair generateRSAKeyPair() {
return generateRSAKeyPair(1024);
}
/**
* 随机生成RSA密钥对
*
* @param keyLength 密钥长度,范围:512~2048
*
* 一般1024
* @return
*/
public static KeyPair generateRSAKeyPair(int keyLength) {
try {
KeyPairGenerator kpg = KeyPairGenerator.getInstance(ALGORITHM_RSA);
kpg.initialize(keyLength);
return kpg.genKeyPair();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
/**
* 用公钥加密
*
* 每次加密的字节数,不能超过密钥的长度值减去11
*
* @param plainData 需加密数据的String数据
* @param publicKey 公钥
* @return 加密后的数据
*/
public static String RSAEncrypt(String plainData, PublicKey publicKey) {
try {
Cipher cipher = Cipher.getInstance(ALGORITHM_RSA);
// 编码前设定编码方式及密钥
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] output = cipher.doFinal(plainData.getBytes("utf-8"));
// 必须先encode成 byte[],再转成encodeToString,否则服务器解密会失败
byte[] encode = Base64.encode(output, Base64.DEFAULT);
return Base64.encodeToString(encode, Base64.DEFAULT);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 用私钥解密
*
* @param encryptdData 经过RSA加密的数据
* @param privateKey 私钥
* @return 解密后的数据
*/
public static String RSADecrypt(String encryptdData, PrivateKey privateKey) {
try {
Cipher cipher = Cipher.getInstance(ALGORITHM_RSA);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] byteDate = cipher.doFinal(Base64.decode(encryptdData, Base64.DEFAULT));
return new String(byteDate);
} catch (Exception e) {
return null;
}
}
/**
* 通过公钥byte[](publicKey.getEncoded())将公钥还原,适用于RSA算法
*
* @param keyBytes
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
public static PublicKey getRSAPublicKey(byte[] keyBytes) throws NoSuchAlgorithmException,
InvalidKeySpecException {
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM_RSA);
PublicKey publicKey = keyFactory.generatePublic(keySpec);
return publicKey;
}
/**
* 通过私钥byte[]将公钥还原,适用于RSA算法
*
* @param keyBytes
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
public static PrivateKey getRSAPrivateKey(byte[] keyBytes) throws NoSuchAlgorithmException,
InvalidKeySpecException {
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM_RSA);
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
return privateKey;
}
/**
* 使用N、e值还原公钥
*
* @param modulus
* @param publicExponent
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
public static PublicKey getRSAPublicKey(String modulus, String publicExponent)
throws NoSuchAlgorithmException, InvalidKeySpecException {
BigInteger bigIntModulus = new BigInteger(modulus);
BigInteger bigIntPrivateExponent = new BigInteger(publicExponent);
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(bigIntModulus, bigIntPrivateExponent);
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM_RSA);
PublicKey publicKey = keyFactory.generatePublic(keySpec);
return publicKey;
}
/**
* 使用N、d值还原私钥
*
* @param modulus
* @param privateExponent
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
public static PrivateKey getRSAPrivateKey(String modulus, String privateExponent)
throws NoSuchAlgorithmException, InvalidKeySpecException {
BigInteger bigIntModulus = new BigInteger(modulus);
BigInteger bigIntPrivateExponent = new BigInteger(privateExponent);
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(bigIntModulus, bigIntPrivateExponent);
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM_RSA);
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
return privateKey;
}
/**
* 从字符串中加载公钥
*
* @param publicKeyStr 公钥数据字符串
* @throws Exception 加载公钥时产生的异常
*/
public static PublicKey loadRSAPublicKey(String publicKeyStr) throws NoSuchAlgorithmException, InvalidKeySpecException {
byte[] buffer = Base64.decode(publicKeyStr, Base64.DEFAULT);
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM_RSA);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
return (RSAPublicKey) keyFactory.generatePublic(keySpec);
}
/**
* 从字符串中加载私钥
*
* 加载时使用的是PKCS8EncodedKeySpec(PKCS#8编码的Key指令)。
*
* @param privateKeyStr
* @return
* @throws Exception
*/
public static PrivateKey loadRSAPrivateKey(String privateKeyStr) throws NoSuchAlgorithmException, InvalidKeySpecException {
byte[] buffer = Base64.decode(privateKeyStr, Base64.DEFAULT);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM_RSA);
return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
}
/**
* 从文件中输入流中加载公钥
*
* @param in 公钥输入流
* @throws Exception 加载公钥时产生的异常
*/
public static PublicKey loadRSAPublicKey(InputStream in) throws IOException, NullPointerException, NoSuchAlgorithmException, InvalidKeySpecException {
return loadRSAPublicKey(readRSAKey(in));
}
/**
* 从文件中加载私钥
*
* @param in 私钥文件名
* @return 是否成功
* @throws Exception
*/
public static PrivateKey loadRSAPrivateKey(InputStream in) throws IOException, NullPointerException, NoSuchAlgorithmException, InvalidKeySpecException {
return loadRSAPrivateKey(readRSAKey(in));
}
/**
* 读取密钥信息
*
* @param in
* @return
* @throws IOException
*/
private static String readRSAKey(InputStream in) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String readLine = null;
StringBuilder sb = new StringBuilder();
while ((readLine = br.readLine()) != null) {
if (readLine.charAt(0) == '-') {
continue;
} else {
sb.append(readLine);
sb.append('\r');
}
}
return sb.toString();
}
}