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();
			// 创建一个空的八位数组,默认情况下为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代码中。

 



  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值