您的位置:首页 > 移动开发 > Android开发

Android常用工具之加密方式

2017-07-19 10:08 501 查看
公司中很多文件需要加密,但是每个公司的加密方式也不相同,基础的代码是相同的。

首先定义加密方式:

private final static byte[] rawkey = new byte[]{ };
private final static byte[] iv = new byte[]{};


加密解密过程
//加密
private static byte[] encrypt(byte[] clear) throws GeneralSecurityException {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(rawkey, "AES"), new IvParameterSpec(iv));
return cipher.doFinal(clear);
}
//解密
private static byte[] decrypt(byte[] encrypted) throws GeneralSecurityException {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(rawkey, "AES"), new IvParameterSpec(iv));
return cipher.doFinal(encrypted);
}
//解密
public static void decrypt(String fileInputPath, String fileOutputPath) throws GeneralSecurityException {
FileInputStream fis = null;
FileOutputStream fw = null;
try {
fis = new FileInputStream(fileInputPath);
fw = new FileOutputStream(fileOutputPath);

byte[] bytes = new byte[fis.available()];
fis.read(bytes);

fw.write(decrypt(bytes));
fw.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null) fis.close();
if (fw != null) fw.close();
} catch (IOException ignored) {
}
}
}
//加密
public static void encrypt(String fileInputPath, String fileOutputPath) throws GeneralSecurityException {
FileInputStream fr = null;
FileOutputStream fos = null;
try {
File f = new File(fileInputPath);
fr = new FileInputStream(f);
byte[] bytes = new byte[(int) f.length()];
fr.read(bytes, 0, bytes.length);
fos = new FileOutputStream(fileOutputPath);
fos.write(encrypt(bytes));
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fr != null) fr.close();
if (fos != null) fos.close();
} catch (IOException ignored) {
}
}
}
//解密
public static String decrypt(String fileInputPath) throws GeneralSecurityException {
FileInputStream fis = null;
String ret = null;
try {
fis = new FileInputStream(fileInputPath);

byte[] bytes = new byte[fis.available()];
fis.read(bytes);
ret = new String(decrypt(bytes));
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) try {
fis.close();
} catch (IOException ignored) {
}
}
return ret;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  解密 Android 工具类