@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 <T> void hash(ProtectedData<T> protectedData) throws EncryptionException, SchemaException { if (protectedData.isHashed()) { throw new IllegalArgumentException("Attempt to hash protected data that are already hashed"); } String algorithmUri = getDigestAlgorithm(); QName algorithmQName = QNameUtil.uriToQName(algorithmUri); String algorithmNamespace = algorithmQName.getNamespaceURI(); if (algorithmNamespace == null) { throw new SchemaException("No algorithm namespace"); } HashedDataType hashedDataType; switch (algorithmNamespace) { case PrismConstants.NS_CRYPTO_ALGORITHM_PBKD: if (!protectedData.canSupportType(String.class)) { throw new SchemaException("Non-string protected data"); } hashedDataType = hashPbkd((ProtectedData<String>) protectedData, algorithmUri, algorithmQName.getLocalPart()); break; default: throw new SchemaException("Unknown namespace " + algorithmNamespace); } protectedData.setHashedData(hashedDataType); protectedData.destroyCleartext(); protectedData.setEncryptedData(null); }
@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(); }