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:it.evilsocket.dsploit.net.GitHubParser.java

public void setBranch(String branch) throws InvalidKeyException, JSONException, IOException {
    if (mBranches == null)
        fetchBranches();/*from   w ww. ja v a2 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:me.lazerka.gae.jersey.oauth2.facebook.TokenVerifierFacebookSignedRequest.java

@Override
public FacebookUserPrincipal verify(String signedRequestToken) throws IOException, InvalidKeyException {
    logger.trace("Requesting endpoint to validate token");

    List<String> parts = Splitter.on('.').splitToList(signedRequestToken);

    checkArgument(parts.size() == 2, "Signed request must have two parts separated by period.");

    byte[] providedSignature = Base64Variants.MODIFIED_FOR_URL.decode(parts.get(0));
    String signedRequestJsonEncoded = parts.get(1);
    byte[] signedRequestJson = Base64Variants.MODIFIED_FOR_URL.decode(signedRequestJsonEncoded);

    SignedRequest signedRequest = jackson.readValue(signedRequestJson, SignedRequest.class);

    if (!"HMAC-SHA256".equals(signedRequest.algorithm)) {
        throw new InvalidKeyException("Unsupported signing method: " + signedRequest.algorithm);
    }/*from w w  w  .  j  a  v  a 2 s  .  c  o m*/

    byte[] expectedSignature = hmac.doFinal(signedRequestJsonEncoded.getBytes(UTF_8));
    if (!Arrays.equals(providedSignature, expectedSignature)) {
        throw new InvalidKeyException("Signature invalid");
    }

    // We still need to verify expiration somehow. The only way is to ask Facebook.

    // Exchange `code` for long-lived access token.
    // This serves as verification for `code` expiration too.

    AccessTokenResponse response = fetcher.fetchUserAccessToken(signedRequest.code, redirectUri);

    // Not fetching email, because maybe we won't need to, if ID is enough.

    return new FacebookUserPrincipal(signedRequest.userId, null, response, null);
}

From source file:me.lazerka.gae.jersey.oauth2.facebook.FacebookFetcher.java

String fetch(URL url) throws IOException, InvalidKeyException {
    logger.trace("Requesting endpoint to validate token");

    HTTPRequest httpRequest = new HTTPRequest(url, GET, validateCertificate());

    Stopwatch stopwatch = Stopwatch.createStarted();
    HTTPResponse response = urlFetchService.fetch(httpRequest);
    logger.debug("Remote call took {}ms", stopwatch.elapsed(TimeUnit.MILLISECONDS));

    int responseCode = response.getResponseCode();
    String content = new String(response.getContent(), UTF_8);

    if (responseCode != 200) {
        logger.warn("{}: {}", responseCode, content);

        String msg = "Endpoint response code " + responseCode;

        // Something is wrong with our request.
        // If signature is invalid, then response code is 403.
        if (responseCode >= 400 && responseCode < 500) {
            try {
                JsonNode tree = jackson.readTree(content);
                JsonNode error = tree.findPath("error");
                if (!error.isMissingNode()) {
                    msg += ": " + error.findPath("message").textValue();
                }/*from  www  . j av  a2s.co  m*/
            } catch (IOException e) {
                logger.warn("Cannot parse response as error");
            }
        }

        throw new InvalidKeyException(msg);
    }

    return content;
}

From source file:com.nexmo.client.auth.JWTAuthMethod.java

protected byte[] decodePrivateKey(byte[] data) throws InvalidKeyException {
    try {/*w w w  .  ja v a 2  s .  com*/
        String s = new String(data, "UTF-8");
        Matcher extracter = pemPattern.matcher(s);
        if (extracter.matches()) {
            String pemBody = extracter.group(1);
            return DatatypeConverter.parseBase64Binary(pemBody);
        } else {
            throw new InvalidKeyException("Private key should be provided in PEM format!");
        }
    } catch (UnsupportedEncodingException exc) {
        // This should never happen.
        throw new NexmoUnexpectedException("UTF-8 is an unsupported encoding in this JVM", exc);
    }
}

From source file:org.opensc.pkcs11.spi.PKCS11CipherSpi.java

@Override
protected int engineGetKeySize(Key key) throws InvalidKeyException {
    if (key instanceof PKCS11PrivateKey) {
        return ((PKCS11PrivateKey) key).getKeyBits();
    }/*from   w  ww . j  a v  a 2 s .c  om*/

    if (key instanceof PKCS11PublicKey) {
        return ((PKCS11PublicKey) key).getKeyBits();
    }

    throw new InvalidKeyException("Invalid key class " + key.getClass());
}

From source file:org.ejbca.core.model.ca.catoken.BaseCAToken.java

private void testKey(KeyPair pair) throws Exception {
    if (log.isDebugEnabled()) {
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        final PrintStream ps = new PrintStream(baos);
        KeyTools.printPublicKeyInfo(pair.getPublic(), ps);
        ps.flush();/*  w w  w  .  ja  va 2 s .  c om*/
        log.debug("Using of " + baos.toString());
    }
    if (!doPermitExtractablePrivateKey() && KeyTools.isPrivateKeyExtractable(pair.getPrivate())) {
        String msg = intres.getLocalizedMessage("catoken.extractablekey",
                EjbcaConfiguration.doPermitExtractablePrivateKeys());
        if (!EjbcaConfiguration.doPermitExtractablePrivateKeys()) {
            throw new InvalidKeyException(msg);
        }
        log.info(msg);
    }
    KeyTools.testKey(pair.getPrivate(), pair.getPublic(), getProvider());
}

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

public boolean verify(String raAuthenticationSecret)
        throws InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException {
    lastUsedRaSecret = raAuthenticationSecret;
    boolean ret = false;
    // Verify the PasswordBased protection of the message
    if (!pAlg.getAlgorithm().equals(CMPObjectIdentifiers.passwordBasedMac)) {
        errMsg = INTRES.getLocalizedMessage("cmp.errorunknownprotalg", pAlg.getAlgorithm().getId());
        LOG.error(errMsg);//from  ww  w . j  ava2  s  . c o m
        return ret;
    } else {
        if (iterationCount > 10000) {
            LOG.info("Received message with too many iterations in PBE protection: " + iterationCount);
            throw new InvalidKeyException("Iteration count can not exceed 10000");
        }
        byte[] raSecret = raAuthenticationSecret.getBytes();
        byte[] basekey = new byte[raSecret.length + salt.length];
        System.arraycopy(raSecret, 0, basekey, 0, raSecret.length);
        System.arraycopy(salt, 0, basekey, raSecret.length, salt.length);
        // Construct the base key according to rfc4210, section 5.1.3.1
        MessageDigest dig = MessageDigest.getInstance(owfOid, "BC");
        for (int i = 0; i < iterationCount; i++) {
            basekey = dig.digest(basekey);
            dig.reset();
        }
        // HMAC/SHA1 is normal 1.3.6.1.5.5.8.1.2 or 1.2.840.113549.2.7 
        Mac mac = Mac.getInstance(macOid, "BC");
        SecretKey key = new SecretKeySpec(basekey, macOid);
        mac.init(key);
        mac.reset();
        mac.update(protectedBytes, 0, protectedBytes.length);
        byte[] out = mac.doFinal();
        // My out should now be the same as the protection bits
        byte[] pb = protection.getBytes();
        ret = Arrays.equals(out, pb);
    }
    return ret;
}

From source file:org.apigw.commons.crypto.ApigwCrypto.java

protected void validateKey(Key key) throws InvalidKeyException, NoSuchAlgorithmException {
    String algorithm = key.getAlgorithm();
    int size = key.getEncoded().length * 8;
    if (!KEY_ALGORITHM.equalsIgnoreCase(algorithm)) {
        String msg = "Expected key of type: " + KEY_ALGORITHM + ", instead it was: " + algorithm;
        log.error(msg);/*w w w.  j  a  v  a 2s  . c o  m*/
        throw new InvalidKeyException(msg);
    } else if (size > Cipher.getMaxAllowedKeyLength(KEY_ALGORITHM)) {
        String msg = "Illegal key size, max platform support for " + KEY_ALGORITHM + " keys is "
                + Cipher.getMaxAllowedKeyLength(KEY_ALGORITHM);
        log.error(msg);
        throw new InvalidKeyException(msg);
    }
}

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

boolean verify(Key key, SignedInfo si, byte[] sig, XMLValidateContext context)
        throws InvalidKeyException, SignatureException, XMLSignatureException {
    if (key == null || si == null || sig == null) {
        throw new NullPointerException();
    }//from  ww  w .  ja va2s. c o m
    if (!(key instanceof SecretKey)) {
        throw new InvalidKeyException("key must be SecretKey");
    }
    if (hmac == null) {
        try {
            hmac = Mac.getInstance(getJCAAlgorithm());
        } catch (NoSuchAlgorithmException nsae) {
            throw new XMLSignatureException(nsae);
        }
    }
    if (outputLengthSet && outputLength < getDigestLength()) {
        throw new XMLSignatureException("HMACOutputLength must not be less than " + getDigestLength());
    }
    hmac.init((SecretKey) key);
    ((DOMSignedInfo) si).canonicalize(context, new MacOutputStream(hmac));
    byte[] result = hmac.doFinal();

    return MessageDigest.isEqual(sig, result);
}

From source file:org.opensc.pkcs11.spi.PKCS11CipherSpi.java

private int getPKCS11MechanismType() throws InvalidKeyException {
    int pkcs11_alg;

    if (this.algorithm.equals("RSA/ECB/PKCS1Padding"))
        pkcs11_alg = PKCS11Mechanism.CKM_RSA_PKCS;
    else//from   w ww.  j  a v a2  s . c  om
        throw new InvalidKeyException("Signature algorithm [" + this.algorithm + "] is unsupported.");

    return pkcs11_alg;
}