import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.RSAPublicKeySpec;
import javax.crypto.Cipher;
public final class RSAUtils {
/**
* 获取公钥方法(16进制公钥)
* @param modulus 公钥字符串(128字节)
* @param exponent 公钥指数 "10001"
* @return 公钥
*/
public static RSAPublicKey getPublicKey(String modulus, String exponent) {
try {
BigInteger n = new BigInteger(modulus, 16); // 此处为进制数
BigInteger e = new BigInteger(exponent, 16);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(n, e);
return (RSAPublicKey) keyFactory.generatePublic(keySpec);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 加密
*
* @param key
* 加密的密钥
* @param data
* 待加密的明文数据
* @return 加密后的数据
* @throws Exception
*/
public static byte[] encrypt(byte[] bt_plaintext, PublicKey key)
throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] bt_encrypted = cipher.doFinal(bt_plaintext);
return bt_encrypted;
}
}