/** * 

* 公钥解密 *

* * @param encryptedData 已加密数据 * @param publicKey 公钥 (无需base64编码,靠,网上的代码为毛说要base64编码,坑啊哥哥们) * @return (已解决解密乱码问题) * @throws Exception */public static byte[] decryptByPublicKey(byte[] encryptedData,String publicKey ) throws Exception { X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); Key publicK = keyFactory.generatePublic(x509KeySpec); Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.DECRYPT_MODE, publicK); int inputLen = encryptedData.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; byte[] cache; int i = 0; // 对数据分段解密 while (inputLen - offSet > 0) { if (inputLen - offSet > MAX_DECRYPT_BLOCK) { cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK); } else { cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * MAX_DECRYPT_BLOCK; } byte[] decryptedData = out.toByteArray(); out.close(); return decryptedData;}
   
/** * 

* 公钥加密 *

* * @param data 源数据 * @param * @return * @throws Exception */public static byte[] encryptByPublicKey(byte[] data,String publicKey) throws Exception { byte[] keyBytes = Base64.decode(publicKey, Base64.DEFAULT); X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); Key publicK = keyFactory.generatePublic(x509KeySpec); // 对数据加密 Cipher cipher = Cipher.getInstance("RSA/None/PKCS1Padding"); cipher.init(Cipher.ENCRYPT_MODE, publicK); int inputLen = data.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; byte[] cache; int i = 0; // 对数据分段加密 while (inputLen - offSet > 0) { if (inputLen - offSet > MAX_ENCRYPT_BLOCK) { cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK); } else { cache = cipher.doFinal(data, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * MAX_ENCRYPT_BLOCK; } byte[] encryptedData = out.toByteArray(); out.close(); return encryptedData;}

   
注:本方法中base64为util包下  
 android.util.Base64;
另外:方法中公钥 为"ASDFG"这种  ,网上有好多公钥前后有---BIGIN   END—— 这种,在本文中并不适用。
本人菜鸟,不知道问什么,求告知

更多相关文章

  1. Android中对TextView中的部分内容的字体样式的设置方法
  2. Android下的JNI创建多线程的方法
  3. Android实现关机重启的方法
  4. Android(安卓)Intent Action 大全(转)
  5. Android(安卓)中与 Touch 事件详解
  6. android的SharedPreferences详解
  7. sharedPreferences的相关用法介绍
  8. 移动开发:Android(安卓)Media (Audio) Framework Analyse
  9. android fragment show hide回调

随机推荐

  1. android launch 初探
  2. Android短信转发默认不需要转发号码修改
  3. android中如何在代码中直接设置View的lay
  4. mount android yaffs image on ubuntu
  5. android 学习笔记有用代码片段(2)
  6. Android 实现旋转键盘的例子
  7. Android实现CoverFlow效果三
  8. android 中对xml 进行解析
  9. Android 平台如何获取程序的版本
  10. Android实现自动定位城市并获取天气信息