private char[] getClearChars(ProtectedData<String> protectedData) throws EncryptionException { if (protectedData.isEncrypted()) { return decryptString(protectedData).toCharArray(); } else { return protectedData.getClearValue().toCharArray(); } }
@Override public <T> void decrypt(ProtectedData<T> protectedData) throws EncryptionException, SchemaException { if (!protectedData.isEncrypted()) { return; //TODO: is this exception really needed?? isn't it better just return the same protected data?? // throw new IllegalArgumentException("Attempt to decrypt protected data that are not encrypted"); } else { byte[] decryptedData = decryptBytes(protectedData); protectedData.setClearBytes(decryptedData); protectedData.setEncryptedData(null); } }
@Override public String decryptString(ProtectedData<String> protectedString) throws EncryptionException { try { if (!protectedString.isEncrypted()) { return protectedString.getClearValue(); } else { byte[] clearBytes = decryptBytes(protectedString); return ProtectedStringType.bytesToString(clearBytes); } } catch (SchemaException ex){ throw new EncryptionException(ex); } }
@Override public <T> void encrypt(ProtectedData<T> protectedData) throws EncryptionException { if (protectedData.isEncrypted()) { throw new IllegalArgumentException("Attempt to encrypt protected data that are already encrypted"); } SecretKey key = getSecretKeyByAlias(getEncryptionKeyAlias()); String algorithm = getCipherAlgorithm(); byte[] clearBytes = protectedData.getClearBytes(); byte[] encryptedBytes; try { encryptedBytes = encryptBytes(clearBytes, algorithm, key); } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | NoSuchProviderException | IllegalBlockSizeException | BadPaddingException | InvalidAlgorithmParameterException e) { throw new EncryptionException(e.getMessage(), e); } // Construct encryption types EncryptedDataType encryptedDataType = new EncryptedDataType(); EncryptionMethodType encryptionMethodType = new EncryptionMethodType(); encryptionMethodType.setAlgorithm(algorithm); encryptedDataType.setEncryptionMethod(encryptionMethodType); KeyInfoType keyInfoType = new KeyInfoType(); keyInfoType.setKeyName(getSecretKeyDigest(key)); encryptedDataType.setKeyInfo(keyInfoType); CipherDataType cipherDataType = new CipherDataType(); cipherDataType.setCipherValue(encryptedBytes); encryptedDataType.setCipherData(cipherDataType); protectedData.setEncryptedData(encryptedDataType); protectedData.destroyCleartext(); }