标签:android加密解密 文件加密解密 图片加密解密 语音加密解密
由于一个银行的项目需要,项目app的Android客户端和web端均需要对客户端上传至服务器的文件(语音、图片)代码如下:
/**
* 根据参数生成KEY
*/
public String getKey(String strKey) {
try {
byte[] keyByte = strKey.getBytes();
// 创建一个空的八位数组,默认情况下为0
byte[] byteTemp = new byte[8];
// 将用户指定的规则转换成八位数组
for (int i = 0; i < byteTemp.length && i < keyByte.length; i++) {
byteTemp[i] = keyByte[i];
}
return new SecretKeySpec(byteTemp, "DES");
} catch (Exception e) {
throw new RuntimeException(
"Error initializing SqlMap class. Cause: " + e);
}
}<span style="white-space:pre"> </span>// 加密文件
<span style="white-space:pre"> </span>public void encrypt(String file, String destFile) throws Exception {
Cipher cipher = Cipher.getInstance("DES");
// cipher.init(Cipher.ENCRYPT_MODE, getKey());
cipher.init(Cipher.ENCRYPT_MODE, this.key);
InputStream is = new FileInputStream(file);
OutputStream out = new FileOutputStream(destFile);
CipherInputStream cis = new CipherInputStream(is, cipher);
byte[] buffer = new byte[1024];
int r;
while ((r = cis.read(buffer)) > 0) {
out.write(buffer, 0, r);
}
cis.close();
is.close();
out.close();
File img2 = new File(file);
CommUtil.delete(img2);
}<span style="white-space:pre"> </span>// 解密文件,此为Android端的,web端加密手段也一样
<pre name="code" class="java"><span style="white-space:pre"> </span>public Bitmap decrypt(String file, String dest) throws Exception {
Bitmap bitmapOriginal = null;
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, this.key);
InputStream is = new FileInputStream(file);
OutputStream out = new FileOutputStream(dest);
CipherOutputStream cos = new CipherOutputStream(out, cipher);
byte[] buffer = new byte[1024];
int r;
while ((r = is.read(buffer)) >= 0) {
cos.write(buffer, 0, r);
}
cos.close();
out.close();
is.close();
InputStream openis = new FileInputStream(dest);
bitmapOriginal = BitmapFactory.decodeStream(openis);
openis.close();
File img2 = new File(dest);
CommUtil.delete(img2);
return bitmapOriginal;
}strKey就被发送至客户端。有些文件操作方式不需要和服务器一致的,这些strkey可以使用jni的方式写在c代码中。
标签:android加密解密 文件加密解密 图片加密解密 语音加密解密
原文地址:http://blog.csdn.net/andywuchuanlong/article/details/44055621