使用16进制编码的RSA公钥进行RSA加密

最近遇到一个客户,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,搞定!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章