Stuart McCulloch | bb01437 | 2012-06-07 21:57:32 +0000 | [diff] [blame] | 1 | package aQute.bnd.settings; |
| 2 | |
| 3 | import java.security.*; |
| 4 | import java.security.interfaces.*; |
| 5 | import java.util.*; |
| 6 | import java.util.prefs.*; |
| 7 | |
| 8 | import aQute.libg.cryptography.*; |
| 9 | import aQute.libg.tuple.*; |
| 10 | |
| 11 | public class Settings { |
| 12 | public final static String EMAIL = "email"; |
| 13 | public final static String NAME = "name"; |
| 14 | public final static String PASSWORD_SHA1 = "password.sha1"; |
| 15 | final static String KEY_PRIVATE = "key.private"; |
| 16 | final static String KEY_PUBLIC = "key.public"; |
| 17 | final static String KEY_SET = "key.set"; |
| 18 | |
| 19 | static Preferences prefs = Preferences.userNodeForPackage(Settings.class); |
| 20 | |
| 21 | public String globalGet(String key, String def) { |
| 22 | return prefs.get(key, def); |
| 23 | } |
| 24 | |
| 25 | public void globalSet(String key, String value) throws BackingStoreException { |
| 26 | prefs.put(key, value); |
| 27 | prefs.sync(); |
| 28 | } |
| 29 | |
| 30 | public Collection<String> getKeys() throws BackingStoreException { |
| 31 | return Arrays.asList(prefs.keys()); |
| 32 | } |
| 33 | |
| 34 | public void globalRemove(String key) throws BackingStoreException { |
| 35 | prefs.remove(key); |
| 36 | prefs.sync(); |
| 37 | } |
| 38 | |
| 39 | private void generate() throws NoSuchAlgorithmException { |
Stuart McCulloch | 2286f23 | 2012-06-15 13:27:53 +0000 | [diff] [blame] | 40 | Pair< ? extends PrivateKey, ? extends RSAPublicKey> pair = RSA.generate(); |
Stuart McCulloch | bb01437 | 2012-06-07 21:57:32 +0000 | [diff] [blame] | 41 | prefs.put(KEY_PRIVATE, Crypto.toString(pair.a)); |
| 42 | prefs.put(KEY_PUBLIC, Crypto.toString(pair.b)); |
| 43 | prefs.putBoolean(KEY_SET, true); |
| 44 | } |
| 45 | |
| 46 | public PrivateKey getPrivateKey() throws Exception { |
| 47 | if (prefs.getBoolean(KEY_SET, false)) |
| 48 | generate(); |
| 49 | |
| 50 | String key = prefs.get(KEY_PRIVATE, null); |
| 51 | return Crypto.fromString(key, PrivateKey.class); |
| 52 | } |
| 53 | |
| 54 | public PublicKey getPublicKey() throws Exception { |
| 55 | if (prefs.getBoolean(KEY_SET, false)) |
| 56 | generate(); |
| 57 | |
| 58 | String key = prefs.get(KEY_PUBLIC, null); |
| 59 | return Crypto.fromString(key, PublicKey.class); |
| 60 | } |
| 61 | |
| 62 | } |