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(Throwable cause) 

Source Link

Document

Creates a KeyException with the specified cause and a detail message of (cause==null ?

Usage

From source file:org.apache.hadoop.hbase.security.EncryptionUtil.java

private static Key getUnwrapKey(Configuration conf, String subject, EncryptionProtos.WrappedKey wrappedKey,
        Cipher cipher) throws IOException, KeyException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    byte[] iv = wrappedKey.hasIv() ? wrappedKey.getIv().toByteArray() : null;
    Encryption.decryptWithSubjectKey(out, wrappedKey.getData().newInput(), wrappedKey.getLength(), subject,
            conf, cipher, iv);/*  w w  w . ja  v  a2s  .com*/
    byte[] keyBytes = out.toByteArray();
    if (wrappedKey.hasHash()) {
        if (!Bytes.equals(wrappedKey.getHash().toByteArray(), Encryption.hash128(keyBytes))) {
            throw new KeyException("Key was not successfully unwrapped");
        }
    }
    return new SecretKeySpec(keyBytes, wrappedKey.getAlgorithm());
}

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

/**
 * Generates a random Java JCE symmetric Key object from the specified XML Encryption algorithm URI.
 * //from   ww  w .j  a v a  2s.c  om
 * @param algoURI The XML Encryption algorithm URI
 * @return a randomly-generated symmetric Key
 * @throws NoSuchAlgorithmException thrown if the specified algorithm is invalid
 * @throws KeyException thrown if the length of the key to generate could not be determined
 */
public static SecretKey generateSymmetricKey(String algoURI) throws NoSuchAlgorithmException, KeyException {
    String jceAlgorithmName = getKeyAlgorithmFromURI(algoURI);
    if (DatatypeHelper.isEmpty(jceAlgorithmName)) {
        log.error("Mapping from algorithm URI '" + algoURI
                + "' to key algorithm not available, key generation failed");
        throw new NoSuchAlgorithmException("Algorithm URI'" + algoURI + "' is invalid for key generation");
    }
    Integer keyLength = getKeyLengthFromURI(algoURI);
    if (keyLength == null) {
        log.error("Key length could not be determined from algorithm URI, can't generate key");
        throw new KeyException("Key length not determinable from algorithm URI, could not generate new key");
    }
    KeyGenerator keyGenerator = KeyGenerator.getInstance(jceAlgorithmName);
    keyGenerator.init(keyLength);
    return keyGenerator.generateKey();
}

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

/**
 * Generates a random Java JCE symmetric Key object from the specified XML Encryption algorithm URI.
 * //from  w w  w . j ava2 s .c om
 * @param algoURI The XML Encryption algorithm URI
 * @return a randomly-generated symmetric Key
 * @throws NoSuchAlgorithmException thrown if the specified algorithm is invalid
 * @throws KeyException thrown if the length of the key to generate could not be determined
 */
public static SecretKey generateSymmetricKey(String algoURI) throws NoSuchAlgorithmException, KeyException {
    Logger log = getLogger();
    String jceAlgorithmName = getKeyAlgorithmFromURI(algoURI);
    if (StringSupport.isNullOrEmpty(jceAlgorithmName)) {
        log.error("Mapping from algorithm URI '" + algoURI
                + "' to key algorithm not available, key generation failed");
        throw new NoSuchAlgorithmException("Algorithm URI'" + algoURI + "' is invalid for key generation");
    }
    Integer keyLength = getKeyLengthFromURI(algoURI);
    if (keyLength == null) {
        log.error("Key length could not be determined from algorithm URI, can't generate key");
        throw new KeyException("Key length not determinable from algorithm URI, could not generate new key");
    }
    KeyGenerator keyGenerator = KeyGenerator.getInstance(jceAlgorithmName);
    keyGenerator.init(keyLength);
    return keyGenerator.generateKey();
}

From source file:org.csploit.android.services.UpdateService.java

/**
 * check if an archive is valid by reading it.
 * @throws RuntimeException if trying to run this with no archive
 *//*from   w  ww.  ja  va  2s.  c o  m*/
private void verifyArchiveIntegrity() throws RuntimeException, KeyException {
    File f;
    long total;
    short old_percentage, percentage;
    CountingInputStream counter;
    ArchiveInputStream is;
    byte[] buffer;
    String rootDirectory;

    Logger.info("verifying archive integrity");

    if (mCurrentTask == null || mCurrentTask.path == null)
        throw new RuntimeException("no archive to test");

    mBuilder.setContentTitle(getString(R.string.checking)).setSmallIcon(android.R.drawable.ic_popup_sync)
            .setContentText("").setContentInfo("").setProgress(100, 0, true);
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());

    f = new File(mCurrentTask.path);
    try {
        counter = new CountingInputStream(new FileInputStream(f));
    } catch (FileNotFoundException e) {
        throw new RuntimeException(String.format("archive '%s' does not exists", mCurrentTask.path));
    }

    try {
        is = openArchiveStream(counter);
        ArchiveEntry entry;
        buffer = new byte[2048];
        total = f.length();
        old_percentage = -1;
        rootDirectory = null;

        // consume the archive
        while (mRunning && (entry = is.getNextEntry()) != null) {
            if (!mCurrentTask.skipRoot)
                continue;

            String name = entry.getName();

            if (rootDirectory == null) {
                if (name.contains("/")) {
                    rootDirectory = name.substring(0, name.indexOf('/'));
                } else if (entry.isDirectory()) {
                    rootDirectory = name;
                } else {
                    throw new IOException(
                            String.format("archive '%s' contains files under it's root", mCurrentTask.path));
                }
            } else {
                if (!name.startsWith(rootDirectory)) {
                    throw new IOException("multiple directories found in the archive root");
                }
            }
        }

        while (mRunning && is.read(buffer) > 0) {
            percentage = (short) (((double) counter.getBytesRead() / total) * 100);
            if (percentage != old_percentage) {
                mBuilder.setProgress(100, percentage, false).setContentInfo(percentage + "%");
                mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
                old_percentage = percentage;
            }
        }
    } catch (IOException e) {
        throw new KeyException("corrupted archive: " + e.getMessage());
    } finally {
        try {
            counter.close();
        } catch (IOException ignore) {
        }
    }

    if (!mRunning)
        throw new CancellationException("archive integrity check cancelled");

    if (mCurrentTask.skipRoot && rootDirectory == null)
        throw new KeyException(String.format("archive '%s' is empty", mCurrentTask.path));
}

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

/**
 * Creates new encrypted credentials/*from w  ww .ja  va2s. c o  m*/
 * <p>
 * Encrypts the message '<code>credData</code>' using the
 * public key <code>pubKey</code> and <code>cipher</code>
 * and store it in a new Credentials object.
 *
 * @see KeyPairUtil#encrypt(PublicKey, String, byte[])
 * @param cc, the class containing the data to be crypted
 * @param pubKey public key used for encryption
 * @param cipher cipher parameters: combination of transformations
 * @return the Credentials object containing the encrypted data
 * @throws KeyException key generation or encryption failed
 */
public static Credentials createCredentials(final CredData cc, final PublicKey pubKey, final String cipher)
        throws KeyException {
    // serialize clear credentials to byte array
    byte[] clearCred;
    try {
        clearCred = ObjectToByteConverter.ObjectStream.convert(cc);
    } catch (IOException e1) {
        throw new KeyException(e1.getMessage());
    }

    HybridEncryptionUtil.HybridEncryptedData encryptedData = HybridEncryptionUtil.encrypt(pubKey, cipher,
            clearCred);
    byte[] encAes = encryptedData.getEncryptedSymmetricKey();
    byte[] encData = encryptedData.getEncryptedData();

    int size = keySize(pubKey);
    return new Credentials(pubKey.getAlgorithm(), size, cipher, encAes, encData);
}

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

/**
 * Decrypts the encapsulated credentials
 *
 * @see org.ow2.proactive.authentication.crypto.KeyPairUtil#decrypt(PrivateKey, String, byte[])
 * @param privKey the private key/*from w ww.ja va  2s  .  co m*/
 * @return the credential data containing the clear data:login, password and key
 * @throws KeyException decryption failure, malformed data
 */
public CredData decrypt(PrivateKey privKey) throws KeyException {
    byte[] decryptedData = HybridEncryptionUtil.decrypt(privKey, this.cipher,
            new HybridEncryptionUtil.HybridEncryptedData(aes, data));

    // deserialize clear credentials and obtain login & password
    try {
        return (CredData) ByteToObjectConverter.ObjectStream.convert(decryptedData);
    } catch (Exception e) {
        throw new KeyException(e.getMessage());
    }

}

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

/**
 * Creates new encrypted credentials//from   w ww . j a  v  a2s  .  co  m
 * <p>
 * Encrypts the message '<code>login</code>:<code>password</code>' using the
 * public key <code>pubKey</code> and <code>cipher</code>
 * and store it in a new Credentials object.
 * 
 * @see KeyPairUtil#encrypt(PublicKey, String, byte[])
 * @param login the login to encrypt
 * @param password the corresponding password to encrypt
 * @param pubKey public key used for encryption
 * @param cipher cipher parameters: combination of transformations
 * @return the Credentials object containing the encrypted data
 * @throws KeyException key generation or encryption failed
 */
@Deprecated
public static Credentials createCredentials(String login, String password, byte[] datakey, PublicKey pubKey,
        String cipher) throws KeyException {

    CredData cc = new CredData();
    cc.setLogin(CredData.parseLogin(login));
    cc.setDomain(CredData.parseDomain(login));
    cc.setPassword(password);
    cc.setKey(datakey);

    // serialize clear credentials to byte array
    byte[] clearCred;
    try {
        clearCred = ObjectToByteConverter.ObjectStream.convert(cc);
    } catch (IOException e1) {
        throw new KeyException(e1.getMessage());
    }

    int size = keySize(pubKey);

    HybridEncryptionUtil.HybridEncryptedData encryptedData = HybridEncryptionUtil.encrypt(pubKey, cipher,
            clearCred);
    byte[] encAes = encryptedData.getEncryptedSymmetricKey();
    byte[] encData = encryptedData.getEncryptedData();

    return new Credentials(pubKey.getAlgorithm(), size, cipher, encAes, encData);
}

From source file:it.evilsocket.dsploit.core.UpdateService.java

/**
 * check if an archive is valid by reading it.
 * @throws RuntimeException if trying to run this with no archive
 *///from w w  w . j  av a 2s . co m
private void verifyArchiveIntegrity() throws RuntimeException, KeyException {
    File f;
    long total;
    short old_percentage, percentage;
    CountingInputStream counter;
    ArchiveInputStream is;
    byte[] buffer;
    boolean dirToExtractFound;

    Logger.info("verifying archive integrity");

    if (mCurrentTask == null || mCurrentTask.path == null)
        throw new RuntimeException("no archive to test");

    mBuilder.setContentTitle(getString(R.string.checking)).setSmallIcon(android.R.drawable.ic_popup_sync)
            .setContentText("").setProgress(100, 0, false);
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());

    f = new File(mCurrentTask.path);
    try {
        counter = new CountingInputStream(new FileInputStream(f));
    } catch (FileNotFoundException e) {
        throw new RuntimeException(String.format("archive '%s' does not exists", mCurrentTask.path));
    }

    dirToExtractFound = mCurrentTask.dirToExtract == null;

    try {
        is = openArchiveStream(counter);
        ArchiveEntry entry;
        buffer = new byte[2048];
        total = f.length();
        old_percentage = -1;
        // consume the archive
        while (mRunning && (entry = is.getNextEntry()) != null)
            if (!dirToExtractFound && entry.getName().startsWith(mCurrentTask.dirToExtract))
                dirToExtractFound = true;
        while (mRunning && is.read(buffer) > 0) {
            percentage = (short) (((double) counter.getBytesRead() / total) * 100);
            if (percentage != old_percentage) {
                mBuilder.setProgress(100, percentage, false).setContentInfo(percentage + "%");
                mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
                old_percentage = percentage;
            }
        }
    } catch (IOException e) {
        throw new KeyException("corrupted archive: " + e.getMessage());
    }

    if (!mRunning)
        throw new CancellationException("archive integrity check cancelled");

    if (!dirToExtractFound)
        throw new KeyException(String.format("archive '%s' does not contains required '%s' directory",
                mCurrentTask.path, mCurrentTask.dirToExtract));
}

From source file:org.csploit.android.core.UpdateService.java

/**
 * check if an archive is valid by reading it.
 * @throws RuntimeException if trying to run this with no archive
 *///w  w  w .j a  v a 2  s.  c o m
private void verifyArchiveIntegrity() throws RuntimeException, KeyException {
    File f;
    long total;
    short old_percentage, percentage;
    CountingInputStream counter;
    ArchiveInputStream is;
    byte[] buffer;
    String rootDirectory;

    Logger.info("verifying archive integrity");

    if (mCurrentTask == null || mCurrentTask.path == null)
        throw new RuntimeException("no archive to test");

    mBuilder.setContentTitle(getString(R.string.checking)).setSmallIcon(android.R.drawable.ic_popup_sync)
            .setContentText("").setProgress(100, 0, false);
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());

    f = new File(mCurrentTask.path);
    try {
        counter = new CountingInputStream(new FileInputStream(f));
    } catch (FileNotFoundException e) {
        throw new RuntimeException(String.format("archive '%s' does not exists", mCurrentTask.path));
    }

    try {
        is = openArchiveStream(counter);
        ArchiveEntry entry;
        buffer = new byte[2048];
        total = f.length();
        old_percentage = -1;
        rootDirectory = null;

        // consume the archive
        while (mRunning && (entry = is.getNextEntry()) != null) {
            if (!mCurrentTask.skipRoot)
                continue;

            String name = entry.getName();

            if (rootDirectory == null) {
                if (name.contains("/")) {
                    rootDirectory = name.substring(0, name.indexOf('/'));
                } else if (entry.isDirectory()) {
                    rootDirectory = name;
                } else {
                    throw new IOException(
                            String.format("archive '%s' contains files under it's root", mCurrentTask.path));
                }
            } else {
                if (!name.startsWith(rootDirectory)) {
                    throw new IOException("multiple directories found in the archive root");
                }
            }
        }

        while (mRunning && is.read(buffer) > 0) {
            percentage = (short) (((double) counter.getBytesRead() / total) * 100);
            if (percentage != old_percentage) {
                mBuilder.setProgress(100, percentage, false).setContentInfo(percentage + "%");
                mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
                old_percentage = percentage;
            }
        }
    } catch (IOException e) {
        throw new KeyException("corrupted archive: " + e.getMessage());
    } finally {
        try {
            counter.close();
        } catch (IOException ignore) {
        }
    }

    if (!mRunning)
        throw new CancellationException("archive integrity check cancelled");

    if (mCurrentTask.skipRoot && rootDirectory == null)
        throw new KeyException(String.format("archive '%s' is empty", mCurrentTask.path));
}