/** * decrypt the passed in message stream * * @param encrypted The message to be decrypted. * @param password Pass phrase (key) * @return Clear text as a byte array. I18N considerations are not handled * by this routine * @throws IOException * @throws PGPException * @throws NoSuchProviderException */ public static byte[] decrypt(byte[] encrypted, String keyIn, char[] password) throws IOException, PGPException, NoSuchProviderException { return decrypt (encrypted, new FileInputStream(keyIn), password); }
private SecretKey getKey (UUID keyId, char[] passPhrase) throws Exception { if (passPhrase == null && unlock == null) throw new SecurityException("Passphrase not available"); passPhrase = passPhrase != null ? passPhrase : unlock.get().toCharArray(); String v = DB.execWithTransaction(db -> { SysConfigManager mgr = new SysConfigManager(db, "key."); return mgr.get(keyId.toString(), null); }); if (v == null) { throw new SecurityException("Invalid key"); } byte[] key = PGPHelper.decrypt( v.getBytes(), privKeyRing, passPhrase ); return new SecretKeySpec(key, 0, key.length, "AES"); }
/** * Unlock the CryptoService */ public boolean unlock (Supplier<String> passwordSupplier) { try { if (isLocked()) { // attempt encrypt/decrypt UUID id = UUID.randomUUID(); SecretKey sk = generateKey(); byte[] b = pgpEncrypt(id.toString(), sk.getEncoded()); PGPHelper.decrypt(b, privKeyRing, passwordSupplier.get().toCharArray()); sem.acquire(); this.unlock = passwordSupplier; sem.release(); } return true; } catch (Exception e) { getLog().warn(e); return false; } }
@Test public void testEncryptDecrypt() throws Exception { String s = "The quick brown fox jumps over the lazy dog 0123456789"; byte[] cypertext = PGPHelper.encrypt( s.getBytes(StandardCharsets.UTF_8), "src/dist/cfg/demo.pub", "abc.txt", true, true, "demo@jpos.org"); byte[] clearText = PGPHelper.decrypt(cypertext, "src/dist/cfg/demo.priv", "demo".toCharArray()); assertEquals(s, new String(clearText, StandardCharsets.UTF_8)); } }