Created
May 11, 2019 07:19
-
-
Save as8190255/5b89e98c0ca675a7d048a3c747c5cf90 to your computer and use it in GitHub Desktop.
android RSA 私钥加密 公钥解密[不支持分段,单次长度约128位]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class AppRsaUtil { | |
static String pub = ""; | |
static String pri = ""; | |
//公钥解密 | |
public static String decodePub(String code){ | |
try { | |
byte[] codeBytes = Base64.decode(code, Base64.DEFAULT); | |
byte[] pubBytes = Base64.decode(pub, Base64.DEFAULT); | |
RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(pubBytes)); | |
//解密 | |
Cipher cipher = Cipher.getInstance("RSA"); | |
cipher.init(Cipher.DECRYPT_MODE, pubKey); | |
String outStr = new String(cipher.doFinal(codeBytes)); | |
return outStr; | |
} catch (Exception e) { | |
return ""; | |
} | |
} | |
/** | |
* 私钥加密 | |
* @param str 待加密字符串 | |
*/ | |
public static String encryptPri(String str){ | |
try { | |
byte[] inputByte = str.getBytes("UTF-8"); | |
//base64编码的私钥 | |
byte[] decoded = Base64.decode(pri, Base64.DEFAULT); | |
RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded)); | |
//加密 | |
Cipher cipher = Cipher.getInstance("RSA"); | |
cipher.init(Cipher.ENCRYPT_MODE, priKey); | |
String outStr = Base64.encodeToString(cipher.doFinal(inputByte), Base64.DEFAULT); | |
return outStr; | |
}catch (Exception e){ | |
return ""; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment