Example usage for java.security KeyException KeyException

List of usage examples for java.security KeyException KeyException

Introduction

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

Prototype

public KeyException(String message, Throwable cause) 

Source Link

Document

Creates a KeyException with the specified detail message and cause.

Usage

From source file:org.ow2.proactive.authentication.crypto.HybridEncryptionUtil.java

public static byte[] decrypt(PrivateKey privateKey, String cipher, HybridEncryptedData encryptedData)
        throws KeyException {
    byte[] decryptedData;
    byte[] decryptedSymmetricKey;

    // recover clear AES key using the private key
    try {/*from w w  w .  jav  a  2  s  .  c  o  m*/
        decryptedSymmetricKey = KeyPairUtil.decrypt(privateKey, cipher,
                encryptedData.getEncryptedSymmetricKey());
    } catch (KeyException e) {
        throw new KeyException("Could not decrypt symmetric key", e);
    }

    // recover clear credentials using the AES key
    try {
        decryptedData = KeyUtil.decrypt(new SecretKeySpec(decryptedSymmetricKey, AES_ALGO), AES_CIPHER,
                encryptedData.getEncryptedData());
    } catch (KeyException e) {
        throw new KeyException("Could not decrypt data", e);
    }
    return decryptedData;
}

From source file:org.ow2.proactive.authentication.crypto.HybridEncryptionUtil.java

public static HybridEncryptedData encrypt(PublicKey publicKey, String cipher, byte[] message)
        throws KeyException {
    // generate symmetric key
    SecretKey aesKey = KeyUtil.generateKey(AES_ALGO, AES_KEYSIZE);

    byte[] encData;
    byte[] encAes;

    // encrypt AES key with public RSA key
    try {//from   ww  w  . j  a v a2 s.co m
        encAes = KeyPairUtil.encrypt(publicKey, cipher, aesKey.getEncoded());
    } catch (KeyException e) {
        throw new KeyException("Symmetric key encryption failed", e);
    }

    // encrypt clear credentials with AES key
    try {
        encData = KeyUtil.encrypt(aesKey, AES_CIPHER, message);
    } catch (KeyException e) {
        throw new KeyException("Message encryption failed", e);
    }
    return new HybridEncryptedData(encAes, encData);
}

From source file:org.ow2.proactive.authentication.crypto.Credentials.java

/**
 * Write the contents of a Credentials object to the disk
 * <p>//from  w  ww . ja va  2  s. c  o  m
 * Use the current value of the {@link org.ow2.proactive.authentication.crypto.Credentials#credentialsPathProperty}
 * property to determine the file to which the data will be written
 * <p>
 * Credentials are written to disk in base64 encoded form.
 * <p>
 * See {@link org.ow2.proactive.authentication.crypto.Credentials#getCredentials()} for the inverse operation
 * 
 * @param path file path where the credentials will be written on the disk
 * @throws KeyException Unable to locate or open file, IO error
 */
public void writeToDisk(String path) throws KeyException {
    File f = new File(path);
    FileOutputStream fs;
    try {
        fs = new FileOutputStream(f);
        fs.write(getBase64());
        fs.close();
    } catch (Exception e) {
        throw new KeyException("Could not write credentials to " + path, e);
    }
}

From source file:org.ow2.proactive.authentication.crypto.Credentials.java

/**
 * Retrieves a public key stored in a local file
 * <p>/*from w w w.  j  a  v a 2  s . c o  m*/
 * 
 * @param pubPath path to the public key on the local filesystem
 * @return the key encapsulated in a regular JCE container
 * @throws KeyException the key could not be retrieved or is malformed
 */
public static PublicKey getPublicKey(String pubPath) throws KeyException {
    byte[] bytes;
    File f = new File(pubPath);
    FileInputStream fin;

    String algo = "", tmp = "";

    // recover public key bytes
    try {
        fin = new FileInputStream(f);
        DataInputStream in = new DataInputStream(fin);
        int read, tot = 0;
        while ((read = in.read()) != '\n') {
            algo += (char) read;
            tot++;
        }
        tot++;
        while ((read = in.read()) != '\n') {
            tmp += (char) read;
            tot++;
        }
        tot++;

        bytes = new byte[(int) f.length() - tot];
        in.readFully(bytes);
        in.close();
    } catch (Exception e) {
        throw new KeyException("Could not retrieve public key from " + pubPath, e);
    }

    // reconstruct public key
    X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(bytes);
    PublicKey pubKey;
    KeyFactory keyFactory;

    try {
        keyFactory = KeyFactory.getInstance(algo);
    } catch (NoSuchAlgorithmException e) {
        throw new KeyException("Cannot initialize key factory", e);
    }

    try {
        pubKey = keyFactory.generatePublic(pubKeySpec);
    } catch (InvalidKeySpecException e) {
        throw new KeyException("Cannot re-generate public key", e);
    }

    return pubKey;
}

From source file:org.ow2.proactive.authentication.crypto.Credentials.java

/**
 * Retrieves a private key stored in a local file
 * <p>/*from   w  ww .  ja va2 s  .  co  m*/
 * Tries to guess the algorithm used for keypair generation which
 * is not included in the file. According to <a href="http://download.oracle.com/javase/1.5.0/docs/guide/security/CryptoSpec.html#AppA">Java Cryptography Specification</a>,
 * the algorithm can be only one of "RSA" or "DSA", so we can just try both using the
 * <code>algorithms</code> param. If the algorithm used to generate the key is neither RSA or DSA
 * (highly unlikely), this method cannot recreate the private key, but {@link #decrypt(String)}
 * maybe will.
 * 
 * @param privPath
 *            path to the private key on the local filesystem
 * @param algorithms a list of algorithms to try for creating the PK. Recommanded value:
 *          {"RSA","DSA"}
 * @return the key encapsulated in a regular JCE container
 * @throws KeyException
 *             the key could not be retrieved or is malformed, or the algorithm used for generation
 *             is not one of <code>algorithms</code>
 */
public static PrivateKey getPrivateKey(String privPath, String[] algorithms) throws KeyException {

    PrivateKey privKey = null;

    for (String algo : algorithms) {
        try {
            KeyFactory keyFactory;
            keyFactory = KeyFactory.getInstance(algo);

            // recover private key bytes
            byte[] bytes;
            try {
                File pkFile = new File(privPath);
                DataInputStream pkStream = new DataInputStream(new FileInputStream(pkFile));
                bytes = new byte[(int) pkFile.length()];
                pkStream.readFully(bytes);
                pkStream.close();
            } catch (Exception e) {
                throw new KeyException("Could not recover private key (algo=" + algo + ")", e);
            }

            // reconstruct private key
            PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(bytes);
            try {
                privKey = keyFactory.generatePrivate(privKeySpec);
            } catch (InvalidKeySpecException e) {
                throw new KeyException("Cannot re-generate private key  (algo=" + algo + ")", e);
            }
        } catch (Exception e) {
        }
    }

    if (privKey == null) {
        String str = "Could not generate Private Key (algorithms: ";
        for (String algo : algorithms) {
            str += algo + " ";
        }
        str += ")";
        throw new KeyException(str);
    }

    return privKey;
}

From source file:org.ow2.proactive.authentication.crypto.Credentials.java

/**
 * Retrieves a credentials from disk/*from  w  ww . j  av a  2s .c  om*/
 * <p>
 * See {@link org.ow2.proactive.authentication.crypto.Credentials#writeToDisk(String)} for details on how information is
 * stored on disk.
 * 
 * @param path to the file in which credentials are stored
 * @return the Credentials object represented by the file located at <code>path</code>
 * @throws KeyException Credentials could not be recovered
 */
public static Credentials getCredentials(String path) throws KeyException {
    File f = new File(path);
    byte[] bytes = new byte[(int) f.length()];
    FileInputStream fin;
    try {
        fin = new FileInputStream(f);
        fin.read(bytes);
        fin.close();
    } catch (Exception e) {
        throw new KeyException("Could not read credentials from " + path, e);
    }
    return getCredentialsBase64(bytes);
}

From source file:org.opensaml.xml.security.SecurityHelper.java

/**
 * Derives the public key from either a DSA or RSA private key.
 * //from  w w  w . ja  v a2  s.c  om
 * @param key the private key to derive the public key from
 * 
 * @return the derived public key
 * 
 * @throws KeyException thrown if the given private key is not a DSA or RSA key or there is a problem generating the
 *             public key
 */
public static PublicKey derivePublicKey(PrivateKey key) throws KeyException {
    KeyFactory factory;
    if (key instanceof DSAPrivateKey) {
        DSAPrivateKey dsaKey = (DSAPrivateKey) key;
        DSAParams keyParams = dsaKey.getParams();
        BigInteger y = keyParams.getQ().modPow(dsaKey.getX(), keyParams.getP());
        DSAPublicKeySpec pubKeySpec = new DSAPublicKeySpec(y, keyParams.getP(), keyParams.getQ(),
                keyParams.getG());

        try {
            factory = KeyFactory.getInstance("DSA");
            return factory.generatePublic(pubKeySpec);
        } catch (GeneralSecurityException e) {
            throw new KeyException("Unable to derive public key from DSA private key", e);
        }
    } else if (key instanceof RSAPrivateCrtKey) {
        RSAPrivateCrtKey rsaKey = (RSAPrivateCrtKey) key;
        RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(rsaKey.getModulus(), rsaKey.getPublicExponent());

        try {
            factory = KeyFactory.getInstance("RSA");
            return factory.generatePublic(pubKeySpec);
        } catch (GeneralSecurityException e) {
            throw new KeyException("Unable to derive public key from RSA private key", e);
        }
    } else {
        throw new KeyException("Private key was not a DSA or RSA key");
    }
}

From source file:org.ow2.proactive.authentication.crypto.Credentials.java

/**
 * Creates a Credentials given its base64 encoded representation
 * //from   w  w  w . ja va  2s.  c  o m
 * @param base64enc the Credentials representation as a base64 encoded byte array,
 *  as returned by {@link Credentials#getBase64()}
 * @return the Credentials object corresponding the <code>base64en</code> representation
 * @throws KeyException
 */
public static Credentials getCredentialsBase64(byte[] base64enc) throws KeyException {
    String algo = "", cipher = "", tmp = "";
    byte[] data;
    byte[] aes;
    int size;
    byte[] asciiEnc;

    try {
        asciiEnc = Base64.decodeBase64(base64enc);
    } catch (Exception e) {
        throw new KeyException("Unable to decode base64 credentials", e);
    }

    try {
        DataInputStream in = new DataInputStream(new ByteArrayInputStream(asciiEnc));
        int read, tot = 0;
        while ((read = in.read()) != '\n') {
            if (read == -1)
                throw new KeyException("Failed to parse malformed credentials");
            algo += (char) read;
            tot++;
        }
        tot++;
        while ((read = in.read()) != '\n') {
            if (read == -1)
                throw new KeyException("Failed to parse malformed credentials");
            tmp += (char) read;
            tot++;
        }
        tot++;
        size = Integer.parseInt(tmp);
        while ((read = in.read()) != '\n') {
            if (read == -1)
                throw new KeyException("Failed to parse malformed credentials");
            cipher += (char) read;
            tot++;
        }
        tot++;
        aes = new byte[size / 8];
        for (int i = 0; i < size / 8; i++) {
            aes[i] = (byte) in.read();
            tot++;
        }

        data = new byte[asciiEnc.length - tot];
        in.readFully(data);
    } catch (Exception e) {
        throw new KeyException("Could not decode credentials", e);
    }

    return new Credentials(algo, size, cipher, aes, data);
}

From source file:org.opensaml.xml.security.SecurityHelper.java

/**
 * Decodes RSA/DSA private keys in DER, PEM, or PKCS#8 (encrypted or unencrypted) formats.
 * //from w  w  w  .  ja v a 2  s.  c o m
 * @param key encoded key
 * @param password decryption password or null if the key is not encrypted
 * 
 * @return deocded private key
 * 
 * @throws KeyException thrown if the key can not be decoded
 */
public static PrivateKey decodePrivateKey(byte[] key, char[] password) throws KeyException {
    try {
        PKCS8Key deocodedKey = new PKCS8Key(key, password);
        return deocodedKey.getPrivateKey();
    } catch (GeneralSecurityException e) {
        throw new KeyException("Unable to decode private key", e);
    }
}

From source file:org.ow2.proactive.authentication.crypto.Credentials.java

/**
 * Returns a representation of this credentials as a base64 encoded byte array
 * <p>/*from  w  ww  .j  a  va2 s .  co m*/
 * Prior to base64 encoding, format is the following:
 * <ul>
 * <li>The key generation algorithm, in human readable format, on a single
 * line
 * <li>The key size, in human readable format, on a single line
 * <li>The cipher parameters, in human readable format, on a single line
 * <li>The encrypted AES key, which should be exactly <code>size / 8</code> bytes
 * <li>The encrypted data, which can be of arbitrary length, should occupy the rest of the file
 * </ul>
 * @throws KeyException
 */
public byte[] getBase64() throws KeyException {
    ByteArrayOutputStream b = new ByteArrayOutputStream();
    try {
        b.write((algorithm + '\n').getBytes());
        b.write(("" + size + '\n').getBytes());
        b.write((cipher + '\n').getBytes());
        b.write(this.aes);
        b.write(this.data);
    } catch (IOException e) {

    }
    byte[] ret;
    try {
        ret = Base64.encodeBase64(b.toByteArray());
    } catch (Exception e) {
        throw new KeyException("Unable to encode credentials to base64", e);
    }
    return ret;
}