接下来,在清单 5 中,我证明了一个给定的密钥实例始终会得到相应 String
的相同加密文本:
清单 5. 对应于一个字符串的一个私钥
@Test public void testEncrypt() throws Exception { SecretKey key = KeyGenerator.getInstance("AES").generateKey(); KeyStore ks = KeyStore.getInstance("JCEKS"); ks.load(null, null); KeyStore.SecretKeyEntry skEntry = new KeyStore.SecretKeyEntry(key); ks.setEntry("mykey", skEntry, new KeyStore.PasswordProtection("mykeypassword".toCharArray())); FileOutputStream fos = new FileOutputStream("agb50.keystore"); ks.store(fos, "somepassword".toCharArray()); fos.close(); Cryptographical crypto = AESCryptoImpl.initialize(new AESCryptoKey(key)); String enc = crypto.encrypt("Andy"); Assert.assertEquals("Andy", crypto.decrypt(enc)); //alternatively, read the keystore file itself to obtain the key Cryptographical anotherInst = AESCryptoImpl.initialize(new AESCryptoKey(key)); String anotherEncrypt = anotherInst.encrypt("Andy"); Assert.assertEquals("Andy", anotherInst.decrypt(anotherEncrypt)); Assert.assertTrue(anotherEncrypt.equals(enc)); }