Android、web中的圖片和語音的加密

來源:互聯網
上載者:User

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代碼中。




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.