1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.pkitesting;
17
18 import org.bouncycastle.jce.provider.BouncyCastleProvider;
19
20 import java.security.GeneralSecurityException;
21 import java.security.KeyPairGenerator;
22 import java.security.NoSuchAlgorithmException;
23 import java.security.Provider;
24 import java.security.SecureRandom;
25 import java.security.Signature;
26 import java.security.spec.AlgorithmParameterSpec;
27 import java.util.Locale;
28
29 final class Algorithms {
30 private static Provider bouncyCastle;
31
32 private Algorithms() {
33 }
34
35 static String oidForAlgorithmName(String algorithmIdentifier) {
36
37
38 switch (algorithmIdentifier.toLowerCase(Locale.ROOT)) {
39 case "sha256withecdsa":
40 return "1.2.840.10045.4.3.2";
41 case "sha384withecdsa":
42 return "1.2.840.10045.4.3.3";
43 case "sha256withrsa":
44 return "1.2.840.113549.1.1.11";
45 case "sha384withrsa":
46 return "1.2.840.113549.1.1.12";
47 case "ed25519":
48 return "1.3.101.112";
49 case "ed448":
50 return "1.3.101.113";
51 case "ml-dsa-44":
52 return "2.16.840.1.101.3.4.3.17";
53 case "ml-dsa-65":
54 return "2.16.840.1.101.3.4.3.18";
55 case "ml-dsa-87":
56 return "2.16.840.1.101.3.4.3.19";
57 default:
58 throw new UnsupportedOperationException("Algorithm not supported: " + algorithmIdentifier);
59 }
60 }
61
62 static KeyPairGenerator keyPairGenerator(String keyType, AlgorithmParameterSpec spec,
63 SecureRandom rng, Provider provider) throws GeneralSecurityException {
64 try {
65 KeyPairGenerator keyGen = KeyPairGenerator.getInstance(keyType);
66 keyGen.initialize(spec, rng);
67 return keyGen;
68 } catch (GeneralSecurityException e) {
69 try {
70 KeyPairGenerator keyGen = KeyPairGenerator.getInstance(keyType,
71 provider != null ? provider : bouncyCastle());
72 keyGen.initialize(spec, rng);
73 return keyGen;
74 } catch (GeneralSecurityException ex) {
75 e.addSuppressed(ex);
76 }
77 throw e;
78 }
79 }
80
81 static Signature signature(String algorithmIdentifier, Provider provider) throws NoSuchAlgorithmException {
82 try {
83 return Signature.getInstance(algorithmIdentifier);
84 } catch (NoSuchAlgorithmException e) {
85 try {
86 return Signature.getInstance(algorithmIdentifier, provider != null ? provider : bouncyCastle());
87 } catch (NoSuchAlgorithmException ex) {
88 e.addSuppressed(ex);
89 }
90 throw e;
91 }
92 }
93
94 private static synchronized Provider bouncyCastle() {
95 if (bouncyCastle == null) {
96 bouncyCastle = new BouncyCastleProvider();
97 }
98 return bouncyCastle;
99 }
100 }