android RSA公钥加密 公钥解密,解决乱码问题

/**
 * 

* 公钥解密 *

* * @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—— 这种,在本文中并不适用。
本人菜鸟,不知道问什么,求告知

你可能感兴趣的:(android)