Search in sources :

Example 26 with KeyException

use of java.security.KeyException in project scheduling by ow2-proactive.

the class SmartProxyImpl method init.

private void init(String url, Credentials credentials, CredData credData) throws SchedulerException, LoginException {
    if (this.connectionInfo == null) {
        this.connectionInfo = new ConnectionInfo(url, null, null, null, false);
    }
    this.connectionInfo.setUrl(url);
    this.credentials = credentials;
    this.credData = credData;
    SchedulerAuthenticationInterface auth = SchedulerConnection.join(url);
    PublicKey pubKey = auth.getPublicKey();
    if (this.credentials != null) {
        this.credentials = credentials;
        this.credData = null;
    } else if (this.credData != null) {
        this.credData = credData;
        try {
            this.credentials = Credentials.createCredentials(credData, pubKey);
        } catch (KeyException e) {
            throw new InternalSchedulerException(e);
        }
    } else {
        throw new IllegalStateException("No valid credential available to connect to the scheduler");
    }
    this.schedulerProxy = auth.login(this.credentials);
    jobTracker.loadJobs();
    setInitialized(true);
    registerAsListener();
    syncAwaitedJobs();
}
Also used : InternalSchedulerException(org.ow2.proactive.scheduler.common.exception.InternalSchedulerException) PublicKey(java.security.PublicKey) SchedulerAuthenticationInterface(org.ow2.proactive.scheduler.common.SchedulerAuthenticationInterface) ConnectionInfo(org.ow2.proactive.authentication.ConnectionInfo) KeyException(java.security.KeyException)

Example 27 with KeyException

use of java.security.KeyException in project hbase by apache.

the class EncryptionUtil method getUnwrapKey.

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);
    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());
}
Also used : SecretKeySpec(javax.crypto.spec.SecretKeySpec) ByteArrayOutputStream(java.io.ByteArrayOutputStream) KeyException(java.security.KeyException)

Example 28 with KeyException

use of java.security.KeyException in project hbase by apache.

the class SecureProtobufLogReader method readHeader.

@Override
protected WALHdrContext readHeader(WALHeader.Builder builder, FSDataInputStream stream) throws IOException {
    WALHdrContext hdrCtxt = super.readHeader(builder, stream);
    WALHdrResult result = hdrCtxt.getResult();
    // no longer set in the site configuration.
    if (result == WALHdrResult.SUCCESS && builder.hasEncryptionKey()) {
        // Serialized header data has been merged into the builder from the
        // stream.
        EncryptionTest.testKeyProvider(conf);
        EncryptionTest.testCipherProvider(conf);
        // Retrieve a usable key
        byte[] keyBytes = builder.getEncryptionKey().toByteArray();
        Key key = null;
        String walKeyName = conf.get(HConstants.CRYPTO_WAL_KEY_NAME_CONF_KEY);
        // First try the WAL key, if one is configured
        if (walKeyName != null) {
            try {
                key = EncryptionUtil.unwrapWALKey(conf, walKeyName, keyBytes);
            } catch (KeyException e) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Unable to unwrap key with WAL key '" + walKeyName + "'");
                }
                key = null;
            }
        }
        if (key == null) {
            String masterKeyName = conf.get(HConstants.CRYPTO_MASTERKEY_NAME_CONF_KEY, User.getCurrent().getShortName());
            try {
                // Then, try the cluster master key
                key = EncryptionUtil.unwrapWALKey(conf, masterKeyName, keyBytes);
            } catch (KeyException e) {
                // one is configured
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Unable to unwrap key with current master key '" + masterKeyName + "'");
                }
                String alternateKeyName = conf.get(HConstants.CRYPTO_MASTERKEY_ALTERNATE_NAME_CONF_KEY);
                if (alternateKeyName != null) {
                    try {
                        key = EncryptionUtil.unwrapWALKey(conf, alternateKeyName, keyBytes);
                    } catch (KeyException ex) {
                        throw new IOException(ex);
                    }
                } else {
                    throw new IOException(e);
                }
            }
        }
        // Use the algorithm the key wants
        Cipher cipher = Encryption.getCipher(conf, key.getAlgorithm());
        if (cipher == null) {
            throw new IOException("Cipher '" + key.getAlgorithm() + "' is not available");
        }
        // Set up the decryptor for this WAL
        decryptor = cipher.getDecryptor();
        decryptor.setKey(key);
        if (LOG.isTraceEnabled()) {
            LOG.trace("Initialized secure protobuf WAL: cipher=" + cipher.getName());
        }
    }
    return hdrCtxt;
}
Also used : IOException(java.io.IOException) Cipher(org.apache.hadoop.hbase.io.crypto.Cipher) Key(java.security.Key) KeyException(java.security.KeyException)

Example 29 with KeyException

use of java.security.KeyException in project android by cSploit.

the class UpdateService method haveLocalFile.

/**
   * check if mLocalFile exists.
   *
   * @return true if file exists and match md5sum and sha1sum.
   * @throws java.util.concurrent.CancellationException when check is cancelled by user
   * @throws SecurityException bad file permissions
   * @throws IOException when IOException occurs
   * @throws java.security.NoSuchAlgorithmException when digests cannot be created
   * @throws java.security.KeyException when file checksum fails
   */
private boolean haveLocalFile() throws CancellationException, SecurityException, IOException, NoSuchAlgorithmException, KeyException {
    File file = null;
    InputStream reader = null;
    boolean exitForError = true;
    if (mCurrentTask.path == null)
        return false;
    try {
        MessageDigest md5, sha1;
        byte[] buffer;
        int read;
        short percentage, previous_percentage;
        long read_counter, total;
        file = new File(mCurrentTask.path);
        buffer = new byte[4096];
        total = file.length();
        read_counter = 0;
        previous_percentage = -1;
        if (!file.exists() || !file.isFile())
            return false;
        if (!file.canWrite() || !file.canRead()) {
            read = -1;
            try {
                read = System.getTools().raw.run(String.format("chmod 777 '%s'", mCurrentTask.path));
            } catch (Exception e) {
                System.errorLogging(e);
            }
            if (read != 0)
                throw new SecurityException(String.format("bad file permissions for '%s', chmod returned: %d", mCurrentTask.path, read));
        }
        if (mCurrentTask.md5 != null || mCurrentTask.sha1 != null) {
            mBuilder.setContentTitle(getString(R.string.checking)).setSmallIcon(android.R.drawable.ic_popup_sync).setContentText("").setProgress(100, 0, false);
            mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
            md5 = (mCurrentTask.md5 != null ? MessageDigest.getInstance("MD5") : null);
            sha1 = (mCurrentTask.sha1 != null ? MessageDigest.getInstance("SHA-1") : null);
            reader = new FileInputStream(file);
            while (mRunning && (read = reader.read(buffer)) != -1) {
                if (md5 != null)
                    md5.update(buffer, 0, read);
                if (sha1 != null)
                    sha1.update(buffer, 0, read);
                read_counter += read;
                percentage = (short) (((double) read_counter / total) * 100);
                if (percentage != previous_percentage) {
                    mBuilder.setProgress(100, percentage, false).setContentInfo(percentage + "%");
                    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
                    previous_percentage = percentage;
                }
            }
            reader.close();
            reader = null;
            if (!mRunning) {
                exitForError = false;
                throw new CancellationException("local file check cancelled");
            }
            if (md5 != null && !mCurrentTask.md5.equals(digest2string(md5.digest())))
                throw new KeyException("wrong MD5");
            if (sha1 != null && !mCurrentTask.sha1.equals(digest2string(sha1.digest())))
                throw new KeyException("wrong SHA-1");
            Logger.info(String.format("checksum ok: '%s'", mCurrentTask.path));
        } else if (mCurrentTask.archiver != null) {
            verifyArchiveIntegrity();
        }
        Logger.info(String.format("file already exists: '%s'", mCurrentTask.path));
        mBuilder.setSmallIcon(android.R.drawable.stat_sys_download_done).setContentTitle(getString(R.string.update_available)).setContentText(getString(R.string.click_here_to_upgrade)).setProgress(0, 0, // remove progress bar
        false).setAutoCancel(true);
        exitForError = false;
        return true;
    } finally {
        if (exitForError && file != null && file.exists() && !file.delete())
            Logger.error(String.format("cannot delete local file '%s'", mCurrentTask.path));
        try {
            if (reader != null)
                reader.close();
        } catch (IOException e) {
            System.errorLogging(e);
        }
    }
}
Also used : BufferedInputStream(java.io.BufferedInputStream) TarArchiveInputStream(org.apache.commons.compress.archivers.tar.TarArchiveInputStream) XZCompressorInputStream(org.apache.commons.compress.compressors.xz.XZCompressorInputStream) ArchiveInputStream(org.apache.commons.compress.archivers.ArchiveInputStream) BZip2CompressorInputStream(org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream) GzipCompressorInputStream(org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream) ZipArchiveInputStream(org.apache.commons.compress.archivers.zip.ZipArchiveInputStream) FileInputStream(java.io.FileInputStream) CountingInputStream(org.apache.commons.compress.utils.CountingInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) KeyException(java.security.KeyException) CancellationException(java.util.concurrent.CancellationException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) FileInputStream(java.io.FileInputStream) KeyException(java.security.KeyException) CancellationException(java.util.concurrent.CancellationException) MessageDigest(java.security.MessageDigest) File(java.io.File)

Example 30 with KeyException

use of java.security.KeyException in project android by cSploit.

the class UpdateService method verifyArchiveIntegrity.

/**
   * check if an archive is valid by reading it.
   * @throws RuntimeException if trying to run this with no archive
   */
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));
}
Also used : CountingInputStream(org.apache.commons.compress.utils.CountingInputStream) FileNotFoundException(java.io.FileNotFoundException) ArchiveEntry(org.apache.commons.compress.archivers.ArchiveEntry) TarArchiveEntry(org.apache.commons.compress.archivers.tar.TarArchiveEntry) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) KeyException(java.security.KeyException) TarArchiveInputStream(org.apache.commons.compress.archivers.tar.TarArchiveInputStream) ArchiveInputStream(org.apache.commons.compress.archivers.ArchiveInputStream) ZipArchiveInputStream(org.apache.commons.compress.archivers.zip.ZipArchiveInputStream) CancellationException(java.util.concurrent.CancellationException) File(java.io.File)

Aggregations

KeyException (java.security.KeyException)59 IOException (java.io.IOException)22 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)14 File (java.io.File)10 PublicKey (java.security.PublicKey)8 FileInputStream (java.io.FileInputStream)7 Cipher (javax.crypto.Cipher)6 Throwables.getStackTraceAsString (com.google.common.base.Throwables.getStackTraceAsString)5 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)5 LoginException (javax.security.auth.login.LoginException)5 Credentials (org.ow2.proactive.authentication.crypto.Credentials)5 FileNotFoundException (java.io.FileNotFoundException)4 PrivateKey (java.security.PrivateKey)4 CredData (org.ow2.proactive.authentication.crypto.CredData)4 RMException (org.ow2.proactive.resourcemanager.exception.RMException)4 CommandLineBuilder (org.ow2.proactive.resourcemanager.utils.CommandLineBuilder)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 DataInputStream (java.io.DataInputStream)3 InputStream (java.io.InputStream)3 Key (java.security.Key)3