Example usage for java.security InvalidKeyException InvalidKeyException

List of usage examples for java.security InvalidKeyException InvalidKeyException

Introduction

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

Prototype

public InvalidKeyException(Throwable cause) 

Source Link

Document

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

Usage

From source file:net.sourceforge.jencrypt.lib.CryptoWrapper.java

/**
 * De- or encrypt a file.//from w  w  w.ja  v  a  2s.  c  o m
 * 
 * @param inputFileFullPath
 *            file to en- or decrypt
 * @param outputFileFullPath
 *            file with result of en-/decryption
 * @param cipherMode
 *            Cipher.ENCRYPT_MODE or Cipher.DECRYPT_MODE
 * @param progress
 *            progress info class to print progress percentage
 * 
 */
public void doCipherOperation(InputStream in, OutputStream out, long nrOfBytesToCipher, int cipherMode,
        ProgressInfo progress) throws Exception {

    if (nrOfBytesToCipher > 0) {

        try {
            // If the nr of bytes to read is smaller than readBufferSize
            // use the nr of bytes as the max buffer size.
            int maxBufferSize = (int) Math.min(readBufferSize, nrOfBytesToCipher);
            byte[] readBuffer = new byte[maxBufferSize];

            if (isInitialized == false) {
                cipher.init(cipherMode, cipherKey, new IvParameterSpec(initializationVector.getEncoded()));
                isInitialized = true;
            }

            long nrOfBytesLeftToCipher = nrOfBytesToCipher;

            while (nrOfBytesLeftToCipher > 0) {

                in.read(readBuffer, 0, maxBufferSize);

                nrOfBytesLeftToCipher -= cipher.update(readBuffer, 0, maxBufferSize, readBuffer);

                // If a ProgressInfo was given, calculate the current
                // percentage and print it
                if (progress != null)
                    progress.trackAndPrintProgress();

                out.write(readBuffer, 0, maxBufferSize);

                if (nrOfBytesLeftToCipher > 0 && nrOfBytesLeftToCipher < maxBufferSize) {
                    maxBufferSize = (int) nrOfBytesLeftToCipher;
                }
            }
            //cipher.doFinal();

        } catch (IOException e) {
            throw new IOException("Error reading bytes to encrypt: " + e.getMessage());
        } catch (InvalidKeyException e) {
            throw new InvalidKeyException("Error : " + e.getMessage()
                    + "\nKey file corrupt or invalid key parameters."
                    + "\nTo use key sizes above 128 bits please install the JCE Unlimited Strength Jurisdiction Policy Files.");
        }
    } else {
        // Print progress even if nrOfBytesToCipher == 0
        if (progress != null)
            progress.trackAndPrintProgress();
    }
}

From source file:org.signserver.server.cryptotokens.CryptoTokenHelper.java

/**
 * Creates a test signature and verifies it.
 *
 * @param privateKey Private key to sign with
 * @param publicKey Public key to verify with
 * @param signatureProvider Name of provider to sign with
 * @throws NoSuchAlgorithmException In case the key or signature algorithm is unknown
 * @throws NoSuchProviderException In case the supplied provider name is unknown or BC is not installed
 * @throws InvalidKeyException If signature verification failed or the key was invalid
 * @throws SignatureException If the signature could not be made or verified correctly
 *///from w w w.ja  v a2 s  . c  om
public static void testSignAndVerify(PrivateKey privateKey, PublicKey publicKey, String signatureProvider)
        throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException {
    final byte input[] = "Lillan gick pa vagen ut, motte dar en katt...".getBytes();
    final String sigAlg = suggestSigAlg(publicKey);
    if (sigAlg == null) {
        throw new NoSuchAlgorithmException("Unknown key algorithm: " + publicKey.getAlgorithm());
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Testing keys with algorithm: " + publicKey.getAlgorithm());
        LOG.debug("testSigAlg: " + sigAlg);
        LOG.debug("provider: " + signatureProvider);
        LOG.trace("privateKey: " + privateKey);
        LOG.trace("privateKey class: " + privateKey.getClass().getName());
        LOG.trace("publicKey: " + publicKey);
        LOG.trace("publicKey class: " + publicKey.getClass().getName());
    }
    final Signature signSignature = Signature.getInstance(sigAlg, signatureProvider);
    signSignature.initSign(privateKey);
    signSignature.update(input);
    byte[] signBA = signSignature.sign();
    if (LOG.isTraceEnabled()) {
        LOG.trace("Created signature of size: " + signBA.length);
        LOG.trace("Created signature: " + new String(Hex.encode(signBA)));
    }

    final Signature verifySignature = Signature.getInstance(sigAlg, "BC");
    verifySignature.initVerify(publicKey);
    verifySignature.update(input);
    if (!verifySignature.verify(signBA)) {
        throw new InvalidKeyException("Test signature inconsistent");
    }
}

From source file:cybervillains.ca.KeyStoreManager.java

/**
 * This method returns the duplicated certificate mapped to the passed in cert, or
 * creates and returns one if no mapping has yet been performed.  If a naked public
 * key has already been mapped that matches the key in the cert, the already mapped
 * keypair will be reused for the mapped cert.
 * @param cert// w  ww . ja  va2 s.co  m
 * @return
 * @throws CertificateEncodingException
 * @throws InvalidKeyException
 * @throws CertificateException
 * @throws CertificateNotYetValidException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws SignatureException
 * @throws KeyStoreException
 * @throws UnrecoverableKeyException
 */
public synchronized X509Certificate getMappedCertificate(final X509Certificate cert)
        throws CertificateEncodingException, InvalidKeyException, CertificateException,
        CertificateNotYetValidException, NoSuchAlgorithmException, NoSuchProviderException, SignatureException,
        KeyStoreException, UnrecoverableKeyException {

    String thumbprint = ThumbprintUtil.getThumbprint(cert);

    String mappedCertThumbprint = _certMap.get(thumbprint);

    if (mappedCertThumbprint == null) {

        // Check if we've already mapped this public key from a KeyValue
        PublicKey mappedPk = getMappedPublicKey(cert.getPublicKey());
        PrivateKey privKey;

        if (mappedPk == null) {
            PublicKey pk = cert.getPublicKey();

            String algo = pk.getAlgorithm();

            KeyPair kp;

            if (algo.equals("RSA")) {
                kp = getRSAKeyPair();
            } else if (algo.equals("DSA")) {
                kp = getDSAKeyPair();
            } else {
                throw new InvalidKeyException("Key algorithm " + algo + " not supported.");
            }
            mappedPk = kp.getPublic();
            privKey = kp.getPrivate();

            mapPublicKeys(cert.getPublicKey(), mappedPk);
        } else {
            privKey = getPrivateKey(mappedPk);
        }

        X509Certificate replacementCert = CertificateCreator.mitmDuplicateCertificate(cert, mappedPk,
                getSigningCert(), getSigningPrivateKey());

        addCertAndPrivateKey(null, replacementCert, privKey);

        mappedCertThumbprint = ThumbprintUtil.getThumbprint(replacementCert);

        _certMap.put(thumbprint, mappedCertThumbprint);
        _certMap.put(mappedCertThumbprint, thumbprint);
        _subjectMap.put(replacementCert.getSubjectX500Principal().getName(), thumbprint);

        if (persistImmediately) {
            persist();
        }
        return replacementCert;
    }
    return getCertificateByAlias(mappedCertThumbprint);

}

From source file:org.apache.cordova.ibeacon.LocationManager.java

private Region parseCircularRegion(JSONObject json)
        throws JSONException, InvalidKeyException, UnsupportedOperationException {

    if (json.has("latitude"))
        throw new InvalidKeyException("'latitude' is missing, cannot parse CircularRegion.");

    if (json.has("longitude"))
        throw new InvalidKeyException("'longitude' is missing, cannot parse CircularRegion.");

    if (json.has("radius"))
        throw new InvalidKeyException("'radius' is missing, cannot parse CircularRegion.");

    /*String identifier = json.getString("identifier");
    double latitude = json.getDouble("latitude");
    double longitude = json.getDouble("longitude");
    double radius = json.getDouble("radius");
    *///from  w  w w  .j a v a  2 s  .co  m
    throw new UnsupportedOperationException("Circular regions are not supported at present");
}

From source file:org.cesecore.keys.token.CryptoTokenManagementSessionBean.java

/** @throws InvalidKeyException if the alias is in use by a private, public or symmetric key */
private void assertAliasNotInUse(final CryptoToken cryptoToken, final String alias) throws InvalidKeyException {
    if (cryptoToken.isAliasUsed(alias)) {
        throw new InvalidKeyException("alias " + alias + " is in use");
    }// w w  w.  j  a v  a  2  s.  co m
}

From source file:net.duckling.ddl.web.controller.LynxEmailResourceController.java

private String getAuthEmail(String auth) throws ParseException, InvalidKeyException {
    try {/*from   w ww.j av  a2 s .  c  o m*/
        String decode = decodeAuth(auth);
        JSONObject obj = new JSONObject(decode);
        String email = obj.getString("email");
        String date = obj.getString("data");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d = sdf.parse(date);
        if (notExpired(d)) {
            return email;
        } else {
            return null;
        }
    } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException
            | BadPaddingException | UnsupportedEncodingException e) {
        throw new InvalidKeyException(e);
    }

}

From source file:org.cesecore.keys.token.CryptoTokenManagementSessionBean.java

@Override
public void removeKeyPair(final AuthenticationToken authenticationToken, final int cryptoTokenId,
        final String alias)
        throws AuthorizationDeniedException, CryptoTokenOfflineException, InvalidKeyException {
    assertAuthorization(authenticationToken, cryptoTokenId,
            CryptoTokenRules.REMOVE_KEYS.resource() + "/" + cryptoTokenId);
    final CryptoToken cryptoToken = getCryptoTokenAndAssertExistence(cryptoTokenId);
    // Check if alias is in use
    if (!cryptoToken.isAliasUsed(alias)) {
        throw new InvalidKeyException("Alias " + alias + " is not in use");
    }/*  w  w w  .j  a v a 2  s.c  o m*/
    final Map<String, Object> details = new LinkedHashMap<String, Object>();
    details.put("msg", "Deleted key pair from CryptoToken " + cryptoTokenId);
    details.put("keyAlias", alias);
    try {
        cryptoToken.deleteEntry(alias);
    } catch (KeyStoreException e) {
        throw new InvalidKeyException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new InvalidKeyException(e);
    } catch (CertificateException e) {
        throw new InvalidKeyException(e);
    } catch (IOException e) {
        throw new InvalidKeyException(e);
    }
    assertAliasNotInUse(cryptoToken, alias);
    log.debug("cryptoTokenSession.mergeCryptoToken");
    // Merge is important for soft tokens where the data is persisted in the database, but will also update lastUpdate
    try {
        cryptoTokenSession.mergeCryptoToken(cryptoToken);
    } catch (CryptoTokenNameInUseException e) {
        throw new IllegalStateException(e); // We have not changed the name of the CrytpoToken here, so this should never happen
    }
    securityEventsLoggerSession.log(EventTypes.CRYPTOTOKEN_DELETE_ENTRY, EventStatus.SUCCESS,
            ModuleTypes.CRYPTOTOKEN, ServiceTypes.CORE, authenticationToken.toString(),
            String.valueOf(cryptoTokenId), null, null, details);
}

From source file:org.cesecore.keys.token.CryptoTokenManagementSessionBean.java

@TransactionAttribute(TransactionAttributeType.REQUIRED)
@Override/*from   w w w.  j  ava  2s. co  m*/
public void removeKeyPairPlaceholder(final AuthenticationToken authenticationToken, final int cryptoTokenId,
        final String alias) throws AuthorizationDeniedException, InvalidKeyException {
    assertAuthorization(authenticationToken, cryptoTokenId,
            CryptoTokenRules.REMOVE_KEYS.resource() + "/" + cryptoTokenId);
    final CryptoToken cryptoToken = getCryptoTokenAndAssertExistence(cryptoTokenId);

    boolean removed = false;
    final Properties props = new Properties();
    props.putAll(cryptoToken.getProperties());
    final String placeholdersString = props.getProperty(CryptoToken.KEYPLACEHOLDERS_PROPERTY, "");
    final List<String> entries = new ArrayList<String>(
            Arrays.asList(placeholdersString.split("[" + CryptoToken.KEYPLACEHOLDERS_OUTER_SEPARATOR + "]")));
    final Iterator<String> iter = entries.iterator();
    while (iter.hasNext()) {
        final String entry = iter.next();
        if (entry.startsWith(alias + CryptoToken.KEYPLACEHOLDERS_INNER_SEPARATOR)) {
            iter.remove();
            removed = true;
        }
    }

    if (removed) {
        final String newValue = StringUtils.join(entries, CryptoToken.KEYPLACEHOLDERS_OUTER_SEPARATOR);
        props.setProperty(CryptoToken.KEYPLACEHOLDERS_PROPERTY, newValue);
        cryptoToken.setProperties(props);
    }

    // Check if alias is in use
    if (!removed) {
        throw new InvalidKeyException("Alias " + alias + " is not in use");
    }

    try {
        cryptoTokenSession.mergeCryptoToken(cryptoToken);
    } catch (CryptoTokenNameInUseException e) {
        throw new IllegalStateException(e); // We have not changed the name of the CrytpoToken here, so this should never happen
    }

    final Map<String, Object> details = new LinkedHashMap<String, Object>();
    details.put("msg", "Deleted key pair placeholder from CryptoToken " + cryptoTokenId);
    details.put("keyAlias", alias);
    securityEventsLoggerSession.log(EventTypes.CRYPTOTOKEN_DELETE_ENTRY, EventStatus.SUCCESS,
            ModuleTypes.CRYPTOTOKEN, ServiceTypes.CORE, authenticationToken.toString(),
            String.valueOf(cryptoTokenId), null, null, details);
}

From source file:com.commontime.plugin.LocationManager.java

private Region parseRegion(JSONObject json)
        throws JSONException, InvalidKeyException, UnsupportedOperationException {

    if (!json.has("typeName"))
        throw new InvalidKeyException("'typeName' is missing, cannot parse Region.");

    if (!json.has("identifier"))
        throw new InvalidKeyException("'identifier' is missing, cannot parse Region.");

    String typeName = json.getString("typeName");
    if (typeName.equals("BeaconRegion")) {
        return parseBeaconRegion(json);
    } else if (typeName.equals("CircularRegion")) {
        return parseCircularRegion(json);

    } else {//www .  j a v a2s.  com
        throw new UnsupportedOperationException("Unsupported region type");
    }

}

From source file:com.commontime.plugin.LocationManager.java

private Region parseCircularRegion(JSONObject json)
        throws JSONException, InvalidKeyException, UnsupportedOperationException {

    if (!json.has("latitude"))
        throw new InvalidKeyException("'latitude' is missing, cannot parse CircularRegion.");

    if (!json.has("longitude"))
        throw new InvalidKeyException("'longitude' is missing, cannot parse CircularRegion.");

    if (!json.has("radius"))
        throw new InvalidKeyException("'radius' is missing, cannot parse CircularRegion.");

    /*String identifier = json.getString("identifier");
    double latitude = json.getDouble("latitude");
    double longitude = json.getDouble("longitude");
    double radius = json.getDouble("radius");
    *//*from w  w  w  . j  a va 2s  . c  o  m*/
    throw new UnsupportedOperationException("Circular regions are not supported at present");
}