Android RSA公钥加密和私钥解密方法
生活随笔
收集整理的這篇文章主要介紹了
Android RSA公钥加密和私钥解密方法
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
一、公鑰加密過(guò)程
/*** RSA公鑰加密** @param str 加密字符串* @param publicKey 公鑰* @return 密文* @throws Exception 加密過(guò)程中的異常信息*/public static String encrypt(String str, String publicKey) throws Exception {//base64編碼的公鑰byte[] decoded = Base64.decodeBase64(publicKey.getBytes());RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));//RSA加密Cipher cipher = Cipher.getInstance("RSA");cipher.init(Cipher.ENCRYPT_MODE, pubKey); // String outStr = Base64.encodeBase64String(cipher.doFinal(str.getBytes("UTF-8")));return new String(Base64.encodeBase64(cipher.doFinal(str.getBytes("UTF-8")))); // return outStr;}二、私鑰解密過(guò)程
/*** RSA私鑰解密** @param str 加密字符串* @param privateKey 私鑰* @return 銘文* @throws Exception 解密過(guò)程中的異常信息*/public static String decrypt(String str, String privateKey) throws Exception {//64位解碼加密后的字符串byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));//base64編碼的私鑰byte[] decoded = Base64.decodeBase64(privateKey.getBytes());RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));//RSA解密Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");cipher.init(Cipher.DECRYPT_MODE, priKey);String outStr = new String(cipher.doFinal(inputByte));return outStr;}總結(jié)
以上是生活随笔為你收集整理的Android RSA公钥加密和私钥解密方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 草图大师SketchUp设计1——开槽
- 下一篇: Android图像处理系列:OpenG