Example usage for java.security InvalidKeyException getMessage

List of usage examples for java.security InvalidKeyException getMessage

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:DDTTestContext.java

/**
 * Construct an instance from a delimited string of the format key1=value1;key2=value2
 * @param delimitedString - the input (delimited) string
 * @param delim - the delimited string separating the key=value pairs - the default is ';'.
 *              If the actual delimiter is not the default then delimitedString has the first character that non-standard delim
 * @param validDelims - a coma-delimited string of valid delimiter - used only in the rare case of using non-standard delim
 *///from w w w.  j a  v a2s  .  c om
public DDTTestContext(String delimitedString, String delim, String validDelims) {

    // Parameters sanity check1 - all strings are not blank
    if (isBlank(delimitedString)) {
        return;
    }

    // Parameters sanity check2 - at least one instance of <key> "=" <value> exists
    if (!delimitedString.contains("=")) {
        return;
    }

    String actualDelim = delim;
    String actualStr = delimitedString;

    // Determine if the caller uses non standard delimiter.
    if (validDelims.contains(delimitedString.substring(0, 1))) {
        actualDelim = delimitedString.substring(0, 1);
        actualStr = delimitedString.substring(1);
    }

    String[] a1 = actualStr.split(actualDelim);
    for (int i = 0; i < a1.length; i++) {
        try {
            int idx = a1[i].indexOf("=");
            if (idx < 0) {
                throw new InvalidKeyException(
                        "'=' Delimiter not found in item " + (i + 1) + " of " + actualStr);
            }
            String key = a1[i].substring(0, idx);
            String value = a1[i].substring(idx + 1);

            if (isBlank(key)) {
                throw new InvalidKeyException("Empty key value in item " + (i + 1) + " of " + actualStr);
            }
            if (null != this.get(key.toLowerCase())) {
                throw new InvalidKeyException(
                        "Repeated key value of " + key + " in item " + (i + 1) + " of " + actualStr);
            }
            // store next & unique value (a2[1]) in hashtable using key of a2[0]
            this.put(key.toLowerCase(), value);
        } // try
        catch (InvalidKeyException e) {
            System.out.println(e.getMessage());
            return;
        }
    } // for loop
}

From source file:eu.eidas.auth.engine.SAMLEngineUtils.java

/**
 * @param cert/* ww w  .j  a  v  a 2s .  co  m*/
 * @return true when the certificate is self signed
 */
public static boolean isCertificateSelfSigned(X509Certificate cert) {
    try {
        PublicKey publicKey = cert.getPublicKey();
        cert.verify(publicKey);
        return true;
    } catch (java.security.SignatureException sigEx) {
        LOG.info("ERROR : SignatureException {}", sigEx.getMessage());
        LOG.debug("ERROR : SignatureException {}", sigEx);
        return false;
    } catch (InvalidKeyException keyEx) {
        // Invalid key --> not self-signed
        LOG.info("ERROR : InvalidKeyException {}", keyEx.getMessage());
        LOG.debug("ERROR : InvalidKeyException {}", keyEx);
        return false;
    } catch (CertificateException certExc) {
        LOG.info("ERROR : CertificateException {}", certExc.getMessage());
        LOG.debug("ERROR : CertificateException {}", certExc);
        return false;
    } catch (NoSuchAlgorithmException nsaExc) {
        LOG.info("ERROR : Bad algorithm: " + nsaExc.getMessage());
        LOG.debug("ERROR : Bad algorithm: " + nsaExc);
        return false;
    } catch (NoSuchProviderException nspExc) {
        LOG.info("ERROR : Bad provider: " + nspExc.getMessage());
        LOG.debug("ERROR : Bad provider: " + nspExc);
        return false;
    }
}

From source file:be.fedict.commons.eid.consumer.BeIDIntegrity.java

/**
 * Verifies an authentication signature.
 * /*  w  w w  .  ja  va  2 s .co  m*/
 * @param toBeSigned
 * @param signatureValue
 * @param authnCertificate
 * @return
 */
public boolean verifyAuthnSignature(final byte[] toBeSigned, final byte[] signatureValue,
        final X509Certificate authnCertificate) {
    final PublicKey publicKey = authnCertificate.getPublicKey();
    boolean result;
    try {
        result = this.verifySignature(signatureValue, publicKey, toBeSigned);
    } catch (final InvalidKeyException ikex) {
        LOG.warn("invalid key: " + ikex.getMessage(), ikex);
        return false;
    } catch (final NoSuchAlgorithmException nsaex) {
        LOG.warn("no such algo: " + nsaex.getMessage(), nsaex);
        return false;
    } catch (final SignatureException sigex) {
        LOG.warn("signature error: " + sigex.getMessage(), sigex);
        return false;
    }
    return result;
}

From source file:be.fedict.commons.eid.consumer.BeIDIntegrity.java

/**
 * Verifies a non-repudiation signature.
 * /*w  w  w  . ja va2 s. co m*/
 * @param expectedDigestValue
 * @param signatureValue
 * @param certificate
 * @return
 */
public boolean verifyNonRepSignature(final byte[] expectedDigestValue, final byte[] signatureValue,
        final X509Certificate certificate) {
    try {
        return __verifyNonRepSignature(expectedDigestValue, signatureValue, certificate);
    } catch (final InvalidKeyException ikex) {
        LOG.warn("invalid key: " + ikex.getMessage(), ikex);
        return false;
    } catch (final NoSuchAlgorithmException nsaex) {
        LOG.warn("no such algo: " + nsaex.getMessage(), nsaex);
        return false;
    } catch (final NoSuchPaddingException nspex) {
        LOG.warn("no such padding: " + nspex.getMessage(), nspex);
        return false;
    } catch (final BadPaddingException bpex) {
        LOG.warn("bad padding: " + bpex.getMessage(), bpex);
        return false;
    } catch (final IOException ioex) {
        LOG.warn("IO error: " + ioex.getMessage(), ioex);
        return false;
    } catch (final IllegalBlockSizeException ibex) {
        LOG.warn("illegal block size: " + ibex.getMessage(), ibex);
        return false;
    }
}

From source file:com.auditmark.jscrambler.client.JScrambler.java

private String generateHMACSignature(String requestMethod, String resourcePath, Map<String, String> params)
        throws InvalidKeyException, NoSuchAlgorithmException, UnsupportedEncodingException {
    String data = hmacSignatureData(requestMethod, resourcePath, apiHost, params);
    try {//from w  w w. j a v a2s  .  c  o  m
        SecretKeySpec signingKey = new SecretKeySpec(secretKey.getBytes(), "HmacSHA256");
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(signingKey);
        byte[] digest = mac.doFinal(data.getBytes());
        return new sun.misc.BASE64Encoder().encode(digest);

    } catch (InvalidKeyException e) {
        System.err.println("Invalid key: " + e.getMessage());
        throw e;
    } catch (NoSuchAlgorithmException e) {
        System.err.println("No such algorithm: " + e.getMessage());
        throw e;
    }
}

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

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

    if (isInitialized == false) {
        try {/*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);
}

From source file:com.cloud.bridge.util.RestAuth.java

/**
 * Create a signature by the following method:
 *     new String( Base64( SHA1( key, byte array )))
 * /*from  w ww .j a  va 2 s. c  o  m*/
 * @param signIt    - the data to generate a keyed HMAC over
 * @param secretKey - the user's unique key for the HMAC operation
 * @return String   - the recalculated string
 * @throws SignatureException
 */
private String calculateRFC2104HMAC(String signIt, String secretKey) throws SignatureException {
    String result = null;
    try {
        SecretKeySpec key = new SecretKeySpec(secretKey.getBytes(), "HmacSHA1");
        Mac hmacSha1 = Mac.getInstance("HmacSHA1");
        hmacSha1.init(key);
        byte[] rawHmac = hmacSha1.doFinal(signIt.getBytes());
        result = new String(Base64.encodeBase64(rawHmac));
    } catch (InvalidKeyException e) {
        throw new SignatureException("Failed to generate keyed HMAC on REST request because key " + secretKey
                + " is invalid" + e.getMessage());
    } catch (Exception e) {
        throw new SignatureException("Failed to generate keyed HMAC on REST request: " + e.getMessage());
    }
    return result.trim();
}

From source file:net.seleucus.wsp.crypto.FwknopSymmetricCryptoTest.java

/**
 * Test of decrypt method, of class FwknopSymmetricCrypto.
 *///from w w  w. j a  va 2  s.  co m
@Test
public void testDecrypt() {
    byte[] key = decodeFromHexString("fd38fb08781e77ca7d85c9f3ec4e35203f4cae3f0d5fd78658638e2d32dd0bc5");
    // ciphertext contains SHA256 HMAC, must be removed before calling decrypt function
    String ciphertext = "88/CLhVNlIRAaqrmMnh0VBwMpoAKZP0r3SwTJ5Rr3PCAVI2xQcDEtnrNnEx6J5udAjWlwtmlCFVGykvLb2X/pXr3G8hf+ZLmQLQV6mU5YHuEqlAlMmXtWZfd65mi5S876hJvdlyhfMpLDrnc5RB/bBPjKpDS98X5fJsDVxnQ7z8LbUYWSsDNt7N2uj4kB6+Ia8usPq5UZIvSoNpNnsPGeyofSC2o6EhfMC9IaiLcfnr54x9cKYw6uApNno5TpNg/3B1dZ9f/DFp48H4fdlxmYehW4h5fPnRPE";
    ciphertext = removeMAC(ciphertext, FwknopSymmetricCrypto.HASH_TYPE_SHA256);
    String expResult = "1183491131188171:dW9wYXJ5b2N1:1421953628:2.0.1:1:MjMyLjIwMC4xMC45NCx0Y3AvNDg4NjY:67Fi6nvavJQAvpaH6OEhqoknCPDd/vf1L0tif8vy1RDE2S67WfTuQ0Fy705ToGN/r9zOwjK8HvqvF6+BY6q7jA";
    try {
        String result = FwknopSymmetricCrypto.decrypt(key, ciphertext);
        assertEquals(expResult, result);
    } catch (InvalidKeyException e) {
        System.out.println(
                "Check: Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files");
        fail("Unexpected exception: " + e.getMessage());
    } catch (Exception e) {
        fail("Unexpected exception: " + e.getMessage());
    }
}

From source file:net.seleucus.wsp.crypto.FwknopSymmetricCryptoTest.java

/**
 * Test of encrypt method, of class FwknopSymmetricCrypto.
 *//*  w  w w  .  jav  a2 s. c o m*/
@Test
public void testEncrypt() {
    byte[] key = new byte[32];
    sr.nextBytes(key);
    int msgLen = 1 + (abs(sr.nextInt()) % 512);
    byte[] msg = new byte[msgLen];
    String message = new String(msg);
    try {
        String encrypted = FwknopSymmetricCrypto.encrypt(key, message);
        System.out.println(encrypted);
        String decrypted = FwknopSymmetricCrypto.decrypt(key, encrypted);
        assertEquals(message, decrypted);
    } catch (InvalidKeyException e) {
        System.out.println(
                "Check: Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files");
        fail("Unexpected exception: " + e.getMessage());
    } catch (Exception e) {
        fail("Unexpected exception: " + e.getMessage());
    }
}

From source file:com.cws.esolutions.security.processors.impl.FileSecurityProcessorImpl.java

/**
 * @see com.cws.esolutions.security.processors.interfaces.IFileSecurityProcessor#decryptFile(com.cws.esolutions.security.processors.dto.FileSecurityRequest)
 *///from w w w. ja  va  2s  .co m
public synchronized FileSecurityResponse decryptFile(final FileSecurityRequest request)
        throws FileSecurityException {
    final String methodName = IFileSecurityProcessor.CNAME
            + "#decryptFile(final FileSecurityRequest request) throws FileSecurityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("FileSecurityRequest: {}", request);
    }

    FileSecurityResponse response = new FileSecurityResponse();

    final RequestHostInfo reqInfo = request.getHostInfo();
    final UserAccount userAccount = request.getUserAccount();
    final KeyManager keyManager = KeyManagementFactory.getKeyManager(keyConfig.getKeyManager());

    if (DEBUG) {
        DEBUGGER.debug("RequestHostInfo: {}", reqInfo);
        DEBUGGER.debug("UserAccount", userAccount);
        DEBUGGER.debug("KeyManager: {}", keyManager);
    }

    try {
        KeyPair keyPair = keyManager.returnKeys(userAccount.getGuid());

        if (keyPair != null) {
            Cipher cipher = Cipher.getInstance(fileSecurityConfig.getEncryptionAlgorithm());
            cipher.init(Cipher.DECRYPT_MODE, keyPair.getPublic());

            if (DEBUG) {
                DEBUGGER.debug("Cipher: {}", cipher);
            }

            IOUtils.write(
                    IOUtils.toByteArray(
                            new CipherInputStream(new FileInputStream(request.getEncryptedFile()), cipher)),
                    new FileOutputStream(request.getDecryptedFile()));

            if ((request.getEncryptedFile().exists()) && (request.getEncryptedFile().length() != 0)) {
                response.setSignedFile(request.getEncryptedFile());
                response.setRequestStatus(SecurityRequestStatus.SUCCESS);
            } else {
                response.setRequestStatus(SecurityRequestStatus.FAILURE);
            }
        } else {
            response.setRequestStatus(SecurityRequestStatus.FAILURE);
        }
    } catch (IOException iox) {
        ERROR_RECORDER.error(iox.getMessage(), iox);

        throw new FileSecurityException(iox.getMessage(), iox);
    } catch (NoSuchAlgorithmException nsax) {
        ERROR_RECORDER.error(nsax.getMessage(), nsax);

        throw new FileSecurityException(nsax.getMessage(), nsax);
    } catch (NoSuchPaddingException nspx) {
        ERROR_RECORDER.error(nspx.getMessage(), nspx);

        throw new FileSecurityException(nspx.getMessage(), nspx);
    } catch (InvalidKeyException ikx) {
        ERROR_RECORDER.error(ikx.getMessage(), ikx);

        throw new FileSecurityException(ikx.getMessage(), ikx);
    } catch (KeyManagementException kmx) {
        ERROR_RECORDER.error(kmx.getMessage(), kmx);

        throw new FileSecurityException(kmx.getMessage(), kmx);
    } finally {
        // audit
        try {
            AuditEntry auditEntry = new AuditEntry();
            auditEntry.setHostInfo(reqInfo);
            auditEntry.setAuditType(AuditType.DECRYPTFILE);
            auditEntry.setUserAccount(userAccount);
            auditEntry.setAuthorized(Boolean.TRUE);
            auditEntry.setApplicationId(request.getApplicationId());
            auditEntry.setApplicationName(request.getAppName());

            if (DEBUG) {
                DEBUGGER.debug("AuditEntry: {}", auditEntry);
            }

            AuditRequest auditRequest = new AuditRequest();
            auditRequest.setAuditEntry(auditEntry);

            if (DEBUG) {
                DEBUGGER.debug("AuditRequest: {}", auditRequest);
            }

            auditor.auditRequest(auditRequest);
        } catch (AuditServiceException asx) {
            ERROR_RECORDER.error(asx.getMessage(), asx);
        }
    }

    return response;
}