Jwks.java 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /*
  2. * Copyright 2020-2021 the original author or authors.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * https://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package sample.jose;
  17. import java.security.KeyPair;
  18. import java.security.interfaces.ECPrivateKey;
  19. import java.security.interfaces.ECPublicKey;
  20. import java.security.interfaces.RSAPrivateKey;
  21. import java.security.interfaces.RSAPublicKey;
  22. import java.util.UUID;
  23. import javax.crypto.SecretKey;
  24. import com.nimbusds.jose.jwk.Curve;
  25. import com.nimbusds.jose.jwk.ECKey;
  26. import com.nimbusds.jose.jwk.OctetSequenceKey;
  27. import com.nimbusds.jose.jwk.RSAKey;
  28. /**
  29. * @author Joe Grandja
  30. * @since 0.1.0
  31. */
  32. public final class Jwks {
  33. private Jwks() {
  34. }
  35. public static RSAKey generateRsa() {
  36. KeyPair keyPair = KeyGeneratorUtils.generateRsaKey();
  37. RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
  38. RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
  39. // @formatter:off
  40. return new RSAKey.Builder(publicKey)
  41. .privateKey(privateKey)
  42. .keyID(UUID.randomUUID().toString())
  43. .build();
  44. // @formatter:on
  45. }
  46. public static ECKey generateEc() {
  47. KeyPair keyPair = KeyGeneratorUtils.generateEcKey();
  48. ECPublicKey publicKey = (ECPublicKey) keyPair.getPublic();
  49. ECPrivateKey privateKey = (ECPrivateKey) keyPair.getPrivate();
  50. Curve curve = Curve.forECParameterSpec(publicKey.getParams());
  51. // @formatter:off
  52. return new ECKey.Builder(curve, publicKey)
  53. .privateKey(privateKey)
  54. .keyID(UUID.randomUUID().toString())
  55. .build();
  56. // @formatter:on
  57. }
  58. public static OctetSequenceKey generateSecret() {
  59. SecretKey secretKey = KeyGeneratorUtils.generateSecretKey();
  60. // @formatter:off
  61. return new OctetSequenceKey.Builder(secretKey)
  62. .keyID(UUID.randomUUID().toString())
  63. .build();
  64. // @formatter:on
  65. }
  66. }