Android、web中的圖片和語音的加密
由於一個銀行的項目需要,項目app的Android用戶端和web端均需要對用戶端上傳至伺服器的檔案(語音、圖片)
進行加密。加密實現方式是使用javax.crypto包中提供的類,這些類中最主要的是Cipher類。
Android項目中實現的步驟如下:
1、根據我們指定的strkey產生一個用於加密解密的key
2、加密檔案,根據key加密檔案
3、解密檔案,根據key解密檔案
代碼如下:
/** * 根據參數產生KEY */public String getKey(String strKey) {try {byte[] keyByte = strKey.getBytes();// 建立一個空的八位元組,預設情況下為0byte[] 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);}}
// 加密檔案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);}
// 解密檔案,此為Android端的,web端加密手段也一樣
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代碼中。