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:org.cesecore.keys.token.BaseCryptoToken.java

@Override
public void testKeyPair(final String alias, PublicKey publicKey, PrivateKey privateKey)
        throws InvalidKeyException { // NOPMD:this is not a junit test
    if (log.isDebugEnabled()) {
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        final PrintStream ps = new PrintStream(baos);
        KeyTools.printPublicKeyInfo(publicKey, ps);
        ps.flush();//from w w w .ja  v a2 s  .  com
        log.debug("Testing key of type " + baos.toString());
    }
    if (!permitExtractablePrivateKeyForTest() && KeyTools.isPrivateKeyExtractable(privateKey)) {
        String msg = intres.getLocalizedMessage("token.extractablekey",
                CesecoreConfiguration.isPermitExtractablePrivateKeys());
        if (!CesecoreConfiguration.isPermitExtractablePrivateKeys()) {
            throw new InvalidKeyException(msg);
        }
        log.info(msg);
    }
    KeyTools.testKey(privateKey, publicKey, getSignProviderName());
}

From source file:org.csploit.android.net.GitHubParser.java

public synchronized void setBranch(String branch) throws InvalidKeyException, JSONException, IOException {
    if (mBranches == null)
        fetchBranches();//ww  w .j a v a 2  s. c  o  m

    for (int i = 0; i < mBranches.length(); i++) {
        if ((mBranches.getJSONObject(i)).getString("name").equals(branch)) {
            mBranch = (mBranches.getJSONObject(i));
            mLastCommit = mBranch.getJSONObject("commit");
            return;
        }
    }
    throw new InvalidKeyException("branch '" + branch + "' not found");
}

From source file:com.ntsync.android.sync.client.ClientKeyHelper.java

private static void validateKey(byte[] check, SecretKey skey) throws InvalidKeyException {
    AEADBlockCipher cipher = CryptoHelper.getCipher();
    try {/*  w  w  w.ja va2s . c  o m*/
        // data, pos, IV_LEN)
        byte[] iv = new byte[CryptoHelper.IV_LEN];
        System.arraycopy(check, 0, iv, 0, CryptoHelper.IV_LEN);
        cipher.init(false, new AEADParameters(new KeyParameter(skey.getEncoded()), CryptoHelper.MAC_SIZE, iv));
        byte[] original = CryptoHelper.cipherData(cipher, check, IV_LENGTH, check.length - IV_LENGTH);

        String orgValue = new String(original, SyncDataHelper.DEFAULT_CHARSET_NAME);
        // Validate Checksum
        int res1 = calcUpcChecksum(orgValue);
        int len = orgValue.length();
        if (orgValue.length() == 0 || res1 != Integer.parseInt(orgValue.substring(len - 1, len))) {
            throw new InvalidKeyException("Invalid Key. Checksum error");
        }
    } catch (NumberFormatException ex) {
        throw new InvalidKeyException("Invalid Key. Data is not number.", ex);
    } catch (DataLengthException e) {
        throw new InvalidKeyException("Invalid Key", e);
    } catch (IllegalStateException e) {
        throw new InvalidKeyException("Invalid Key. Wrong Parameter.", e);
    } catch (InvalidCipherTextException e) {
        throw new InvalidKeyException("Invalid Key.", e);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException("No support for UTF-8 available.", e);
    }
}

From source file:org.apache.jcp.xml.dsig.internal.dom.DOMSignatureMethod.java

byte[] sign(Key key, SignedInfo si, XMLSignContext context) throws InvalidKeyException, XMLSignatureException {
    if (key == null || si == null) {
        throw new NullPointerException();
    }//from w w w  .ja v  a2  s.co m

    if (!(key instanceof PrivateKey)) {
        throw new InvalidKeyException("key must be PrivateKey");
    }
    if (signature == null) {
        try {
            Provider p = (Provider) context.getProperty("org.jcp.xml.dsig.internal.dom.SignatureProvider");
            signature = (p == null) ? Signature.getInstance(getJCAAlgorithm())
                    : Signature.getInstance(getJCAAlgorithm(), p);
        } catch (NoSuchAlgorithmException nsae) {
            throw new XMLSignatureException(nsae);
        }
    }
    signature.initSign((PrivateKey) key);
    if (log.isDebugEnabled()) {
        log.debug("Signature provider:" + signature.getProvider());
        log.debug("Signing with key: " + key);
    }

    ((DOMSignedInfo) si).canonicalize(context, new SignerOutputStream(signature));

    try {
        Type type = getAlgorithmType();
        if (type == Type.DSA) {
            return convertASN1toXMLDSIG(signature.sign());
        } else if (type == Type.ECDSA) {
            return SignatureECDSA.convertASN1toXMLDSIG(signature.sign());
        } else {
            return signature.sign();
        }
    } catch (SignatureException se) {
        throw new XMLSignatureException(se);
    } catch (IOException ioe) {
        throw new XMLSignatureException(ioe);
    }
}

From source file:org.cesecore.certificates.certificate.CertificateCreateSessionBean.java

@Override
public CertificateResponseMessage createCertificate(final AuthenticationToken admin,
        final EndEntityInformation endEntityInformation, final CA ca, final RequestMessage req,
        final Class<? extends ResponseMessage> responseClass, CertificateGenerationParams certGenParams,
        final long updateTime)
        throws CryptoTokenOfflineException, SignRequestSignatureException, IllegalKeyException,
        IllegalNameException, CustomCertificateSerialNumberException, CertificateCreateException,
        CertificateRevokeException, CertificateSerialNumberException, AuthorizationDeniedException,
        IllegalValidityException, CAOfflineException, InvalidAlgorithmException, CertificateExtensionException {
    if (log.isTraceEnabled()) {
        log.trace(">createCertificate(IRequestMessage, CA)");
    }//from   w  ww  .  ja v  a2 s.c o m
    CertificateResponseMessage ret = null;
    try {
        final CAToken catoken = ca.getCAToken();
        final CryptoToken cryptoToken = cryptoTokenManagementSession.getCryptoToken(catoken.getCryptoTokenId());
        final String alias = catoken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN);
        // See if we need some key material to decrypt request
        if (req.requireKeyInfo()) {
            // You go figure...scep encrypts message with the public CA-cert
            req.setKeyInfo(ca.getCACertificate(), cryptoToken.getPrivateKey(alias),
                    cryptoToken.getEncProviderName());
        }
        // Verify the request
        final PublicKey reqpk;
        try {
            if (!req.verify()) {
                throw new SignRequestSignatureException(
                        intres.getLocalizedMessage("createcert.popverificationfailed"));
            }
            reqpk = req.getRequestPublicKey();
            if (reqpk == null) {
                final String msg = intres.getLocalizedMessage("createcert.nokeyinrequest");
                throw new InvalidKeyException(msg);
            }
        } catch (InvalidKeyException e) {
            // If we get an invalid key exception here, we should throw an IllegalKeyException to the caller
            // The catch of InvalidKeyException in the end of this method, catches error from the CA crypto token
            throw new IllegalKeyException(e);
        }

        final Date notBefore = req.getRequestValidityNotBefore(); // Optionally requested validity
        final Date notAfter = req.getRequestValidityNotAfter(); // Optionally requested validity
        final Extensions exts = req.getRequestExtensions(); // Optionally requested extensions
        int keyusage = -1;
        if (exts != null) {
            if (log.isDebugEnabled()) {
                log.debug(
                        "we have extensions, see if we can override KeyUsage by looking for a KeyUsage extension in request");
            }
            final Extension ext = exts.getExtension(Extension.keyUsage);
            if (ext != null) {
                final ASN1OctetString os = ext.getExtnValue();
                DERBitString bs;
                try {
                    bs = new DERBitString(os.getEncoded());
                } catch (IOException e) {
                    throw new IllegalStateException("Unexpected IOException caught.");
                }
                keyusage = bs.intValue();
                if (log.isDebugEnabled()) {
                    log.debug("We have a key usage request extension: " + keyusage);
                }
            }
        }
        String sequence = null;
        byte[] ki = req.getRequestKeyInfo();
        // CVC sequence is only 5 characters, don't fill with a lot of garbage here, it must be a readable string
        if ((ki != null) && (ki.length > 0) && (ki.length < 10)) {
            final String str = new String(ki);
            // A cvc sequence must be ascii printable, otherwise it's some binary data
            if (StringUtils.isAsciiPrintable(str)) {
                sequence = new String(ki);
            }
        }

        CertificateDataWrapper certWrapper = createCertificate(admin, endEntityInformation, ca, req, reqpk,
                keyusage, notBefore, notAfter, exts, sequence, certGenParams, updateTime);
        // Create the response message with all nonces and checks etc
        ret = ResponseMessageUtils.createResponseMessage(responseClass, req, ca.getCertificateChain(),
                cryptoToken.getPrivateKey(alias), cryptoToken.getEncProviderName());
        ResponseStatus status = ResponseStatus.SUCCESS;
        FailInfo failInfo = null;
        String failText = null;
        if ((certWrapper == null) && (status == ResponseStatus.SUCCESS)) {
            status = ResponseStatus.FAILURE;
            failInfo = FailInfo.BAD_REQUEST;
        } else {
            ret.setCertificate(certWrapper.getCertificate());
            ret.setCACert(ca.getCACertificate());
            ret.setBase64CertData(certWrapper.getBase64CertData());
            ret.setCertificateData(certWrapper.getCertificateData());
        }
        ret.setStatus(status);
        if (failInfo != null) {
            ret.setFailInfo(failInfo);
            ret.setFailText(failText);
        }
        ret.create();
    } catch (InvalidKeyException e) {
        throw new CertificateCreateException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new CertificateCreateException(e);
    } catch (NoSuchProviderException e) {
        throw new CertificateCreateException(e);
    } catch (CertificateEncodingException e) {
        throw new CertificateCreateException(e);
    } catch (CRLException e) {
        throw new CertificateCreateException(e);
    }

    if (log.isTraceEnabled()) {
        log.trace("<createCertificate(IRequestMessage, CA)");
    }
    return ret;
}

From source file:org.kaaproject.kaa.common.endpoint.security.KeyUtil.java

/**
 * Gets the private key from bytes.//from   w ww .  j  a va 2 s .  com
 *
 * @param keyBytes the key bytes
 * @return the private
 * @throws InvalidKeyException invalid key exception
 */
public static PrivateKey getPrivate(byte[] keyBytes) throws InvalidKeyException {
    try {
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory kf = KeyFactory.getInstance(RSA);
        return kf.generatePrivate(spec);
    } catch (NoSuchAlgorithmException | InvalidKeySpecException ex) {
        throw new InvalidKeyException(ex);
    }
}

From source file:org.ejbca.core.protocol.cmp.CrmfRequestMessage.java

private PublicKey getPublicKey(final SubjectPublicKeyInfo subjectPKInfo, final String provider)
        throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException {
    try {/*  ww w  . j  av  a 2s  .co m*/
        final X509EncodedKeySpec xspec = new X509EncodedKeySpec(new DERBitString(subjectPKInfo).getBytes());
        final AlgorithmIdentifier keyAlg = subjectPKInfo.getAlgorithm();
        return KeyFactory.getInstance(keyAlg.getAlgorithm().getId(), provider).generatePublic(xspec);
    } catch (java.security.spec.InvalidKeySpecException e) {
        final InvalidKeyException newe = new InvalidKeyException("Error decoding public key.");
        newe.initCause(e);
        throw newe;
    } catch (IOException e) {
        final InvalidKeyException newe = new InvalidKeyException("Error decoding public key.");
        newe.initCause(e);
        throw newe;
    }
}

From source file:com.blackducksoftware.tools.commonframework.core.encryption.Password.java

/**
 * Decrypt the given binary/encrypted password, and return the original text
 * password. The argument should have been encrypted using a valid
 * (according to isValidPassword() password encrypted by the
 * encryptStringToBinary() method./*  www  . j a  va 2  s  .c  om*/
 *
 * @param encryptedPasswordBinary
 * @return the original text password
 * @throws KeyStoreException
 * @throws NoSuchAlgorithmException
 * @throws CertificateException
 * @throws IOException
 * @throws UnrecoverableKeyException
 * @throws InvalidKeyException
 * @throws NoSuchPaddingException
 * @throws IllegalBlockSizeException
 * @throws BadPaddingException
 */
public static String decryptBinaryToString(final byte[] encryptedPasswordBinary) throws KeyStoreException,
        NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException,
        InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {

    // get key
    final Key key = getKey(KEY_PASSWORD);
    if (key == null) {
        throw new InvalidKeyException("The password decryption key is null");
    }

    // decrypt
    final Cipher cipher = Cipher.getInstance(CIPHER_TRANSFORMATION);
    cipher.init(Cipher.DECRYPT_MODE, key);
    byte[] decryptedBytes = cipher.doFinal(encryptedPasswordBinary);
    decryptedBytes = Arrays.copyOf(decryptedBytes, MAX_LENGTH);

    // convert byte array to String
    final String reconstitutedString = new String(decryptedBytes, UTF8).trim();
    return reconstitutedString;
}

From source file:tk.playerforcehd.networklib.bukkit.socket.client.NS_NetClientSocket.java

/**
 * Starts to encrypt the connection//from ww w  .  j av  a  2  s .com
 *
 * @param key The key for the encryption (MUST be 128 bit)
 */
@Override
public void startConnectionEncryption(String key) throws InvalidKeyException {
    if (key.getBytes().length != 16) {
        throw new InvalidKeyException(
                "The given key is not a 128 bit key! (Use 16 Characters, 1 char = 1 byte)");
    }
    this.encryptionKey = key;
    this.enableEncryption = true;
}

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

public byte[] cipherBytes(byte[] bytesToCipher, int cipherMode) throws Exception {

    if (isInitialized == false) {
        try {/*from   w  ww  .j  a  v a 2  s  .c om*/
            cipher.init(cipherMode, cipherKey, new IvParameterSpec(initializationVector.getEncoded()));
        } 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.");
        }
        isInitialized = true;
    }

    return cipher.update(bytesToCipher);
}