使用rsa publickey字符串(不是文件),当我加密时,出现错误“无效密钥格式”

时间:2018-03-06 13:00:27

标签: java rsa public-key-encryption

我有一个公钥字符串(从api获取),我想使用公钥加密参数,而我得到错误“java.security.InvalidKeyException:invalid key format”,我的代码是下面:

try {
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKey.getBytes());
            PublicKey key = keyFactory.generatePublic(publicKeySpec);
            params = EncryptionUtil.encrypt(params.getBytes(), key);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }

        logger.info("encrypt params:" + params);

的公钥值是: “MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDBYu61cljDpI + XdWPO1bi5Ricv5 + U / 4u9Mqj4SdWp8YnCr3FaXTphW5mJol9KdqzK50GmD0Kv1x4z5gz6TDayfn527FX9KEO / puFlPiIkik2lg5UP9vGIyeWKoaxw1S8skjW13Md + Lw4i9ZqeoI9boLVMJdxMCtS + MTVDNxwDShwIDAQAB”

那么,如何解决这个问题呢?

1 个答案:

答案 0 :(得分:2)

您必须从api解码公钥:

String pubk = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDBYu61cljDpI+XdWPO1bi5Ricv5+U/4u9Mqj4SdWp8YnCr3FaXTphW5mJol9KdqzK50GmD0Kv1x4z5gz6TDayfn527FX9KEO/puFlPiIkik2lg5UP9vGIyeWKoaxw1S8skjW13Md+Lw4i9ZqeoI9boLVMJdxMCtS+MTVDNxwDShwIDAQAB";
byte[] bPubk = Base64.getDecoder().decode(pubk);

try {
    KeyFactory kf = KeyFactory.getInstance("RSA");
    X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(bPubk);
    PublicKey key = kf.generatePublic(publicKeySpec);
    System.out.println(key);
} catch (Exception e) {
    System.err.println(e.getMessage());
}

给出这个结果:

Sun RSA public key, 1024 bits
  modulus: 135800586859931582642310957384205018809539137294767840577881254803756232956639555134422701591513823339589448014996895987307431572469047529249728795673095119495397484042215360480856267006156705758125294683622900407564820516858390483599968159314547137229473538993288665937138465454319026029781283370049170625159
  public exponent: 65537