Example usage for java.security NoSuchAlgorithmException getCause

List of usage examples for java.security NoSuchAlgorithmException getCause

Introduction

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

Prototype

public synchronized Throwable getCause() 

Source Link

Document

Returns the cause of this throwable or null if the cause is nonexistent or unknown.

Usage

From source file:org.suren.autotest.web.framework.util.Encryptor.java

/** 
 * ?//from w w w . ja  va 2s  .  co m
 *  
 * @param desKey 
 * @param algorithm ??? {@link #DES}? {@link #DESEDE}?{@link #AES}?
 *            {@link #BLOWFISH}?{@link #RC2}? {@link #RC4}
 * @return 
 */
public static SecretKey getSecretKey(byte[] desKey, String algorithm) {
    if (ALG_DES.equalsIgnoreCase(algorithm)) {
        try {
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm);
            DESKeySpec dks = new DESKeySpec(desKey);
            return keyFactory.generateSecret(dks);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e.getCause());
        } catch (Exception e) {
            throw new IllegalArgumentException("?", e);
        }
    }

    return new SecretKeySpec(desKey, algorithm);
}

From source file:finale.year.stage.utility.Util.java

public static JSONObject forgotLogin(String email, String password, String id) {
    HttpJSONExchange exchange = new HttpJSONExchange();

    HashMap<String, String> headers = new HashMap<>();
    HashMap<String, String> params = new HashMap<>();
    String url = ROOT + "forgot-password";

    headers.put("User-Agent", "desktop");
    headers.put("demand", "yes");
    params.put("email", email);
    try {//w w w .ja  va2 s .c  om
        params.put("password", encryptPassword(password));
    } catch (NoSuchAlgorithmException ex) {
        forgotLogin.updateStatus("Error Occured : " + ex.getCause());
    }
    params.put("id", id);

    JSONObject json = null;
    if (isAv(mainF.mainFrame)) //Check Internet Connection 
        json = exchange.sendPOSTRequest(url, params, headers);

    //Return Result to InscriptionWindow
    return json;
}

From source file:main.java.vasolsim.common.GenericUtils.java

/**
 * initializes a cipher//w  w  w.  ja v  a  2s.c  om
 *
 * @param key  the key
 * @param mode the mode (Cipher.ENCRYPT_MODE or Cipher.DECRYPT_MODE)
 *
 * @return an initialized cipher
 *
 * @throws VaSolSimException for all the usual crypto stuff
 */
public static Cipher initCrypto(byte[] key, int mode) throws VaSolSimException {
    if (mode != Cipher.ENCRYPT_MODE && mode != Cipher.DECRYPT_MODE)
        throw new VaSolSimException(ERROR_MESSAGE_BAD_CIPHER_MODE);

    byte[] parametricIV = new byte[16];
    Cipher cipher;
    try {
        //create an IV
        SecureRandom random = new SecureRandom();
        random.nextBytes(parametricIV);

        //initialize the crypto
        cipher = Cipher.getInstance(DEFAULT_SERVICE_PROVIDER_INTERFACE, DEFAULT_SERVICE_PROVIDER);
        cipher.init(mode, new SecretKeySpec(key, DEFAULT_ENCRYPTION_ALGORITHM),
                new IvParameterSpec(parametricIV));
    } catch (NoSuchAlgorithmException e) {
        throw new VaSolSimException(ERROR_MESSAGE_GENERIC_CRYPTO + "\n\nBAD ALGORITHM\n" + e.toString() + "\n"
                + e.getCause() + "\n" + ExceptionUtils.getStackTrace(e), e);
    } catch (NoSuchProviderException e) {
        throw new VaSolSimException(ERROR_MESSAGE_GENERIC_CRYPTO + "\n\nBAD PROVIDER\n" + e.toString() + "\n"
                + e.getCause() + "\n" + ExceptionUtils.getStackTrace(e), e);
    } catch (NoSuchPaddingException e) {
        throw new VaSolSimException(ERROR_MESSAGE_GENERIC_CRYPTO + "\n\nNO SUCH PADDING\n" + e.toString() + "\n"
                + e.getCause() + "\n" + ExceptionUtils.getStackTrace(e), e);
    } catch (InvalidKeyException e) {
        throw new VaSolSimException(ERROR_MESSAGE_GENERIC_CRYPTO + "\n\nBAD KEY\n" + e.toString() + "\n"
                + e.getCause() + "\n" + ExceptionUtils.getStackTrace(e), e);
    } catch (InvalidAlgorithmParameterException e) {
        throw new VaSolSimException(ERROR_MESSAGE_GENERIC_CRYPTO + "\n\nBAD ALGORITHM PARAMS\n" + e.toString()
                + "\n" + e.getCause() + "\n" + ExceptionUtils.getStackTrace(e), e);
    }

    return cipher;
}

From source file:com.xinferin.licensing.LicenceActivator.java

/**
 * Verifies the signature for the given bytes using the public key.
 * @param signature Signature/*  ww  w  .java 2 s.c  om*/
 * @param data Data that was signed
 * @return boolean True if valid signature else false
 * @throws Exception 
*/
public boolean verifySignature(byte[] signature, byte[] data) throws Exception {

    try {
        initialiseKeys();
        Signature signatureInstance = Signature.getInstance("SHA1withRSA");
        signatureInstance.initVerify(publicKey);
        signatureInstance.update(data);

        return signatureInstance.verify(signature);
    } catch (NoSuchAlgorithmException e) {
        throw new Exception("There is no such algorithm. Please check the JDK ver." + e.getCause());
    } catch (SignatureException e) {
        throw new Exception("There is a problem with the signature provided " + e.getCause());
    }
}

From source file:io.apiman.gateway.vertx.api.AuthenticatingRouteMatcher.java

private boolean basicAuth(HttpServerRequest request, String encodedAuth) {
    byte[] authBytes = Base64.decodeBase64(encodedAuth);
    String decodedString = new String(authBytes);
    String[] splitAuth = StringUtils.split(StringUtils.trim(decodedString), ":"); //$NON-NLS-1$

    if (splitAuth.length != 2)
        return false;

    if (fileBasicAuthData.containsKey(splitAuth[0])) {
        String storedHash = new String(Base64.decodeBase64(fileBasicAuthData.get(splitAuth[0])));

        MessageDigest digest;//w w w  .  ja  v  a  2 s  .c o  m
        try {
            digest = MessageDigest.getInstance("SHA-256"); //$NON-NLS-1$
            digest.update(splitAuth[1].getBytes());

            String receivedHash = new String(digest.digest());

            if (storedHash.equals(receivedHash)) {
                return true;
            }
        } catch (NoSuchAlgorithmException e) {
            logger.error(e.getMessage(), e.getCause());
        }
    }

    request.response().headers().add("WWW-Authenticate", "Basic realm=\"" + config.getRealm() + "\""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$

    return false;
}

From source file:com.xinferin.licensing.LicenceGenerator.java

/**
 * Signs the data and returns the signature.
 * @param toBeSigned Data to be signed//from w ww  .  j  a v a 2  s.c  o m
 * @return byte[] Signature
 * @throws Exception 
*/
public byte[] signData(byte[] toBeSigned) throws Exception {

    try {
        if (privateKey == null)
            initialisePrivateKey();

        Signature signatureInstance = Signature.getInstance("SHA1withRSA");
        signatureInstance.initSign(privateKey);
        signatureInstance.update(toBeSigned);

        return signatureInstance.sign();

    } catch (NoSuchAlgorithmException ex) {
        throw new Exception("The SHA1withRSA algorithm was not found. " + ex.getCause());
    } catch (InvalidKeyException in) {
        throw new Exception("Invalid key returned from database. " + in.getCause());
    } catch (SignatureException se) {
        throw new Exception("No signature instance can be created. " + se.getCause());
    }
}

From source file:main.java.vasolsim.common.file.__NONUSEDREFERENCE_VaSOLSimExam.java

/**
 * Creates a cipher around a 128bit AES encryption initialized to decryption mode.
 *
 * @param key the key for the cipher//  w  w  w .  j  av  a2 s .  c om
 *
 * @return initialized cipher, null if there is an error. The popup manager is used to notify errors.
 */
protected static Cipher getDecryptionCipher(byte[] key) throws VaSolSimException {
    byte[] validatedKey = new byte[algorithmExpectedKeyLengthInBytes];

    /*
     * Holy crap yes I know this is terribly insecure but if you give this function an encryption key smaller
     * than 128 bits or of a value than the one you have set in teh static fields we have bigger problems to
     * deal with. Also, its for school, who is actually going to read this but me haha. If you do, email me with
     * the subject line LAWL YOUR CRYPTO IS REALLY BAD and we can share a laugh;
     *
     * Anyways, if the key is too short, repeat the byte sequence (copy it) until the byte array key is long
     * enough.
     */
    if (key.length < algorithmExpectedKeyLengthInBytes) {
        int invalidatedKeyIndex = 0;
        for (int index = 0; index < algorithmExpectedKeyLengthInBytes; index++) {
            validatedKey[index] = key[invalidatedKeyIndex++];

            if (index >= key.length)
                invalidatedKeyIndex = 0;
        }
    } else if (key.length > algorithmExpectedKeyLengthInBytes) {
        if (!(key.length == 32 || key.length == 64))
            throw new VaSolSimException(
                    ERROR_MESSAGE_GENERIC_CRYPTO + "\n\nBAD KEY: HIGHER KEY NOT POT (256, 512)");

        if (key.length == 32) {
            byte[] xorKey = new byte[16];
            byte[] lowerHalf = new byte[16];
            byte[] higherHalf = new byte[16];

            System.arraycopy(key, 0, lowerHalf, 0, 16);
            System.arraycopy(key, 16, higherHalf, 0, 16);

            for (int index = 0; index < 16; index++) {
                int xorBytes = (int) lowerHalf[index] ^ (int) higherHalf[index];
                xorKey[index] = (byte) (0xff & xorBytes);
            }

            validatedKey = xorKey;
        } else {
            byte[] lowerQuarterOne = new byte[16];
            byte[] lowerQuarterTwo = new byte[16];
            byte[] higherQuarterOne = new byte[16];
            byte[] higherQuarterTwo = new byte[16];
            byte[] lowerHalf = new byte[16];
            byte[] higherHalf = new byte[16];
            byte[] xorKey = new byte[16];

            System.arraycopy(key, 0, lowerQuarterOne, 0, 16);
            System.arraycopy(key, 16, lowerQuarterTwo, 0, 16);
            System.arraycopy(key, 32, higherQuarterOne, 0, 16);
            System.arraycopy(key, 48, higherQuarterTwo, 0, 16);

            for (int index = 0; index < 16; index++) {
                int xorBytes = (int) lowerQuarterOne[index] ^ (int) lowerQuarterTwo[index];
                lowerHalf[index] = (byte) (0xff & xorBytes);
            }

            for (int index = 0; index < 16; index++) {
                int xorBytes = (int) higherQuarterOne[index] ^ (int) higherQuarterTwo[index];
                higherHalf[index] = (byte) (0xff & xorBytes);
            }

            for (int index = 0; index < 16; index++) {
                int xorBytes = (int) lowerHalf[index] ^ (int) higherHalf[index];
                xorKey[index] = (byte) (0xff & xorBytes);
            }

            validatedKey = xorKey;
        }

    } else if (key.length == algorithmExpectedKeyLengthInBytes)
        validatedKey = key;

    Cipher cipher = null;
    try {
        System.out.println(validatedKey.length);

        cipher = Cipher.getInstance(serviceProviderInterface, serviceProvider);
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(validatedKey, algorithm), new IvParameterSpec(IV));
    } catch (NoSuchAlgorithmException e) {
        throw new VaSolSimException(ERROR_MESSAGE_GENERIC_CRYPTO + "\n\nBAD ALGORITHM\n" + e.toString() + "\n"
                + e.getCause() + "\n" + ExceptionUtils.getStackTrace(e), e);
    } catch (NoSuchProviderException e) {
        throw new VaSolSimException(ERROR_MESSAGE_GENERIC_CRYPTO + "\n\nBAD PROVIDER\n" + e.toString() + "\n"
                + e.getCause() + "\n" + ExceptionUtils.getStackTrace(e), e);
    } catch (NoSuchPaddingException e) {
        throw new VaSolSimException(ERROR_MESSAGE_GENERIC_CRYPTO + "\n\nNO SUCH PADDING\n" + e.toString() + "\n"
                + e.getCause() + "\n" + ExceptionUtils.getStackTrace(e), e);
    } catch (InvalidKeyException e) {
        throw new VaSolSimException(ERROR_MESSAGE_GENERIC_CRYPTO + "\n\nBAD KEY\n" + e.toString() + "\n"
                + e.getCause() + "\n" + ExceptionUtils.getStackTrace(e), e);
    } catch (InvalidAlgorithmParameterException e) {
        throw new VaSolSimException(ERROR_MESSAGE_GENERIC_CRYPTO + "\n\nBAD ALGORITHM PARAMS\n" + e.toString()
                + "\n" + e.getCause() + "\n" + ExceptionUtils.getStackTrace(e), e);
    }

    return cipher;
}

From source file:main.java.vasolsim.common.file.__NONUSEDREFERENCE_VaSOLSimExam.java

/**
 * Creates a cipher around a statically defined DEFAULT_ENCRYPTION_ALGORITHM, AES 128bit by default, initialized to
 * encryption mode./* w  w w.j  ava  2 s . c  o  m*/
 *
 * @param key secure hash of some sort of the key
 *
 * @return initialized cipher, null if internal exception
 *
 * @throws VaSolSimException any internal cryptographic related exceptions throw this for debugging to the user
 */
protected static Cipher getEncryptionCipher(byte[] key) throws VaSolSimException {
    byte[] validatedKey = new byte[algorithmExpectedKeyLengthInBytes];

    /*
     * Holy crap yes I know this is terribly insecure but if you give this function an encryption key smaller
     * than 128 bits or of a value than the one you have set in teh static fields we have bigger problems to
     * deal with. Also, its for school, who is actually going to read this but me haha. If you do, email me with
     * the subject line LAWL YOUR CRYPTO IS REALLY BAD and we can share a laugh;
     *
     * Anyways, if the key is too short, repeat the byte sequence (copy it) until the byte array key is long
     * enough.
     */
    if (key.length < algorithmExpectedKeyLengthInBytes) {

        int invalidatedKeyIndex = 0;
        for (int index = 0; index < algorithmExpectedKeyLengthInBytes; index++) {
            validatedKey[index] = key[invalidatedKeyIndex++];

            if (index >= key.length)
                invalidatedKeyIndex = 0;
        }
    } else if (key.length > algorithmExpectedKeyLengthInBytes) {
        if (!(key.length == 32 || key.length == 64))
            throw new VaSolSimException(
                    ERROR_MESSAGE_GENERIC_CRYPTO + "\n\nBAD KEY: HIGHER KEY NOT POT (256, 512)");

        if (key.length == 32) {
            byte[] xorKey = new byte[16];
            byte[] lowerHalf = new byte[16];
            byte[] higherHalf = new byte[16];

            System.arraycopy(key, 0, lowerHalf, 0, 16);
            System.arraycopy(key, 16, higherHalf, 0, 16);

            for (int index = 0; index < 16; index++) {
                int xorBytes = (int) lowerHalf[index] ^ (int) higherHalf[index];
                xorKey[index] = (byte) (0xff & xorBytes);
            }

            validatedKey = xorKey;
        } else {
            byte[] lowerQuarterOne = new byte[16];
            byte[] lowerQuarterTwo = new byte[16];
            byte[] higherQuarterOne = new byte[16];
            byte[] higherQuarterTwo = new byte[16];
            byte[] lowerHalf = new byte[16];
            byte[] higherHalf = new byte[16];
            byte[] xorKey = new byte[16];

            System.arraycopy(key, 0, lowerQuarterOne, 0, 16);
            System.arraycopy(key, 16, lowerQuarterTwo, 0, 16);
            System.arraycopy(key, 32, higherQuarterOne, 0, 16);
            System.arraycopy(key, 48, higherQuarterTwo, 0, 16);

            for (int index = 0; index < 16; index++) {
                int xorBytes = (int) lowerQuarterOne[index] ^ (int) lowerQuarterTwo[index];
                lowerHalf[index] = (byte) (0xff & xorBytes);
            }

            for (int index = 0; index < 16; index++) {
                int xorBytes = (int) higherQuarterOne[index] ^ (int) higherQuarterTwo[index];
                higherHalf[index] = (byte) (0xff & xorBytes);
            }

            for (int index = 0; index < 16; index++) {
                int xorBytes = (int) lowerHalf[index] ^ (int) higherHalf[index];
                xorKey[index] = (byte) (0xff & xorBytes);
            }

            validatedKey = xorKey;
        }
    } else if (key.length == algorithmExpectedKeyLengthInBytes)
        validatedKey = key;

    /*
     * Initialize the Cipher
     */
    Cipher cipher = null;
    try {
        cipher = Cipher.getInstance(serviceProviderInterface, serviceProvider);
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(validatedKey, algorithm), new IvParameterSpec(IV));
    } catch (NoSuchAlgorithmException e) {
        throw new VaSolSimException(ERROR_MESSAGE_GENERIC_CRYPTO + "\n\nBAD ALGORITHM\n" + e.toString() + "\n"
                + e.getCause() + "\n" + ExceptionUtils.getStackTrace(e), e);
    } catch (NoSuchProviderException e) {
        throw new VaSolSimException(ERROR_MESSAGE_GENERIC_CRYPTO + "\n\nBAD PROVIDER\n" + e.toString() + "\n"
                + e.getCause() + "\n" + ExceptionUtils.getStackTrace(e), e);
    } catch (NoSuchPaddingException e) {
        throw new VaSolSimException(ERROR_MESSAGE_GENERIC_CRYPTO + "\n\nNO SUCH PADDING\n" + e.toString() + "\n"
                + e.getCause() + "\n" + ExceptionUtils.getStackTrace(e), e);
    } catch (InvalidKeyException e) {
        throw new VaSolSimException(ERROR_MESSAGE_GENERIC_CRYPTO + "\n\nBAD KEY\n" + e.toString() + "\n"
                + e.getCause() + "\n" + ExceptionUtils.getStackTrace(e), e);
    } catch (InvalidAlgorithmParameterException e) {
        throw new VaSolSimException(ERROR_MESSAGE_GENERIC_CRYPTO + "\n\nBAD ALGORITHM PARAMS\n" + e.toString()
                + "\n" + e.getCause() + "\n" + ExceptionUtils.getStackTrace(e), e);
    }

    return cipher;
}

From source file:com.vmware.identity.idm.server.clientcert.IdmCertificatePathValidator.java

/**
 * build and validate cert path from end certificate.
 *
 * Note: the certpath return seems only include intermediate CA unless there is none in
 * which case the end cert is returned.// w  w  w  .  j  av  a  2  s .  c om
 * @param endCert
 * @return CertPath  never null
 * @throws CertificatePathBuildingException
 */
private CertPath buildCertPath(X509Certificate endCert) throws CertificatePathBuildingException {

    CertPathBuilder cpb = null;
    try {
        cpb = CertPathBuilder.getInstance("PKIX");
    } catch (NoSuchAlgorithmException e) {
        throw new CertificatePathBuildingException("Error building CertPathBuilder:" + e.getMessage(), e);
    }

    PKIXBuilderParameters params = CreatePKIXBuilderParameters(endCert);
    CertPathBuilderResult cpbResult;
    try {
        cpbResult = cpb.build(params);
    } catch (CertPathBuilderException e) {
        throw new CertificatePathBuildingException(e.getMessage(), e.getCause());
    } catch (InvalidAlgorithmParameterException e) {
        throw new CertificatePathBuildingException(e.getMessage(), e);
    }

    CertPath cp = cpbResult.getCertPath();

    return cp;
}

From source file:ca.uhn.hl7v2.testpanel.model.conn.AbstractConnection.java

public KeyStore getTlsKeystore() throws KeyStoreException {
    if (isBlank(myTlsKeystoreLocation) || isTls() == false) {
        return null;
    }/*from   ww  w .  j  a  va2  s .com*/
    if (myTlsKeystore != null) {
        return myTlsKeystore;
    }

    File jksFile = new File(myTlsKeystoreLocation);
    if (!jksFile.exists() || !jksFile.canRead()) {
        throw new KeyStoreException("File does not exist or can not be read: " + jksFile.getAbsolutePath());
    }

    char[] password = null;
    if (isNotBlank(myTlsKeystorePassword)) {
        password = myTlsKeystorePassword.toCharArray();
    }

    KeyStore keystore;
    try {
        keystore = KeystoreUtils.loadKeystore(jksFile, password);
    } catch (NoSuchAlgorithmException e) {
        ourLog.error("Failed to load keystore!", e);
        throw new KeyStoreException("Failed to load keystore: " + e.getMessage());
    } catch (CertificateException e) {
        ourLog.error("Failed to load keystore!", e);
        throw new KeyStoreException("Failed to load keystore: " + e.getMessage());
    } catch (IOException e) {
        ourLog.error("Failed to load keystore!", e);
        if (e.getCause() instanceof UnrecoverableKeyException) {
            throw new KeyStoreException("Keystore password appears to be incorrect");
        }
        throw new KeyStoreException("Failed to load keystore: " + e.getMessage());
    }

    if (this instanceof InboundConnection) {
        if (!KeystoreUtils.validateKeystoreForTlsReceiving(keystore)) {
            throw new KeyStoreException("Keystore contains no keys appropriate for receiving data");
        }
    } else if (this instanceof OutboundConnection) {
        if (!KeystoreUtils.validateKeystoreForTlsSending(keystore)) {
            throw new KeyStoreException("Keystore contains no keys appropriate for receiving data");
        }
    }

    myTlsKeystore = keystore;
    return myTlsKeystore;
}