最近遇到一個客戶,RSA公鑰發過來是16進制的(我也不大明白爲什麼要這樣做,反正當時後臺告訴我轉了16進制,要我自己處理),不能直接使用:如下
A32ADB16D88E28BB5FCE9600765BF61D8831C58164C94879
FF34C16B6532AAE948E4B6BA268DEEC84CFF08CE11D4458E
5165EA2098A9CB8A2F885D72E7CCE91111111111111111111
111111111111111111111111111111111111111111111111111
111111111111111111111111111111111111111111111111111
1111111AD
(這個就是下面方法裏面的參數modulus,由於是客戶的公鑰,中間部分用1代替,總共256位,大家明白就好)
加密方法如下:
public static RSAPublicKey getPublicKey(String modulus, String exponent) { //exponent我這邊傳入的是5位的數字,如10101,這個客戶提供的,真實值不能提供
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[] bt_plaintext, String key)
throws Exception {
PublicKey publicKey = getPublicKey(key, exponent);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] bt_encrypted = cipher.doFinal(bt_plaintext);
return bt_encrypted;
}
OK,搞定!