public class RSAUtil {
public static String encrypt(String encryptStr) throws Exception {
HashMap<String, String> mmm = rsaParameters("<RSAKeyValue><Modulus>7NAI2E4PDc6AWuioK/0NfrM7bCMH7xC9nnMyDoIZYwnhKL4Q20aByQdocH0E46FzDVFZ+xs1lZokA9FHoIcT9gYLqcEcHugl36wT/sxhH/W90LLryev+8OuCmJicJ/icXxUiFROe11j29GEy/SgsL6FEkSIvDg6J1rIS/8LpKxE=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>");
PublicKey mPublicKey = getPublicKey(mmm.get("mudulus"), mmm.get("exponent"));
return encrypt(encryptStr.getBytes("utf-8"), mPublicKey);
}
private static final int MAXENCRYPTSIZE = 1024;
/**
* 返回包含模数modulus和指数exponent的haspMap
*
* @return
* @throws MalformedURLException
* @throws DocumentException
*/
private static HashMap<String, String> rsaParameters(String xmlPublicKey) throws MalformedURLException, DocumentException {
HashMap<String, String> map = new HashMap<String, String>();
Document doc = DocumentHelper.parseText(xmlPublicKey);
String mudulus = (String) doc.getRootElement().element("Modulus").getData();
String exponent = (String) doc.getRootElement().element("Exponent").getData();
map.put("mudulus", mudulus);
map.put("exponent", exponent);
return map;
}
private static byte[] decodeBase64(String input) throws Exception {
return Base64.decode(input,Base64.NO_WRAP);
}
/**
* 返回RSA公钥
*
* @param modules
* @param exponent
* @return
*/
private static PublicKey getPublicKey(String modulus, String exponent) {
try {
byte[] m = decodeBase64(modulus);
byte[] e = decodeBase64(exponent);
BigInteger b1 = new BigInteger(1, m);
BigInteger b2 = new BigInteger(1, e);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(b1, b2);
return (RSAPublicKey) keyFactory.generatePublic(keySpec);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private static String encrypt(byte[] source, PublicKey publicKey) throws Exception {
String encryptData = "";
try {
// Cipher cipher = Cipher.getInstance("RSA");
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
int length = source.length;
int offset = 0;
byte[] cache;
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
int i = 0;
while (length - offset > 0) {
if (length - offset > MAXENCRYPTSIZE) {
cache = cipher.doFinal(source, offset, MAXENCRYPTSIZE);
} else {
cache = cipher.doFinal(source, offset, length - offset);
}
outStream.write(cache, 0, cache.length);
i++;
offset = i * MAXENCRYPTSIZE;
}
return encodeBase64(outStream.toByteArray());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return encryptData;
}
private static String encodeBase64(byte[] bytes) {
return Base64.encodeToString(bytes, Base64.NO_WRAP);
}
}
Android RSA加密 工具类
于 2018-05-04 17:51:40 首次发布