blob: c1aa2ee223870030717dc933da9e5130de80082f [file] [log] [blame]
Stuart McCullochbb014372012-06-07 21:57:32 +00001package aQute.libg.cryptography;
2
3import java.math.*;
4import java.security.*;
5import java.security.interfaces.*;
6import java.security.spec.*;
7
8import aQute.libg.tuple.*;
9
10public class RSA {
11 final static String ALGORITHM = "RSA";
12
13 final static KeyFactory factory = getKeyFactory();
14
15 static private KeyFactory getKeyFactory() {
16 try {
17 return KeyFactory.getInstance(ALGORITHM);
Stuart McCulloch2286f232012-06-15 13:27:53 +000018 }
19 catch (Exception e) {
Stuart McCullochbb014372012-06-07 21:57:32 +000020 // built in
21 }
22 return null;
23 }
24
25 public static RSAPrivateKey create(RSAPrivateKeySpec keyspec) throws InvalidKeySpecException {
26 return (RSAPrivateKey) factory.generatePrivate(keyspec);
27 }
Stuart McCulloch2286f232012-06-15 13:27:53 +000028
Stuart McCullochbb014372012-06-07 21:57:32 +000029 public static RSAPublicKey create(RSAPublicKeySpec keyspec) throws InvalidKeySpecException {
30 return (RSAPublicKey) factory.generatePrivate(keyspec);
31 }
Stuart McCulloch2286f232012-06-15 13:27:53 +000032
Stuart McCullochbb014372012-06-07 21:57:32 +000033 public static RSAPublicKey createPublic(BigInteger m, BigInteger e) throws InvalidKeySpecException {
Stuart McCulloch2286f232012-06-15 13:27:53 +000034 return create(new RSAPublicKeySpec(m, e));
Stuart McCullochbb014372012-06-07 21:57:32 +000035 }
Stuart McCulloch2286f232012-06-15 13:27:53 +000036
Stuart McCullochbb014372012-06-07 21:57:32 +000037 public static RSAPrivateKey createPrivate(BigInteger m, BigInteger e) throws InvalidKeySpecException {
Stuart McCulloch2286f232012-06-15 13:27:53 +000038 return create(new RSAPrivateKeySpec(m, e));
Stuart McCullochbb014372012-06-07 21:57:32 +000039 }
Stuart McCulloch2286f232012-06-15 13:27:53 +000040
41 public static Pair<RSAPrivateKey,RSAPublicKey> generate() throws NoSuchAlgorithmException {
Stuart McCullochbb014372012-06-07 21:57:32 +000042 KeyPairGenerator kpg = KeyPairGenerator.getInstance(ALGORITHM);
43 KeyPair keypair = kpg.generateKeyPair();
Stuart McCulloch2286f232012-06-15 13:27:53 +000044 return new Pair<RSAPrivateKey,RSAPublicKey>((RSAPrivateKey) keypair.getPrivate(),
45 (RSAPublicKey) keypair.getPublic());
Stuart McCullochbb014372012-06-07 21:57:32 +000046 }
47}