Stuart McCulloch | bb01437 | 2012-06-07 21:57:32 +0000 | [diff] [blame] | 1 | package aQute.libg.cryptography; |
| 2 | |
| 3 | import java.math.*; |
| 4 | import java.security.*; |
| 5 | import java.security.interfaces.*; |
| 6 | import java.security.spec.*; |
| 7 | |
| 8 | import aQute.libg.tuple.*; |
| 9 | |
| 10 | public 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 McCulloch | 2286f23 | 2012-06-15 13:27:53 +0000 | [diff] [blame] | 18 | } |
| 19 | catch (Exception e) { |
Stuart McCulloch | bb01437 | 2012-06-07 21:57:32 +0000 | [diff] [blame] | 20 | // 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 McCulloch | 2286f23 | 2012-06-15 13:27:53 +0000 | [diff] [blame] | 28 | |
Stuart McCulloch | bb01437 | 2012-06-07 21:57:32 +0000 | [diff] [blame] | 29 | public static RSAPublicKey create(RSAPublicKeySpec keyspec) throws InvalidKeySpecException { |
| 30 | return (RSAPublicKey) factory.generatePrivate(keyspec); |
| 31 | } |
Stuart McCulloch | 2286f23 | 2012-06-15 13:27:53 +0000 | [diff] [blame] | 32 | |
Stuart McCulloch | bb01437 | 2012-06-07 21:57:32 +0000 | [diff] [blame] | 33 | public static RSAPublicKey createPublic(BigInteger m, BigInteger e) throws InvalidKeySpecException { |
Stuart McCulloch | 2286f23 | 2012-06-15 13:27:53 +0000 | [diff] [blame] | 34 | return create(new RSAPublicKeySpec(m, e)); |
Stuart McCulloch | bb01437 | 2012-06-07 21:57:32 +0000 | [diff] [blame] | 35 | } |
Stuart McCulloch | 2286f23 | 2012-06-15 13:27:53 +0000 | [diff] [blame] | 36 | |
Stuart McCulloch | bb01437 | 2012-06-07 21:57:32 +0000 | [diff] [blame] | 37 | public static RSAPrivateKey createPrivate(BigInteger m, BigInteger e) throws InvalidKeySpecException { |
Stuart McCulloch | 2286f23 | 2012-06-15 13:27:53 +0000 | [diff] [blame] | 38 | return create(new RSAPrivateKeySpec(m, e)); |
Stuart McCulloch | bb01437 | 2012-06-07 21:57:32 +0000 | [diff] [blame] | 39 | } |
Stuart McCulloch | 2286f23 | 2012-06-15 13:27:53 +0000 | [diff] [blame] | 40 | |
| 41 | public static Pair<RSAPrivateKey,RSAPublicKey> generate() throws NoSuchAlgorithmException { |
Stuart McCulloch | bb01437 | 2012-06-07 21:57:32 +0000 | [diff] [blame] | 42 | KeyPairGenerator kpg = KeyPairGenerator.getInstance(ALGORITHM); |
| 43 | KeyPair keypair = kpg.generateKeyPair(); |
Stuart McCulloch | 2286f23 | 2012-06-15 13:27:53 +0000 | [diff] [blame] | 44 | return new Pair<RSAPrivateKey,RSAPublicKey>((RSAPrivateKey) keypair.getPrivate(), |
| 45 | (RSAPublicKey) keypair.getPublic()); |
Stuart McCulloch | bb01437 | 2012-06-07 21:57:32 +0000 | [diff] [blame] | 46 | } |
| 47 | } |