由于一个银行的项目需要,项目app的Android客户端和web端均需要对客户端上传至服务器的文件(语音、图片)
进行加密。加密实现方式是使用javax.crypto包中提供的类,这些类中最主要的是Cipher类。
Android项目中实现的步骤如下:
1、根据我们指定的strkey生成一个用于加密解密的key
2、加密文件,根据key加密文件
3、解密文件,根据key解密文件
strKey是我们自己配置的,用于生成加密和解密的key,strkey为了安全起见和配置灵活,项目中是放在服务器中的,每当登陆Android客户端,
进行加密。加密实现方式是使用javax.crypto包中提供的类,这些类中最主要的是Cipher类。
Android项目中实现的步骤如下:
1、根据我们指定的strkey生成一个用于加密解密的key
2、加密文件,根据key加密文件
3、解密文件,根据key解密文件
代码如下:
/**
* 根据参数生成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);
}
}
</pre><pre name="code" class="java"><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);
}
</pre><pre name="code" class="java"><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是我们自己配置的,用于生成加密和解密的key,strkey为了安全起见和配置灵活,项目中是放在服务器中的,每当登陆Android客户端,
strKey就被发送至客户端。有些文件操作方式不需要和服务器一致的,这些strkey可以使用jni的方式写在c代码中。