Java源码示例:org.jasypt.exceptions.EncryptionOperationNotPossibleException

示例1
public static byte[] fromHexadecimal(final String message) {
    if (message == null) {
        return null;
    }
    if ((message.length() % 2) != 0) {
        throw new EncryptionOperationNotPossibleException();
    }
    try {
        final byte[] result = new byte[message.length() / 2];
        for (int i = 0; i < message.length(); i = i + 2) {
            final int first = Integer.parseInt("" + message.charAt(i), 16);
            final int second = Integer.parseInt("" + message.charAt(i + 1), 16);
            result[i/2] = (byte) (0x0 + ((first & 0xff) << 4) + (second & 0xff));
        }
        return result;
    } catch (Exception e) {
        throw new EncryptionOperationNotPossibleException();
    }
}
 
示例2
public static String encrypt(final String plain) {
    if (!EncryptionSecretKeyChecker.useEncryption() || (plain == null) || plain.isEmpty()) {
        return plain;
    }
    if (s_encryptor == null) {
        initialize();
    }
    String encryptedString = null;
    try {
        encryptedString = s_encryptor.encrypt(plain);
    } catch (final EncryptionOperationNotPossibleException e) {
        s_logger.debug("Error while encrypting: " + plain);
        throw e;
    }
    return encryptedString;
}
 
示例3
public static String decrypt(final String encrypted) {
    if (!EncryptionSecretKeyChecker.useEncryption() || (encrypted == null) || encrypted.isEmpty()) {
        return encrypted;
    }
    if (s_encryptor == null) {
        initialize();
    }

    String plain = null;
    try {
        plain = s_encryptor.decrypt(encrypted);
    } catch (final EncryptionOperationNotPossibleException e) {
        s_logger.debug("Error while decrypting: " + encrypted);
        throw e;
    }
    return plain;
}
 
示例4
@Override
public String resolvePropertyValue(String value) {
    return Optional.ofNullable(value)
            .map(environment::resolvePlaceholders)
            .filter(detector::isEncrypted)
            .map(resolvedValue -> {
                try {
                    String unwrappedProperty = detector.unwrapEncryptedValue(resolvedValue.trim());
                    String resolvedProperty = environment.resolvePlaceholders(unwrappedProperty);
                    return encryptor.decrypt(resolvedProperty);
                } catch (EncryptionOperationNotPossibleException e) {
                    throw new DecryptionException("Unable to decrypt: " + value + ". Decryption of Properties failed,  make sure encryption/decryption " +
                            "passwords match", e);
                }
            })
            .orElse(value);
}
 
示例5
@Test (enabled=false)
public void testStrongEncryptionAndDecryption() throws IOException {
  String password = UUID.randomUUID().toString();
  String masterPassword = UUID.randomUUID().toString();
  File masterPwdFile = getMasterPwdFile(masterPassword);
  State state = new State();
  state.setProp(ConfigurationKeys.ENCRYPT_KEY_LOC, masterPwdFile.toString());
  state.setProp(ConfigurationKeys.ENCRYPT_USE_STRONG_ENCRYPTOR, true);
  try{
    StrongTextEncryptor encryptor = new StrongTextEncryptor();
    encryptor.setPassword(masterPassword);
    String encrypted = encryptor.encrypt(password);
    encrypted = "ENC(" + encrypted + ")";
    String decrypted = PasswordManager.getInstance(state).readPassword(encrypted);
    Assert.assertEquals(decrypted, password);
  }
  catch (EncryptionOperationNotPossibleException e) {
    //no strong encryption is supported
  }
}
 
示例6
public AuthToken(String key,String token) throws AuthenticationException {
    try {
        logger.info("En: " + token);
        token = decrypt(token, key);
        logger.info("De: " + token);
        String[] parts = token.split("(\\|)");
        for (String s : parts){
            logger.info("Part: " + s);
        }
        userId = parts[1];
        expirationDate = Long.parseLong(parts[2]);
    } catch (EncryptionOperationNotPossibleException e){
        e.printStackTrace();
        throw new AuthenticationException("Failed to create AuthToken",e);
    }
}
 
示例7
private void encryptIpSecPresharedKeysOfRemoteAccessVpn(Connection conn) {
    try (
            PreparedStatement selectStatement = conn.prepareStatement("SELECT id, ipsec_psk FROM `cloud`.`remote_access_vpn`");
            ResultSet resultSet = selectStatement.executeQuery();
        ) {
        while (resultSet.next()) {
            Long rowId = resultSet.getLong(1);
            String preSharedKey = resultSet.getString(2);
            try {
                preSharedKey = DBEncryptionUtil.decrypt(preSharedKey);
            } catch (EncryptionOperationNotPossibleException ignored) {
                s_logger.debug("The ipsec_psk preshared key id=" + rowId + "in remote_access_vpn is not encrypted, encrypting it.");
            }
            try (PreparedStatement updateStatement = conn.prepareStatement("UPDATE `cloud`.`remote_access_vpn` SET ipsec_psk=? WHERE id=?");) {
                updateStatement.setString(1, DBEncryptionUtil.encrypt(preSharedKey));
                updateStatement.setLong(2, rowId);
                updateStatement.executeUpdate();
            }
        }
    } catch (SQLException e) {
        throw new CloudRuntimeException("Unable to update the remote_access_vpn's preshared key ipsec_psk column", e);
    }
    s_logger.debug("Done encrypting remote_access_vpn's ipsec_psk column");
}
 
示例8
public static String encrypt(String plain) {
    if (!EncryptionSecretKeyChecker.useEncryption() || (plain == null) || plain.isEmpty()) {
        return plain;
    }
    if (s_encryptor == null) {
        initialize();
    }
    String encryptedString = null;
    try {
        encryptedString = s_encryptor.encrypt(plain);
    } catch (EncryptionOperationNotPossibleException e) {
        s_logger.debug("Error while encrypting: " + plain);
        throw e;
    }
    return encryptedString;
}
 
示例9
public static String decrypt(String encrypted) {
    if (!EncryptionSecretKeyChecker.useEncryption() || (encrypted == null) || encrypted.isEmpty()) {
        return encrypted;
    }
    if (s_encryptor == null) {
        initialize();
    }

    String plain = null;
    try {
        plain = s_encryptor.decrypt(encrypted);
    } catch (EncryptionOperationNotPossibleException e) {
        s_logger.debug("Error while decrypting: " + encrypted);
        throw e;
    }
    return plain;
}
 
示例10
static void showError(final Throwable t, final boolean verbose) {

        if (verbose) {

            System.err.println("\n----ERROR-----------------------\n");
            if (t instanceof EncryptionOperationNotPossibleException) {
                System.err.println(
                        "Operation not possible (Bad input or parameters)");
            } else {
                if (t.getMessage() != null) {
                    System.err.println(t.getMessage());
                } else {
                    System.err.println(t.getClass().getName());
                }
            }
            System.err.println("\n");
            
        } else {
            
            System.err.print("ERROR: ");
            if (t instanceof EncryptionOperationNotPossibleException) {
                System.err.println(
                        "Operation not possible (Bad input or parameters)");
            } else {
                if (t.getMessage() != null) {
                    System.err.println(t.getMessage());
                } else {
                    System.err.println(t.getClass().getName());
                }
            }
            
        }
        
    }
 
示例11
private synchronized String decode(final String encodedValue) {
    
    if (!PropertyValueEncryptionUtils.isEncryptedValue(encodedValue)) {
        return encodedValue;
    }
    if (this.stringEncryptor != null) {
        return PropertyValueEncryptionUtils.decrypt(encodedValue, this.stringEncryptor);
        
    }
    if (this.textEncryptor != null) {
        return PropertyValueEncryptionUtils.decrypt(encodedValue, this.textEncryptor);
    }
    
    /*
     * If neither a StringEncryptor nor a TextEncryptor can be retrieved
     * from the registry, this means that this EncryptableProperties
     * object has been serialized and then deserialized in a different
     * classloader and virtual machine, which is an unsupported behaviour. 
     */
    throw new EncryptionOperationNotPossibleException(
            "Neither a string encryptor nor a text encryptor exist " +
            "for this instance of EncryptableProperties. This is usually " +
            "caused by the instance having been serialized and then " +
            "de-serialized in a different classloader or virtual machine, " +
            "which is an unsupported behaviour (as encryptors cannot be " +
            "serialized themselves)");
    
}
 
示例12
private void handleInvalidKeyException(final InvalidKeyException e) {

        if ((e.getMessage() != null) && 
                ((e.getMessage().toUpperCase().indexOf("KEY SIZE") != -1))) {
            
            throw new EncryptionOperationNotPossibleException(
                    "Encryption raised an exception. A possible cause is " +
                    "you are using strong encryption algorithms and " +
                    "you have not installed the Java Cryptography " + 
                    "Extension (JCE) Unlimited Strength Jurisdiction " +
                    "Policy Files in this Java Virtual Machine");
            
        }
        
    }
 
示例13
/**
 * Creates an instance of the nifi sensitive property encryptor. Validates
 * that the encryptor is actually working.
 *
 * @param niFiProperties properties
 * @return encryptor
 * @throws EncryptionException if any issues arise initializing or
 * validating the encryptor
 */
public static StringEncryptor createEncryptor(final NiFiProperties niFiProperties) throws EncryptionException {

    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    final String sensitivePropAlgorithmVal = niFiProperties.getProperty(NF_SENSITIVE_PROPS_ALGORITHM);
    final String sensitivePropProviderVal = niFiProperties.getProperty(NF_SENSITIVE_PROPS_PROVIDER);
    final String sensitivePropValueNifiPropVar = niFiProperties.getProperty(NF_SENSITIVE_PROPS_KEY, DEFAULT_SENSITIVE_PROPS_KEY);

    if (StringUtils.isBlank(sensitivePropAlgorithmVal)) {
        throw new EncryptionException(NF_SENSITIVE_PROPS_ALGORITHM + "must bet set");
    }

    if (StringUtils.isBlank(sensitivePropProviderVal)) {
        throw new EncryptionException(NF_SENSITIVE_PROPS_PROVIDER + "must bet set");
    }

    if (StringUtils.isBlank(sensitivePropValueNifiPropVar)) {
        throw new EncryptionException(NF_SENSITIVE_PROPS_KEY + "must bet set");
    }

    final StringEncryptor nifiEncryptor;
    try {
        nifiEncryptor = new StringEncryptor(sensitivePropAlgorithmVal, sensitivePropProviderVal, sensitivePropValueNifiPropVar);
        //test that we can infact encrypt and decrypt something
        if (!nifiEncryptor.decrypt(nifiEncryptor.encrypt(TEST_PLAINTEXT)).equals(TEST_PLAINTEXT)) {
            throw new EncryptionException("NiFi property encryptor does appear to be working - decrypt/encrypt return invalid results");
        }

    } catch (final EncryptionInitializationException | EncryptionOperationNotPossibleException ex) {
        throw new EncryptionException("Cannot initialize sensitive property encryptor", ex);

    }
    return nifiEncryptor;
}
 
示例14
/**
 * Get system setting {@link SerializableOptional}. The return object is never
 * null in order to cache requests for system settings which have no value or default value.
 *
 * @param name the system setting name.
 * @param defaultValue the default value for the system setting.
 * @return an optional system setting value.
 */
private SerializableOptional getSystemSettingOptional( String name, Serializable defaultValue )
{
    SystemSetting setting = systemSettingStore.getByNameTx( name );

    if ( setting != null && setting.hasValue() )
    {
        if ( isConfidential( name ) )
        {
            try
            {
                return SerializableOptional.of( pbeStringEncryptor.decrypt( (String) setting.getDisplayValue() ) );
            }
            catch ( EncryptionOperationNotPossibleException e ) // Most likely this means the value is not encrypted or not existing
            {
                log.warn( "Could not decrypt system setting '" + name + "'" );
                return SerializableOptional.empty();
            }
        }
        else
        {
            return SerializableOptional.of( setting.getDisplayValue() );
        }
    }
    else
    {
        return SerializableOptional.of( defaultValue );
    }
}
 
示例15
/**
 * Decrypts the encrypted string using the configured encryptionPassword
 * 
 * @param encryptedStr
 *            The string to decrypt
 * @throws EncryptionOperationNotPossibleException
 *             When the encryptionPassword is not correct
 * @return The decrypted string
 */
public static String decrypt(String encryptedStr) 
		throws EncryptionOperationNotPossibleException {
	try {
		return getEncryptor().decrypt(encryptedStr);
	} catch (EncryptionOperationNotPossibleException e) {
		logger.error("Problem decrypting the encrypted string " 
				+ encryptedStr);
		throw e;
	}
}
 
示例16
@Override
public Json convertToEntityAttribute(String dbData) {
    String json;
    try {
        json = encryptor.decrypt(dbData);
    } catch (EncryptionOperationNotPossibleException e) {
        try {
            json = legacyEncryptor.decrypt(dbData);
        } catch (EncryptionOperationNotPossibleException ex) {
            json = dbData;
            LOGGER.info("Cannot decrypt the data. Null or empty: [{}]", StringUtils.isEmpty(dbData), ex);
        }
    }
    return super.convertToEntityAttribute(json);
}
 
示例17
static byte[] processBigIntegerEncryptedByteArray(
        final byte[] byteArray, final int signum) {
    
    // Check size
    if (byteArray.length > 4) {
        
        final int initialSize = byteArray.length;
        
        final byte[] encryptedMessageExpectedSizeBytes = new byte[4];
        System.arraycopy(byteArray, (initialSize - 4), encryptedMessageExpectedSizeBytes, 0, 4);
        
        final byte[] processedByteArray = new byte[initialSize - 4];
        System.arraycopy(byteArray, 0, processedByteArray, 0, (initialSize - 4));
        
        final int expectedSize = 
            NumberUtils.intFromByteArray(encryptedMessageExpectedSizeBytes);
        if (expectedSize < 0 || expectedSize > maxSafeSizeInBytes()) {
            throw new EncryptionOperationNotPossibleException();
        }

        // If expected and real sizes do not match, we will need to pad
        // (this happens because BigInteger removes 0x0's and -0x1's in
        // the leftmost side).
        if (processedByteArray.length != expectedSize) {

            // BigInteger can have removed, in the leftmost side:
            //      * 0x0's: for not being significative
            //      * -0x1's: for being translated as the "signum"
            final int sizeDifference = 
                (expectedSize - processedByteArray.length);

            final byte[] paddedProcessedByteArray = new byte[expectedSize];
            for (int i = 0; i < sizeDifference; i++) {
                paddedProcessedByteArray[i] = (signum >= 0)? (byte)0x0 : (byte)-0x1;
            }
                

            // Finally, the encrypted message bytes are represented
            // as they supposedly were when they were encrypted.
            System.arraycopy(processedByteArray, 0, paddedProcessedByteArray, sizeDifference, processedByteArray.length);
            
            return paddedProcessedByteArray;
            
        }
        
        return processedByteArray;
        
    }
        
    return (byte[]) byteArray.clone();
    
}
 
示例18
/**
 * <p>
 * Encrypts a message using the specified configuration.
 * </p>
 * <p>
 * The mechanisms applied to perform the encryption operation are described
 * in <a href="http://www.rsasecurity.com/rsalabs/node.asp?id=2127" 
 * target="_blank">PKCS &#035;5: Password-Based Cryptography Standard</a>.
 * </p>
 * <p>
 * This encryptor uses a salt for each encryption
 * operation. The size of the salt depends on the algorithm
 * being used. This salt is used
 * for creating the encryption key and, if generated by a random generator,
 * it is also appended unencrypted at the beginning
 * of the results so that a decryption operation can be performed.
 * </p>
 * <p>
 * <b>If a random salt generator is used, two encryption results for 
 * the same message will always be different
 * (except in the case of random salt coincidence)</b>. This may enforce
 * security by difficulting brute force attacks on sets of data at a time
 * and forcing attackers to perform a brute force attack on each separate
 * piece of encrypted data.
 * </p>
 * 
 * @param message the byte array message to be encrypted
 * @return the result of encryption 
 * @throws EncryptionOperationNotPossibleException if the encryption 
 *         operation fails, ommitting any further information about the
 *         cause for security reasons.
 * @throws EncryptionInitializationException if initialization could not
 *         be correctly done (for example, no password has been set).
 */
public byte[] encrypt(final byte[] message) 
        throws EncryptionOperationNotPossibleException {

    // Check initialization
    if (!isInitialized()) {
        initialize();
    }
    
    int poolPosition;
    synchronized(this) {
        poolPosition = this.roundRobin;
        this.roundRobin = (this.roundRobin + 1) % this.poolSize;
    }
    
    return this.pool[poolPosition].encrypt(message);
    
}
 
示例19
/**
 * <p>
 * Decrypts a message using the specified configuration.
 * </p>
 * <p>
 * The mechanisms applied to perform the decryption operation are described
 * in <a href="http://www.rsasecurity.com/rsalabs/node.asp?id=2127" 
 * target="_blank">PKCS &#035;5: Password-Based Cryptography Standard</a>.
 * </p>
 * <p>
 * If a random salt generator is used, this decryption operation will
 * expect to find an unencrypted salt at the 
 * beginning of the encrypted input, so that the decryption operation can be
 * correctly performed (there is no other way of knowing it).
 * </p>
 * 
 * @param encryptedMessage the byte array message to be decrypted
 * @return the result of decryption 
 * @throws EncryptionOperationNotPossibleException if the decryption 
 *         operation fails, ommitting any further information about the
 *         cause for security reasons.
 * @throws EncryptionInitializationException if initialization could not
 *         be correctly done (for example, no password has been set).
 */
public byte[] decrypt(final byte[] encryptedMessage) 
        throws EncryptionOperationNotPossibleException {

    // Check initialization
    if (!isInitialized()) {
        initialize();
    }
    
    int poolPosition;
    synchronized(this) {
        poolPosition = this.roundRobin;
        this.roundRobin = (this.roundRobin + 1) % this.poolSize;
    }
    
    return this.pool[poolPosition].decrypt(encryptedMessage);
    
}
 
示例20
/**
 * <p>
 * Checks a message against a given digest.
 * </p>
 * <p>
 * This method tells whether a message corresponds to a specific digest
 * or not by getting the salt with which the digest was created and
 * applying it to a digest operation performed on the message. If 
 * new and existing digest match, the message is said to match the digest.
 * </p>
 * <p>
 * This method will be used, for instance, for password checking in
 * authentication processes.
 * </p>
 * <p>
 * A null message will only match a null digest.
 * </p>
 * 
 * @param message the message to be compared to the digest.
 * @param digest the digest. 
 * @return true if the specified message matches the digest, false
 *         if not.
 * @throws EncryptionOperationNotPossibleException if the digest matching
 *         operation fails, ommitting any further information about the 
 *         cause for security reasons.
 * @throws EncryptionInitializationException if initialization could not
 *         be correctly done (for example, if the digest algorithm chosen
 *         cannot be used).
 */
public boolean matches(final byte[] message, final byte[] digest) {

    if (message == null) {
        return (digest == null);
    } else if (digest == null) {
        return false;
    }
    
    // Check initialization
    if (!isInitialized()) {
        initialize();
    }
        
    try {

        // If we are using a salt, extract it to use it.
        byte[] salt = null;
        if (this.useSalt) {
            // If we are using a salt generator which specifies the salt
            // to be included into the digest itself, get it from there.
            // If not, the salt is supposed to be fixed and thus the
            // salt generator can be safely asked for it again.
            if (this.saltGenerator.includePlainSaltInEncryptionResults()) {
                
                // Compute size figures and perform length checks
                int digestSaltSize = this.saltSizeBytes;
                if (this.digestLengthBytes > 0) {
                    if (this.useLenientSaltSizeCheck) {
                        if (digest.length < this.digestLengthBytes) {
                            throw new EncryptionOperationNotPossibleException();
                        }
                        digestSaltSize = digest.length - this.digestLengthBytes;
                    } else {
                        if (digest.length != (this.digestLengthBytes + this.saltSizeBytes)) {
                            throw new EncryptionOperationNotPossibleException();
                        }
                    }
                } else {
                    // Salt size check behaviour cannot be set to lenient
                    if (digest.length < this.saltSizeBytes) {
                        throw new EncryptionOperationNotPossibleException();
                    }
                }
                
                if (!this.invertPositionOfPlainSaltInEncryptionResults) {
                    salt = new byte[digestSaltSize];
                    System.arraycopy(digest, 0, salt, 0, digestSaltSize);
                } else {
                    salt = new byte[digestSaltSize];
                    System.arraycopy(digest, digest.length - digestSaltSize, salt, 0, digestSaltSize);
                }
                
            } else {
                salt = this.saltGenerator.generateSalt(this.saltSizeBytes);
            }
        }
        
        // Digest the message with the extracted digest.
        final byte[] encryptedMessage = digest(message, salt);
        
        // If, using the same salt, digests match, then messages too. 
        return (digestsAreEqual(encryptedMessage, digest));
    
    } catch (Exception e) {
        // If digest fails, it is more secure not to return any information
        // about the cause in nested exceptions. Simply fail.
        throw new EncryptionOperationNotPossibleException();
    }
    
}
 
示例21
/**
 * Encrypts the given clear text.
 *
 * @param clearText the message to encrypt
 *
 * @return the cipher text
 *
 * @throws EncryptionException if the encrypt fails
 */
public String encrypt(String clearText) throws EncryptionException {
    try {
        return encryptor.encrypt(clearText);
    } catch (final EncryptionOperationNotPossibleException | EncryptionInitializationException eonpe) {
        throw new EncryptionException(eonpe);
    }
}
 
示例22
/**
 * Decrypts the given cipher text.
 *
 * @param cipherText the message to decrypt
 *
 * @return the clear text
 *
 * @throws EncryptionException if the decrypt fails
 */
public String decrypt(String cipherText) throws EncryptionException {
    try {
        return encryptor.decrypt(cipherText);
    } catch (final EncryptionOperationNotPossibleException | EncryptionInitializationException eonpe) {
        throw new EncryptionException(eonpe);
    }
}
 
示例23
@Test
public void testUnMarshallWrongPassword() {

    envVariables.clear(com.quorum.tessera.config.util.EnvironmentVariables.CONFIG_SECRET_PATH);

    resolver = new EncryptedStringResolver();

    ByteArrayInputStream in = new ByteArrayInputStream(("bogus" + System.lineSeparator() + "bogus").getBytes());
    System.setIn(in);

    assertThatExceptionOfType(EncryptionOperationNotPossibleException.class)
            .isThrownBy(() -> resolver.resolve("ENC(KLa6pRQpxI8Ez3Bo6D3cI6y13YYdntu7)"));

    System.setIn(System.in);
}