Search code examples
javajwtapple-sign-in

How to create public RSA key using modulus and exponent for Sign In with Apple?


I am implementing server side part for Sign In with Apple feature that is used in the IOS application.

In order to verify JWT I need to use public key. I stuck at the moment how to create public key from modulus and exponent that I get from Apple.


Solution

  • To generate public key from the exponent and modulus, they need to be transformed to BigInteger, and then KeyFactory from Java security can be used.

    For example:

    
      String modulus = "modulus from Apple";
      String exponent = "exponent from Apple";
      byte[] modulusByte = Base64.getUrlDecoder().decode(modulus);
    
      BigInteger modulusAsBigInt = new BigInteger(1, modulusByte);
      byte[] exponentByte = Base64.getUrlDecoder().decode(exponent);
      BigInteger exponentAsBigInt = new BigInteger(1, exponentByte);
    
      RSAPublicKeySpec spec = new RSAPublicKeySpec(modulusAsBigInt, exponentAsBigInt);
      KeyFactory factory = KeyFactory.getInstance("RSA");
      PublicKey pub = factory.generatePublic(spec);