/*** 生成公钥和私钥
*@throwsNoSuchAlgorithmException
**/
public static HashMap getKeys() throwsNoSuchAlgorithmException{
HashMap map = new HashMap();
KeyPairGenerator keyPairGen= KeyPairGenerator.getInstance("RSA");
keyPairGen.initialize(1024);
KeyPair keyPair=keyPairGen.generateKeyPair();
RSAPublicKey publicKey=(RSAPublicKey) keyPair.getPublic();
RSAPrivateKey privateKey=(RSAPrivateKey) keyPair.getPrivate();
map.put("public", publicKey);
map.put("private", privateKey);returnmap;
}/*** 使用模和指数生成RSA公钥
* 注意:【此代码用了默认补位方式,为RSA/None/PKCS1Padding,不同JDK默认的补位方式可能不同,如Android默认是RSA
* /None/NoPadding】
*
*@parammodulus
* 模
*@paramexponent
* 指数
*@return
*/
public staticRSAPublicKey getPublicKey(String modulus, String exponent) {try{
BigInteger b1= newBigInteger(modulus);
BigInteger b2= newBigInteger(exponent);
KeyFactory keyFactory= KeyFactory.getInstance("RSA");
RSAPublicKeySpec keySpec= newRSAPublicKeySpec(b1, b2);return(RSAPublicKey) keyFactory.generatePublic(keySpec);
}catch(Exception e) {
e.printStackTrace();return null;
}
}/*** 使用模和指数生成RSA私钥
* 注意:【此代码用了默认补位方式,为RSA/None/PKCS1Padding,不同JDK默认的补位方式可能不同,如Android默认是RSA
* /None/NoPadding】
*
*@parammodulus
* 模
*@paramexponent
* 指数
*@return
*/
public staticRSAPrivateKey getPrivateKey(String modulus, String exponent) {try{
BigInteger b1= newBigInteger(modulus);
BigInteger b2= newBigInteger(exponent);
KeyFactory keyFactory= KeyFactory.getInstance("RSA");
RSAPrivateKeySpec keySpec= newRSAPrivateKeySpec(b1, b2);return(RSAPrivateKey) keyFactory.generatePrivate(keySpec);
}catch(Exception e) {
e.printStackTrace();return null;
}
}/*** 公钥加密
*
*@paramdata
*@parampublicKey
*@return*@throwsException*/
public staticString encryptByPublicKey(String data, RSAPublicKey publicKey)throwsException {
Cipher cipher= Cipher.getInstance("RSA/ECB/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);//模长
int key_len = publicKey.getModulus().bitLength() / 8;//加密数据长度 <= 模长-11
String[] datas = splitString(data, key_len - 11);
String mi= "";//如果明文长度大于模长-11则要分组加密
for(String s : datas) {
mi+=bcd2Str(cipher.doFinal(s.getBytes()));
}returnmi;
}/*** 私钥解密
*
*@paramdata
*@paramprivateKey
*@return*@throwsException*/
public staticString decryptByPrivateKey(String data, RSAPrivateKey privateKey)throwsException {
Cipher cipher= Cipher.getInstance("RSA/ECB/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, privateKey);//模长
int key_len = privateKey.getModulus().bitLength() / 8;byte[] bytes =data.getBytes();byte[] bcd =ASCII_To_BCD(bytes, bytes.length);
System.err.println(bcd.length);//如果密文长度大于模长则要分组解密
String ming = "";byte[][] arrays =splitArray(bcd, key_len);for(byte[] arr : arrays){
ming+= newString(cipher.doFinal(arr));
}returnming;
}