public class RSAUtil {
public static final String KEY_ALGORITHM = "RSA/None/PKCS1Padding";
/**
* 使用模和指数生成RSA公钥
* 注意:【此代码用了默认补位方式,为RSA/None/PKCS1Padding,不同JDK默认的补位方式可能不同,如Android默认是RSA
* /None/NoPadding】
*
* @param modulus 模
* @param exponent 指数
* @return
*/
public static RSAPublicKey getPublicKey(String modulus, String exponent) {
try {
BigInteger b1 = new BigInteger(modulus, 16);
BigInteger b2 = new BigInteger(exponent, 16);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(b1, b2);
return (RSAPublicKey) keyFactory.generatePublic(keySpec);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 公钥加密
*/
public static byte[] encrypt(byte[] content, PublicKey publicKey) {
try {
Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(content);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
Android 用这个方法生成公私钥对
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
Android RSA加解密的时候用
Cipher cipher = Cipher.getInstance("RSA/None/PKCS1Padding");