最近用到了 andorid 端的 RSA 网上很多都是过时的方法 什么Base64doecde 都找不到这些方法,专门引用了jar包又有jar冲突,
最后整理出新的api 的加密方法 方法如下(请直接复制粘贴使用):
/*** RSA加密过程** @param* @param plainTextData 明文数据* @return* @throws Exception 加密过程中的异常信息*/public static byte[] encrypt(byte[] plainTextData) throws Exception {Cipher cipher;RSAPublicKey publicKey;try {byte[] buffer = Base64.decode("这里是服务端给的公钥",Base64.DEFAULT);KeyFactory keyFactory = KeyFactory.getInstance("RSA");X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);publicKey = (RSAPublicKey) keyFactory.generatePublic(keySpec);} catch (NoSuchAlgorithmException e) {throw new Exception("无此算法");} catch (InvalidKeySpecException e) {throw new Exception("公钥非法");} catch (NullPointerException e) {throw new Exception("公钥数据为空");}try {cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");cipher.init(Cipher.ENCRYPT_MODE, publicKey);return cipher.doFinal(plainTextData);} catch (NoSuchAlgorithmException e) {throw new Exception("无此加密算法");} catch (NoSuchPaddingException e) {e.printStackTrace();return null;} catch (InvalidKeyException e) {throw new Exception("加密公钥非法,请检查");} catch (IllegalBlockSizeException e) {throw new Exception("明文长度非法");} catch (BadPaddingException e) {throw new Exception("明文数据已损坏");}
}
上面的方法 可以拿到一个 byte类型
转成字符串的方法如下:
Base64.encodeToString(MyRSAUtil.encrypt(“加密的原始数据”).getBytes(), Base64.DEFAULT)
最后 导入的 包是
import android.util.Base64;
不是
import java.util.Base64;