Example usage for java.security InvalidKeyException getMessage

List of usage examples for java.security InvalidKeyException getMessage

Introduction

In this page you can find the example usage for java.security InvalidKeyException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:by.bsuir.chujko.model.entities.security.StringCrypter.java

/**
 * //  w w w  . j a  v  a2  s  .  co m
 * Simplified constructor. Creates StringCrypter with a 
 * DESSecretKey (encryption algorithm DES) with the value of the key. 
 * 
 * @param key must have a length of 8 bytes.
 */
public StringCrypter(byte[] key) {
    try {
        updateSecretKey(new DESSecretKey(key));
    } catch (InvalidKeyException ex) {
        throw new IllegalArgumentException(ex.getMessage());
    } catch (NoSuchPaddingException ex) {
        Logger.getLogger(StringCrypter.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(StringCrypter.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.apache.james.jdkim.IscheduleDKIMSigner.java

public String sign(final Headers reqHeaders, final BodyHasher bh) throws PermFailException {
    if (!(bh instanceof BodyHasherImpl)) {
        throw new PermFailException("Supplied BodyHasher has not been generated with this signer");
    }/*from   w w w .  j a va  2 s  .  com*/
    BodyHasherImpl bhj = (BodyHasherImpl) bh;
    byte[] computedHash = bhj.getDigest();

    bhj.getSignatureRecord().setBodyHash(computedHash);

    List<CharSequence> headers = bhj.getSignatureRecord().getHeaders();
    try {
        // TODO handle b= in SignatureRecord.
        // whenever any tag is changed the b should be invalidated and the
        // text representation lost.
        // whenever the b value is regenerated it should also be associated
        // with the right test representation.
        // we need a method to "regenerate the text representation" and to
        // retrieve it when it is valid.
        byte[] signatureHash = signatureSign(reqHeaders, bhj.getSignatureRecord(), privateKey, headers);

        bhj.getSignatureRecord().setSignature(signatureHash);

        return "DKIM-Signature:" + bhj.getSignatureRecord().toString();
    } catch (InvalidKeyException e) {
        throw new PermFailException("Invalid key: " + e.getMessage(), e);
    } catch (NoSuchAlgorithmException e) {
        throw new PermFailException("Unknown algorithm: " + e.getMessage(), e);
    } catch (SignatureException e) {
        throw new PermFailException("Signing exception: " + e.getMessage(), e);
    }
}

From source file:org.apache.james.jdkim.DKIMSigner.java

public String sign(Headers message, BodyHasher bh) throws PermFailException {
    if (!(bh instanceof BodyHasherImpl)) {
        throw new PermFailException("Supplied BodyHasher has not been generated with this signer");
    }//from  w w w . j av  a  2 s  . c  o  m
    BodyHasherImpl bhj = (BodyHasherImpl) bh;
    byte[] computedHash = bhj.getDigest();

    bhj.getSignatureRecord().setBodyHash(computedHash);

    List<CharSequence> headers = bhj.getSignatureRecord().getHeaders();
    try {
        // TODO handle b= in SignatureRecord.
        // whenever any tag is changed the b should be invalidated and the
        // text representation lost.
        // whenever the b value is regenerated it should also be associated
        // with the right test representation.
        // we need a method to "regenerate the text representation" and to
        // retrieve it when it is valid.
        byte[] signatureHash = signatureSign(message, bhj.getSignatureRecord(), privateKey, headers);

        bhj.getSignatureRecord().setSignature(signatureHash);

        return "DKIM-Signature:" + bhj.getSignatureRecord().toString();
    } catch (InvalidKeyException e) {
        throw new PermFailException("Invalid key: " + e.getMessage(), e);
    } catch (NoSuchAlgorithmException e) {
        throw new PermFailException("Unknown algorythm: " + e.getMessage(), e);
    } catch (SignatureException e) {
        throw new PermFailException("Signing exception: " + e.getMessage(), e);
    }
}

From source file:org.jets3t.service.multi.DownloadPackage.java

/**
 * Creates an output stream to receive the object's data. The output stream is either
 * the output stream provided to this package in its constructor, or an
 * automatically-created FileOutputStream if a File object was provided as the target
 * output object. The output stream will also be wrapped in a GZipInflatingOutputStream if
 * isUnzipping is true and/or a decrypting output stream if this package has an associated
 * non-null EncryptionUtil.//from   ww w.j av  a 2  s.  c o  m
 *
 * @return
 * an output stream that writes data to the output target managed by this class.
 *
 * @throws IOException
 */
public OutputStream getOutputStream() throws IOException {
    OutputStream outputStream = null;
    if (outputFile != null) {
        // Create parent directories for file, if necessary.
        if (outputFile.getParentFile() != null) {
            outputFile.getParentFile().mkdirs();
        }

        outputStream = new FileOutputStream(outputFile, appendToFile);
    } else {
        outputStream = this.outputStream;
    }

    if (isUnzipping) {
        log.debug("Inflating gzipped data for object: " + object.getKey());
        outputStream = new GZipInflatingOutputStream(outputStream);
    }
    if (encryptionUtil != null) {
        log.debug("Decrypting encrypted data for object: " + object.getKey());
        try {
            outputStream = encryptionUtil.decrypt(outputStream);
        } catch (InvalidKeyException e) {
            final IOException exception = new IOException(e.getMessage());
            exception.initCause(e);
            throw exception;
        } catch (InvalidAlgorithmParameterException e) {
            final IOException exception = new IOException(e.getMessage());
            exception.initCause(e);
            throw exception;
        } catch (NoSuchAlgorithmException e) {
            final IOException exception = new IOException(e.getMessage());
            exception.initCause(e);
            throw exception;
        } catch (NoSuchPaddingException e) {
            final IOException exception = new IOException(e.getMessage());
            exception.initCause(e);
            throw exception;
        }
    }
    return outputStream;
}

From source file:org.apache.accumulo.core.security.crypto.CachingHDFSSecretKeyEncryptionStrategy.java

private void doKeyEncryptionOperation(int encryptionMode, CryptoModuleParameters params) throws IOException {
    Cipher cipher = DefaultCryptoModuleUtils
            .getCipher(params.getAllOptions().get(Property.CRYPTO_DEFAULT_KEY_STRATEGY_CIPHER_SUITE.getKey()));

    try {//from w w w  . jav  a2 s.co  m
        cipher.init(encryptionMode,
                new SecretKeySpec(secretKeyCache.getKeyEncryptionKey(), params.getAlgorithmName()));
    } catch (InvalidKeyException e) {
        log.error("{}", e.getMessage(), e);
        throw new RuntimeException(e);
    }

    if (Cipher.UNWRAP_MODE == encryptionMode) {
        try {
            Key plaintextKey = cipher.unwrap(params.getEncryptedKey(), params.getAlgorithmName(),
                    Cipher.SECRET_KEY);
            params.setPlaintextKey(plaintextKey.getEncoded());
        } catch (InvalidKeyException e) {
            log.error("{}", e.getMessage(), e);
            throw new RuntimeException(e);
        } catch (NoSuchAlgorithmException e) {
            log.error("{}", e.getMessage(), e);
            throw new RuntimeException(e);
        }
    } else {
        Key plaintextKey = new SecretKeySpec(params.getPlaintextKey(), params.getAlgorithmName());
        try {
            byte[] encryptedSecretKey = cipher.wrap(plaintextKey);
            params.setEncryptedKey(encryptedSecretKey);
            params.setOpaqueKeyEncryptionKeyID(secretKeyCache.getPathToKeyName());
        } catch (InvalidKeyException e) {
            log.error("{}", e.getMessage(), e);
            throw new RuntimeException(e);
        } catch (IllegalBlockSizeException e) {
            log.error("{}", e.getMessage(), e);
            throw new RuntimeException(e);
        }

    }
}

From source file:com.lightszentip.module.security.password.PasswordModuleImpl.java

private String crypt(String value, String key, EncryptionType type, int optmode) {
    try {/*  w  w w  .ja  v  a 2s  .c  o m*/
        Cipher cipher = Cipher.getInstance(type.getText());
        String passwordSecret = null;
        cipher.init(optmode, new SecretKeySpec((key).getBytes(), type.getText()));
        if (optmode == Cipher.ENCRYPT_MODE) {
            passwordSecret = Base64.encodeBase64String(cipher.doFinal(value.getBytes()));
        } else {
            passwordSecret = new String(cipher.doFinal(Base64.decodeBase64(value)));
        }
        return passwordSecret;
    } catch (InvalidKeyException e) {
        throw new CryptionException(e.getMessage(), e);
    } catch (IllegalBlockSizeException e) {
        throw new CryptionException(e.getMessage(), e);
    } catch (BadPaddingException e) {
        throw new CryptionException(e.getMessage(), e);
    } catch (NoSuchAlgorithmException e) {
        throw new CryptionException(e.getMessage(), e);
    } catch (NoSuchPaddingException e) {
        throw new CryptionException(e.getMessage(), e);
    }
}

From source file:org.dasein.cloud.qingcloud.util.requester.QingCloudRequestBuilder.java

private String doMac(byte[] accessKeySecret, String stringToSign) throws InternalException {
    String signature;// w  ww  .  j ava 2s.  c o  m
    try {
        Mac mac = Mac.getInstance(SIGNATURE_ALGORITHM);
        mac.init(new SecretKeySpec(accessKeySecret, SIGNATURE_ALGORITHM));
        byte[] signedData = mac.doFinal(stringToSign.getBytes(ENCODING));
        signature = new String(Base64.encodeBase64(signedData));
    } catch (NoSuchAlgorithmException noSuchAlgorithmException) {
        logger.error("AliyunRequestBuilderStrategy.sign() failed due to algorithm not supported: "
                + noSuchAlgorithmException.getMessage());
        throw new InternalException(noSuchAlgorithmException);
    } catch (InvalidKeyException invalidKeyException) {
        logger.error("AliyunRequestBuilderStrategy.sign() failed due to key invalid: "
                + invalidKeyException.getMessage());
        throw new InternalException(invalidKeyException);
    } catch (UnsupportedEncodingException unsupportedEncodingException) {
        logger.error("AliyunMethod.sign() failed due to encoding not supported: "
                + unsupportedEncodingException.getMessage());
        throw new InternalException(unsupportedEncodingException);
    }
    return signature;
}

From source file:org.apache.juddi.v3.auth.CryptedXMLDocAuthenticator.java

/**
 *
 */// w w  w  .ja  v a2 s  .c  o m
private String encrypt(String str) throws FatalErrorException {
    try {
        Cryptor cryptor = (Cryptor) CryptorFactory.getCryptor();
        return cryptor.encrypt(str);
    } catch (InvalidKeyException e) {
        logger.error("Invalid Key Exception in crypting the password", e);
        throw new FatalErrorException(new ErrorMessage("errors.auth.cryptor.InvalidKey", e.getMessage()));
    } catch (NoSuchPaddingException e) {
        logger.error("Padding Exception in crypting the password", e);
        throw new FatalErrorException(new ErrorMessage("errors.auth.cryptor.Padding", e.getMessage()));
    } catch (NoSuchAlgorithmException e) {
        logger.error("Algorithm Exception in crypting the password", e);
        throw new FatalErrorException(new ErrorMessage("errors.auth.cryptor.Algorithm", e.getMessage()));
    } catch (InvalidAlgorithmParameterException e) {
        logger.error("Algorithm parameter Exception in crypting the password", e);
        throw new FatalErrorException(new ErrorMessage("errors.auth.cryptor.AlgorithmParam", e.getMessage()));
    } catch (IllegalBlockSizeException e) {
        logger.error("Block size Exception in crypting the password", e);
        throw new FatalErrorException(new ErrorMessage("errors.auth.cryptor.BlockSize", e.getMessage()));
    } catch (BadPaddingException e) {
        logger.error("Bad Padding Exception in crypting the password", e);
        throw new FatalErrorException(new ErrorMessage("errors.auth.cryptor.BadPadding", e.getMessage()));
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        throw new FatalErrorException(new ErrorMessage("errors.auth.cryptor.BlockSize", e.getMessage()));
    }
}

From source file:nl.esciencecenter.octopus.webservice.mac.MacScheme.java

/**
 * Computes RFC 2104-compliant HMAC signature.
 *
 * @param data/*from  w w w .j ava2 s.c  o m*/
 *            The data to be signed.
 * @param key
 *            The signing key.
 * @param algorithm
 *            MAC algorithm implemented by javax.crypto.MAC
 * @return The Base64-encoded RFC 2104-compliant HMAC signature.
 * @throws AuthenticationException
 *             when signature generation fails
 */
private String calculateRFC2104HMAC(String data, String key, String algorithm) throws AuthenticationException {
    try {
        Mac mac = Mac.getInstance(algorithm);
        SecretKeySpec macKey = new SecretKeySpec(key.getBytes(), "RAW");
        mac.init(macKey);
        byte[] signature = mac.doFinal(data.getBytes());
        return Base64.encodeBase64String(signature);
    } catch (InvalidKeyException e) {
        throw new AuthenticationException("Failed to generate HMAC: " + e.getMessage(), e);
    } catch (NoSuchAlgorithmException e) {
        throw new AuthenticationException("Algorithm is not supported", e);
    }
}

From source file:nl.esciencecenter.osmium.mac.MacScheme.java

/**
 * Computes RFC 2104-compliant HMAC signature.
 *
 * @param data/*from w  w  w  . j  ava  2  s  . com*/
 *            The data to be signed.
 * @param key
 *            The signing key.
 * @param algorithm
 *            MAC algorithm implemented by javax.crypto.MAC
 * @return The Base64-encoded RFC 2104-compliant HMAC signature.
 * @throws AuthenticationException
 *             when signature generation fails
 */
private String calculateRFC2104HMAC(String data, String key, String algorithm) throws AuthenticationException {
    try {
        Mac mac = Mac.getInstance(algorithm);
        SecretKeySpec macKey = new SecretKeySpec(key.getBytes(StandardCharsets.US_ASCII), "RAW");
        mac.init(macKey);
        byte[] signature = mac.doFinal(data.getBytes(StandardCharsets.US_ASCII));
        return Base64.encodeBase64String(signature);
    } catch (InvalidKeyException e) {
        throw new AuthenticationException("Failed to generate HMAC: " + e.getMessage(), e);
    } catch (NoSuchAlgorithmException e) {
        throw new AuthenticationException("Algorithm is not supported", e);
    }
}