Creating RSA keys from known parameters in Java

前端 未结 3 606
终归单人心
终归单人心 2020-12-31 06:00

I\'m working on implementing Bing Cashback. In order to verify an incoming request from Bing as valid they provide a signature. The signature is a 160-bit SHA-1 hash of the

相关标签:
3条回答
  • 2020-12-31 06:29
    RSAPublicKeySpec spec = new RSAPublicKeySpec(modulus, exponent);
    KeyFactory factory = KeyFactory.getInstance("RSA");
    PublicKey pub = factory.generatePublic(spec);
    Signature verifier = Signature.getInstance("SHA1withRSA");
    verifier.initVerify(pub);
    verifier.update(url.getBytes("UTF-8")); // Or whatever interface specifies.
    boolean okay = verifier.verify(signature);
    
    0 讨论(0)
  • 2020-12-31 06:31

    Use java.security.spec.RSAPublicKeySpec. It can construct a key from exponent and modulus. Then use java.security.KeyFactory.generatePublic() with key spec as a parameter.

    0 讨论(0)
  • 2020-12-31 06:32

    Something like this should do the trick:

      private PublicKey convertPublicKey(String publicKey) throws Exception{
        PublicKey pub = null;
    
        byte[] pubKey = Hex.decodeHex(publicKey.toCharArray());
        X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(pubKey);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        pub = (RSAPublicKey) keyFactory.generatePublic(pubSpec);
    
        return pub;
      }
    

    This assumes the Public key is given as a hex string, and you'll need the Apache Commons Codec library

    If you have the key in a different format, try the KeyFactory for more information.

    0 讨论(0)
提交回复
热议问题