Stuart McCulloch | 3fdcd85 | 2011-10-17 10:31:43 +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 | import java.util.regex.*; |
| 8 | |
| 9 | public class Crypto { |
| 10 | static final Pattern RSA_PRIVATE = Pattern |
| 11 | .compile("\\s*RSA.Private\\((\\p{xDigit})+:(\\p{xDigit})+\\)\\s*"); |
| 12 | static final Pattern RSA_PUBLIC = Pattern |
| 13 | .compile("\\s*RSA.Public\\((\\p{xDigit})+:(\\p{xDigit})+\\)\\s*"); |
| 14 | |
| 15 | /** |
| 16 | * |
| 17 | * @param <T> |
| 18 | * @param spec |
| 19 | * @return |
| 20 | * @throws Exception |
| 21 | */ |
| 22 | @SuppressWarnings("unchecked") public static <T> T fromString(String spec, Class<T> c) throws Exception { |
| 23 | if ( PrivateKey.class.isAssignableFrom(c)) { |
| 24 | Matcher m = RSA_PRIVATE.matcher(spec); |
| 25 | if ( m.matches()) { |
| 26 | return (T) RSA.createPrivate( |
| 27 | new BigInteger(m.group(1)), new BigInteger(m.group(2))); |
| 28 | } |
| 29 | throw new IllegalArgumentException("No such private key " + spec ); |
| 30 | } |
| 31 | |
| 32 | if ( PublicKey.class.isAssignableFrom(c)) { |
| 33 | Matcher m = RSA_PUBLIC.matcher(spec); |
| 34 | if ( m.matches()) { |
| 35 | return (T) RSA.create( new RSAPublicKeySpec( |
| 36 | new BigInteger(m.group(1)), new BigInteger(m.group(2)))); |
| 37 | } |
| 38 | throw new IllegalArgumentException("No such public key " + spec ); |
| 39 | } |
| 40 | return null; |
| 41 | } |
| 42 | |
| 43 | public static String toString( Object key ) { |
| 44 | if ( key instanceof RSAPrivateKey ) { |
| 45 | RSAPrivateKey pk = (RSAPrivateKey) key; |
| 46 | return "RSA.Private(" + pk.getModulus() + ":" + pk.getPrivateExponent() + ")"; |
| 47 | } |
| 48 | if ( key instanceof RSAPublicKey ) { |
| 49 | RSAPublicKey pk = (RSAPublicKey) key; |
| 50 | return "RSA.Private(" + pk.getModulus() + ":" + pk.getPublicExponent() + ")"; |
| 51 | } |
| 52 | return null; |
| 53 | } |
| 54 | |
| 55 | |
| 56 | public static <T extends Digest> Signer<T> signer(PrivateKey key, Digester<T> digester) throws NoSuchAlgorithmException { |
| 57 | Signature s = Signature.getInstance(key.getAlgorithm() + "with" + digester.getAlgorithm()); |
| 58 | return new Signer<T>(s,digester); |
| 59 | } |
| 60 | |
| 61 | public static Verifier verifier(PublicKey key, Digest digest) throws NoSuchAlgorithmException { |
| 62 | Signature s = Signature.getInstance(key.getAlgorithm() + "with" + digest.getAlgorithm()); |
| 63 | return new Verifier(s,digest); |
| 64 | } |
| 65 | |
| 66 | |
| 67 | } |