Example usage for java.security NoSuchAlgorithmException printStackTrace

List of usage examples for java.security NoSuchAlgorithmException printStackTrace

Introduction

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

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:org.tomahawk.libtomahawk.resolver.PipeLine.java

/**
 * Send a broadcast containing the stream url which has previously been requested by a
 * MediaPlayerInterface./*from   w  ww  .  ja v a2  s  .  c om*/
 */
public void sendStreamUrlReportBroadcast(final String resultKey, final String url,
        final Map<String, String> headers) {
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                String finalUrl = url;
                if (headers != null) {
                    finalUrl = TomahawkUtils.getRedirectedUrl(TomahawkUtils.HTTP_METHOD_GET, url, headers);
                }
                Intent reportIntent = new Intent(PIPELINE_STREAMURLREPORTED);
                reportIntent.putExtra(PIPELINE_STREAMURLREPORTED_RESULTKEY, resultKey);
                reportIntent.putExtra(PIPELINE_STREAMURLREPORTED_URL, finalUrl);
                TomahawkApp.getContext().sendBroadcast(reportIntent);
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (KeyManagementException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }).start();
}

From source file:de.rrze.idmone.utils.jpwgen.PwGenerator.java

/**
 * This method parses the command line options, initializes the needed
 * objects and generates the required number of passwords by calling
 * <em>generatePassword()</em>. When not used as a stand-alone program this
 * method is to be preferred instead of the main(String[]).
 * /*  w  ww .  j  a  v  a2  s.c o m*/
 * @param args
 *            the arguments used to initialize the generation process
 * @return a list of passwords or <em>null</em> if no suitable passwords
 *         could be generated.
 */

public static synchronized List<String> process(String[] args) {
    int passwordFlags = initDefaultFlags();

    // The length of the password to be generated
    int passwordLength = DEFAULT_PASSWORD_LENGTH;

    int numberOfPasswords = DEFAULT_NUMBER_OF_PASSWORDS;

    int maxAttempts = DEFAULT_MAX_ATTEMPTS;

    log(Messages.getString("PwGenerator.PASSWORD_GENERATOR"), //$NON-NLS-1$
            false);

    ArrayList<String> passwords = new ArrayList<String>();
    BasicParser parser = new BasicParser();
    try {
        CommandLine commandLine = parser.parse(options, args);

        parser.parse(options, args);
        if (commandLine.hasOption(CL_HELP)) {
            printUsage();
            log(Messages.getString("PwGenerator.SEPARATOR"), //$NON-NLS-1$
                    false);
            return passwords;
        }

        parser.parse(options, args);
        if (commandLine.hasOption(CL_SR_PROVIDERS)) {
            Set<String> serviceProviders = RandomFactory.getInstance()
                    .getServiceProviderFor(IRandomFactory.TYPE_SECURE_RANDOM);
            log(Messages.getString("PwGenerator.SERVICES_PROVIDERS_FOR") //$NON-NLS-1$
                    + IRandomFactory.TYPE_SECURE_RANDOM + Messages.getString("PwGenerator.NEW_LINE"), false); //$NON-NLS-1$
            for (Iterator<String> iter = serviceProviders.iterator(); iter.hasNext();) {
                String element = (String) iter.next();
                log(Messages.getString("PwGenerator.SERVICE_PROVIDERS") + element //$NON-NLS-1$
                        + Messages.getString("PwGenerator.NEW_LINE"), false); //$NON-NLS-1$
                log(Messages.getString("PwGenerator.SEPARATOR"), //$NON-NLS-1$
                        false);
                return passwords;
            }
        }

        parser.parse(options, args);
        if (commandLine.hasOption(CL_PROVIDERS)) {
            log(Messages.getString("PwGenerator.ALL_SEC_PROVIDERS") //$NON-NLS-1$
                    + IRandomFactory.TYPE_SECURE_RANDOM + Messages.getString("PwGenerator.NEW_LINE"), false); //$NON-NLS-1$
            Provider[] serviceProviders = RandomFactory.getInstance().getProviders();
            for (int i = 0; i < serviceProviders.length; i++) {
                log(Messages.getString("PwGenerator.SEPARATOR"), //$NON-NLS-1$
                        false);
                log(Messages.getString("PwGenerator.PROVIDER") + serviceProviders[i].getName() //$NON-NLS-1$
                        + Messages.getString("PwGenerator.NEW_LINE"), //$NON-NLS-1$
                        false);
                Set<Provider.Service> services = serviceProviders[i].getServices();
                log(Messages.getString("PwGenerator.SERVICES") + Messages.getString("PwGenerator.NEW_LINE"), //$NON-NLS-1$//$NON-NLS-2$
                        false);
                log(services.toString(), false);
                log(Messages.getString("PwGenerator.SEPARATOR"), //$NON-NLS-1$
                        false);
            }
            log(Messages.getString("PwGenerator.SEPARATOR"), //$NON-NLS-1$
                    false);
            return passwords;
        }

        if (commandLine.hasOption(CL_NUMBER_PASSWORD)) {
            String sNumberOfPasswords = commandLine.getOptionValue(CL_NUMBER_PASSWORD);
            if (sNumberOfPasswords != null)
                numberOfPasswords = Integer.parseInt(sNumberOfPasswords);
            log(Messages.getString("PwGenerator.NUM_PASSWORDS") + numberOfPasswords, false); //$NON-NLS-1$
        }

        commandLine = parser.parse(options, args);
        if (commandLine.hasOption(CL_PASSWORD_LENGTH)) {
            String sPasswordLength = commandLine.getOptionValue(CL_PASSWORD_LENGTH);
            if (sPasswordLength != null)
                passwordLength = Integer.parseInt(sPasswordLength);
            log(Messages.getString("PwGenerator.PASSWORD_LENGTH") + passwordLength, false); //$NON-NLS-1$
        }

        parser.parse(options, args);
        if (commandLine.hasOption(CL_COLUMN)) {
            doColumns = true;
            log(Messages.getString("PwGenerator.COLUMNS_ENABLED"), false); //$NON-NLS-1$
        }

        parser.parse(options, args);
        if (commandLine.hasOption(CL_TERM_WIDTH)) {
            String sTermWidth = commandLine.getOptionValue(CL_TERM_WIDTH);
            if (sTermWidth != null)
                termWidth = Integer.parseInt(sTermWidth);
            log(Messages.getString("PwGenerator.TERMINAL_LENGTH") + termWidth, false); //$NON-NLS-1$
        }

        Random random = null;
        parser.parse(options, args);
        if (commandLine.hasOption(CL_RANDOM)) {
            random = RandomFactory.getInstance().getRandom();
            log(Messages.getString("PwGenerator.NORMAL_RANDOM"), false); //$NON-NLS-1$
        } else {
            try {
                random = RandomFactory.getInstance().getSecureRandom();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
                random = RandomFactory.getInstance().getRandom();
            } catch (NoSuchProviderException e) {
                e.printStackTrace();
                random = RandomFactory.getInstance().getRandom();
            }
        }

        parser.parse(options, args);
        if (commandLine.hasOption(CL_SR_ALGORITHM)) {
            String[] data = commandLine.getOptionValues(CL_SR_ALGORITHM);
            if (data.length == 2) {
                try {
                    random = RandomFactory.getInstance().getSecureRandom(data[0], data[1]);

                    log(Messages.getString("PwGenerator.SEC_ALG") + data[0] //$NON-NLS-1$
                            + Messages.getString("PwGenerator.PROV") + data[1] //$NON-NLS-1$
                            + Messages.getString("PwGenerator.DOR"), false); //$NON-NLS-1$
                } catch (NoSuchAlgorithmException e) {
                    log(Messages.getString("PwGenerator.ERROR") + e.getMessage() //$NON-NLS-1$
                            + Messages.getString("PwGenerator.NEW_LINE"), true); //$NON-NLS-1$
                    log(Messages.getString("PwGenerator.DEFAUL_RANDOM"), true); //$NON-NLS-1$
                } catch (NoSuchProviderException e) {
                    log(Messages.getString("PwGenerator.ERROR") + e.getMessage() //$NON-NLS-1$
                            + Messages.getString("PwGenerator.NEW_LINE"), true); //$NON-NLS-1$
                    log(Messages.getString("PwGenerator.DEFAUL_RANDOM"), true); //$NON-NLS-1$
                }
            }
        }

        if (commandLine.hasOption(CL_NUMERALS)) {
            passwordFlags |= PW_DIGITS;
            log(Messages.getString("PwGenerator.DIGITS_ON"), false); //$NON-NLS-1$
        }

        if (commandLine.hasOption(CL_NO_NUMERALS)) {
            passwordFlags &= ~PW_DIGITS;
            log(Messages.getString("PwGenerator.DIGITS_OFF"), false); //$NON-NLS-1$
        }

        if (commandLine.hasOption(CL_CAPITALIZE)) {
            passwordFlags |= PW_UPPERS;
            log(Messages.getString("PwGenerator.UPPERCASE_ON"), false); //$NON-NLS-1$
        }

        if (commandLine.hasOption(CL_NO_CAPITALIZE)) {
            passwordFlags &= ~PW_UPPERS;
            log(Messages.getString("PwGenerator.UPPERCASE_OFF"), false); //$NON-NLS-1$
        }

        if (commandLine.hasOption(CL_AMBIGOUS)) {
            passwordFlags |= PW_AMBIGUOUS;
            log(Messages.getString("PwGenerator.AMBIGOUS_ON"), false); //$NON-NLS-1$
        }

        if (commandLine.hasOption(CL_NO_AMBIGOUS)) {
            passwordFlags &= ~PW_AMBIGUOUS;
            log(Messages.getString("PwGenerator.AMBIGOUS_OFF"), false); //$NON-NLS-1$
        }

        if (commandLine.hasOption(CL_SYMBOLS)) {
            passwordFlags |= PW_SYMBOLS;
            log(Messages.getString("PwGenerator.SYMBOLS_ON"), false); //$NON-NLS-1$
        }

        if (commandLine.hasOption(CL_SYMBOLS_REDUCED)) {
            passwordFlags |= PW_SYMBOLS_REDUCED;
            log(Messages.getString("PwGenerator.SYMBOLS_REDUCED_ON"), false); //$NON-NLS-1$
        }

        if (commandLine.hasOption(CL_NO_SYMBOLS)) {
            passwordFlags &= ~PW_SYMBOLS;
            passwordFlags &= ~PW_SYMBOLS_REDUCED;
            log(Messages.getString("PwGenerator.SYMBOLS_OFF"), false); //$NON-NLS-1$
        }

        if (commandLine.hasOption(CL_MAX_ATTEMPTS)) {
            String sMaxAttempts = commandLine.getOptionValue(CL_MAX_ATTEMPTS);
            if (sMaxAttempts != null)
                maxAttempts = Integer.parseInt(sMaxAttempts);
            log(Messages.getString("PwGenerator.MAX_ATTEMPTS") + maxAttempts, false); //$NON-NLS-1$
        }

        if (commandLine.hasOption(CL_REGEX_STARTS_NO_SMALL_LETTER))
            passwordFlags |= REGEX_STARTS_NO_SMALL_LETTER_FLAG;

        if (commandLine.hasOption(CL_REGEX_ENDS_NO_SMALL_LETTER))
            passwordFlags |= REGEX_STARTS_NO_SMALL_LETTER_FLAG;

        if (commandLine.hasOption(CL_REGEX_STARTS_NO_UPPER_LETTER))
            passwordFlags |= REGEX_STARTS_NO_UPPER_LETTER_FLAG;

        if (commandLine.hasOption(CL_REGEX_ENDS_NO_UPPER_LETTER))
            passwordFlags |= REGEX_ENDS_NO_UPPER_LETTER_FLAG;

        if (commandLine.hasOption(CL_REGEX_ENDS_NO_DIGIT))
            passwordFlags |= REGEX_ENDS_NO_DIGIT_FLAG;

        if (commandLine.hasOption(CL_REGEX_STARTS_NO_DIGIT))
            passwordFlags |= REGEX_STARTS_NO_DIGIT_FLAG;

        if (commandLine.hasOption(CL_REGEX_STARTS_NO_SYMBOL))
            passwordFlags |= REGEX_STARTS_NO_SYMBOL_FLAG;

        if (commandLine.hasOption(CL_REGEX_ENDS_NO_SYMBOL))
            passwordFlags |= REGEX_ENDS_NO_SYMBOL_FLAG;

        if (commandLine.hasOption(CL_REGEX_ONLY_1_CAPITAL))
            passwordFlags |= REGEX_ONLY_1_CAPITAL_FLAG;

        if (commandLine.hasOption(CL_REGEX_ONLY_1_SYMBOL))
            passwordFlags |= REGEX_ONLY_1_SYMBOL_FLAG;

        if (commandLine.hasOption(CL_REGEX_AT_LEAST_2_SYMBOLS))
            passwordFlags |= REGEX_AT_LEAST_2_SYMBOLS_FLAG;

        if (commandLine.hasOption(CL_REGEX_ONLY_1_DIGIT))
            passwordFlags |= REGEX_ONLY_1_DIGIT_FLAG;

        if (commandLine.hasOption(CL_REGEX_AT_LEAST_2_DIGITS))
            passwordFlags |= REGEX_AT_LEAST_2_DIGITS_FLAG;
        // -------------------------------------------------------------------

        log(Messages.getString("PwGenerator.GENRIC_FLAGS"), //$NON-NLS-1$
                false);

        int res = passwordFlags & PW_DIGITS;
        log(Messages.getString("PwGenerator.DIGITS") + (res != 0), false); //$NON-NLS-1$
        res = passwordFlags & PW_AMBIGUOUS;
        log(Messages.getString("PwGenerator.AMBIGOUS") + (res != 0), false); //$NON-NLS-1$
        res = passwordFlags & PW_SYMBOLS;
        log(Messages.getString("PwGenerator.SYMBOLS") + (res != 0), false); //$NON-NLS-1$
        res = passwordFlags & PW_SYMBOLS_REDUCED;
        log(Messages.getString("PwGenerator.SYMBOLS_REDUCED") + (res != 0), false); //$NON-NLS-1$
        res = passwordFlags & PW_UPPERS;
        log(Messages.getString("PwGenerator.UPPERS") + (res != 0), false); //$NON-NLS-1$
        log(Messages.getString("PwGenerator.SEPARATOR"), //$NON-NLS-1$
                false);

        log(Messages.getString("PwGenerator.GENERATING") + numberOfPasswords //$NON-NLS-1$
                + Messages.getString("PwGenerator.PW_LENGTH") //$NON-NLS-1$
                + passwordLength, false);
        log(Messages.getString("PwGenerator.PW"), //$NON-NLS-1$
                false);

        int i;
        for (i = 0; i < numberOfPasswords; i++) {
            String password = generatePassword(passwordLength, passwordFlags, maxAttempts, random);
            if (password != null)
                passwords.add(password);
        }
    } catch (ParseException e) {
        log(Messages.getString("PwGenerator.PARAM_ERROR") + e.getLocalizedMessage(), true); //$NON-NLS-1$
        printUsage();
    } catch (NumberFormatException e) {
        log(Messages.getString("PwGenerator.NUM_FORM_ERROR") + e.getLocalizedMessage(), true); //$NON-NLS-1$
        printUsage();
    }

    return passwords;
}

From source file:edu.umass.cs.gigapaxos.testing.TESTPaxosApp.java

/**
 * /*from   w  w w  .  j  a v a  2  s .c o  m*/
 */
public TESTPaxosApp() {
    // app uses nio only to send, not receive, so no PacketDemultiplexer
    try {
        md = MessageDigest.getInstance("SHA");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
}

From source file:com.dnanexus.DXHTTPRequest.java

/**
 * Construct the DXHTTPRequest using the given DXEnvironment.
 *//*from w  w  w . j  a va  2 s  .  c  om*/
public DXHTTPRequest(DXEnvironment env) {
    this.securityContext = env.getSecurityContextJson();
    this.apiserver = env.getApiserverPath();
    this.disableRetry = env.isRetryDisabled();

    SSLContextBuilder builder = new SSLContextBuilder();
    try {
        builder.loadTrustMaterial(null, new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }
        });
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    }

    SSLConnectionSocketFactory sslSF = null;
    try {
        sslSF = new SSLConnectionSocketFactory(builder.build(),
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }
    HttpClientBuilder httpClientBuilder = HttpClients.custom().useSystemProperties();
    String proxyHost = System.getProperty("http.proxyHost");
    String proxyPort = System.getProperty("http.proxyPort");
    String proxyHostS = System.getProperty("https.proxyHost");
    String proxyPortS = System.getProperty("https.proxyPort");
    if ((proxyHost == null || proxyPort == null) && (proxyHostS == null || proxyPortS == null)) {
        this.httpclient = HttpClientBuilder.create().setUserAgent(USER_AGENT).build();
    } else {
        HttpHost proxy = null;
        if (proxyHostS != null && proxyPortS != null) {
            proxy = new HttpHost(proxyHostS, Integer.parseInt(proxyPortS));
        } else {
            proxy = new HttpHost(proxyHost, Integer.parseInt(proxyPort));
        }
        httpClientBuilder.setProxy(proxy);
        HttpRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
        httpClientBuilder.setRoutePlanner(routePlanner).setSSLSocketFactory(sslSF);
        httpclient = httpClientBuilder.setUserAgent(USER_AGENT).build();
    }
}

From source file:at.spardat.xma.xdelta.test.JarDeltaJarPatcherTest.java

/**
 * Instantiates a new jar delta jar patcher test.
 *//*from   w  w w  . j  av a 2s  . c o  m*/
public JarDeltaJarPatcherTest() {
    try {
        random = SecureRandom.getInstance("SHA1PRNG");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        throw new RuntimeException(e.getMessage());
    }
}

From source file:com.tremolosecurity.saml.Saml2Assertion.java

public Saml2Assertion(String subject, PrivateKey key, X509Certificate cert, X509Certificate encCert,
        String issuer, String recepient, String audience, boolean signAssertion, boolean signResponse,
        boolean encAssertion, String nameIDFormat, String authnContextRef) {
    this.subject = subject;

    this.sigKey = key;
    this.sigCert = cert;
    this.encCert = encCert;

    long now = System.currentTimeMillis();

    this.notBefore = (new DateTime(now - (5 * 60 * 1000))).withZone(DateTimeZone.UTC);
    this.notAfter = (new DateTime(now + (5 * 60 * 1000))).withZone(DateTimeZone.UTC);
    this.attribs = new ArrayList<Attribute>();
    this.issueInstant = (new DateTime()).withZone(DateTimeZone.UTC);

    this.issuer = issuer;
    this.recepient = recepient;
    this.audience = audience;

    this.signAssertion = signAssertion;
    this.signResponse = signResponse;
    this.encAssertion = encAssertion;

    this.nameIDFormat = nameIDFormat;
    this.authnContextRef = authnContextRef;

    try {/*from   w w  w  . jav  a  2  s.  com*/
        this.random = SecureRandom.getInstance("SHA1PRNG");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }

}

From source file:com.piusvelte.hydra.ConnectionManager.java

String createToken() throws Exception {
    if (tokenFile != null) {
        String token = new BigInteger(256, new SecureRandom()).toString(16);
        MessageDigest md;//from   w  w  w.  j a va2  s. c  om
        try {
            md = MessageDigest.getInstance("SHA-256");
            md.update(token.getBytes("UTF-8"));
            token = new BigInteger(1, md.digest()).toString(16);
            if (token.length() > 64)
                token = token.substring(0, 64);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            throw new Exception("error generating token");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw new Exception("error generating token");
        }
        synchronized (tokenLock) {
            unauthorizedTokens.put(getHash64(token + passphrase), token);
            return token;
        }
    } else
        throw new Exception("no tokens available");
}

From source file:at.asitplus.regkassen.core.DemoCashBox.java

/**
 * encrypt the current turnover counter/* w  ww. ja  v  a2s.co m*/
 *
 * @param cashBoxIDUTF8String
 * @param receiptIdentifierUTF8String
 * @param rkSuite
 * @return
 */
protected String encryptTurnOverCounter(String cashBoxIDUTF8String, String receiptIdentifierUTF8String,
        RKSuite rkSuite) {
    try {
        //encrypt turnover counter and store the encrypted value in the data-to-be-signed package

        //prepare IV for encryption process, the Initialisation Vector (IV) is calculating by concatenating and then
        //hashing the
        //receipt-identifier (Belegnummer) and
        //the cashbox-ID (Kassen-ID)

        //Get UTF-8 String representation of cashBox-ID (Kassen-ID), STRING in Java are already UTF-8 encoded, thus no
        //encoding transformation is done here
        //IMPORTANT HINT: NEVER EVER use the same "Kassen-ID" and "Belegnummer" for different receipts!!!!
        String IVUTF8StringRepresentation = cashBoxIDUTF8String + receiptIdentifierUTF8String;

        ///hash the String with the hash-algorithm defined in the cashbox-algorithm-suite
        MessageDigest messageDigest = MessageDigest
                .getInstance(rkSuite.getHashAlgorithmForPreviousSignatureValue());
        byte[] hashValue = messageDigest.digest(IVUTF8StringRepresentation.getBytes());
        byte[] concatenatedHashValue = new byte[16];
        System.arraycopy(hashValue, 0, concatenatedHashValue, 0, 16);

        //encrypt the turnover counter using the AES key
        //Note: 3 AES encryption methods are provided for demonstration purposes,
        //which all use a different mode of operation (CTR, CFB, or ECB).
        //All three methods provided yield the same result. Still, they are provided here to
        //demonstrate the use of different modes of operation for encryption. This can be useful,
        //if AES functionality is re-implemented in another programming language that does
        //support selected AES modes of operation only. Please refer to
        //https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation for more details
        //on different modes of operation for block ciphers
        String base64EncryptedTurnOverValue1 = null;

        base64EncryptedTurnOverValue1 = CryptoUtil.encryptCTR(concatenatedHashValue, turnoverCounter,
                cashBoxParameters.getTurnOverCounterAESKey());

        String base64EncryptedTurnOverValue2 = CryptoUtil.encryptCFB(concatenatedHashValue, turnoverCounter,
                cashBoxParameters.getTurnOverCounterAESKey());
        String base64EncryptedTurnOverValue3 = CryptoUtil.encryptECB(concatenatedHashValue, turnoverCounter,
                cashBoxParameters.getTurnOverCounterAESKey());
        if (!base64EncryptedTurnOverValue1.equals(base64EncryptedTurnOverValue2)) {
            System.out.println("ENCRYPTION ERROR IN METHOD updateTurnOverCounter, MUST NOT HAPPEN");
            System.exit(-1);
        }
        if (!base64EncryptedTurnOverValue1.equals(base64EncryptedTurnOverValue3)) {
            System.out.println("ENCRYPTION ERROR IN METHOD updateTurnOverCounter, MUST NOT HAPPEN");
            System.exit(-1);
        }

        //THE FOLLOWING CODE IS ONLY FOR DEMONSTRATION PURPOSES
        //decryption and reconstruction of the turnover value
        //this is just here for demonstration purposes (so that the whole encryption/decryption process can be found in one place)
        //and not needed for that function
        //IV needs to be setup the same way as above
        //encryptedTurnOverValue needs to be reconstructed as described in the used utility method
        //Note: 3 AES decryption methods are provided for demonstration purposes,
        //which all use a different mode of operation (CTR, CFB, or ECB).
        //All three methods provided yield the same result. Still, they are provided here to
        //demonstrate the use of different modes of operation for decryption. This can be useful, if
        //AES functionality is re-implemented in another programming language that does
        //support selected AES modes of operation only. Please refer to
        //https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation for more details
        //on different modes of operation for block ciphers
        long testPlainOverTurnOverReconstructed1 = CryptoUtil.decryptCTR(concatenatedHashValue,
                base64EncryptedTurnOverValue1, cashBoxParameters.getTurnOverCounterAESKey());
        long testPlainOverTurnOverReconstructed2 = CryptoUtil.decryptCFB(concatenatedHashValue,
                base64EncryptedTurnOverValue2, cashBoxParameters.getTurnOverCounterAESKey());
        long testPlainOverTurnOverReconstructed3 = CryptoUtil.decryptECB(concatenatedHashValue,
                base64EncryptedTurnOverValue3, cashBoxParameters.getTurnOverCounterAESKey());
        if (testPlainOverTurnOverReconstructed1 != testPlainOverTurnOverReconstructed2) {
            System.out.println("DECRYPTION ERROR IN METHOD updateTurnOverCounter, MUST NOT HAPPEN");
            System.exit(-1);
        }

        if (testPlainOverTurnOverReconstructed1 != testPlainOverTurnOverReconstructed3) {
            System.out.println("DECRYPTION ERROR IN METHOD updateTurnOverCounter, MUST NOT HAPPEN");
            System.exit(-1);
        }

        if (turnoverCounter != testPlainOverTurnOverReconstructed1) {
            System.out.println("DECRYPTION ERROR IN METHOD updateTurnOverCounter, MUST NOT HAPPEN");
            System.exit(-1);
        }

        return base64EncryptedTurnOverValue1;
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (NoSuchProviderException e) {
        e.printStackTrace();
    } catch (NoSuchPaddingException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (InvalidAlgorithmParameterException e) {
        e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
        e.printStackTrace();
    } catch (BadPaddingException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.hichinaschool.flashcards.libanki.Utils.java

/**
 * SHA1 checksum.//  w  w w  .j a  v a2  s  .c  o m
 * Equivalent to python sha1.hexdigest()
 *
 * @param data the string to generate hash from
 * @return A string of length 40 containing the hexadecimal representation of the MD5 checksum of data.
 */
public static String checksum(String data) {
    String result = "";
    if (data != null) {
        MessageDigest md = null;
        byte[] digest = null;
        try {
            md = MessageDigest.getInstance("SHA1");
            digest = md.digest(data.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            Log.e(AnkiDroidApp.TAG, "Utils.checksum: No such algorithm. " + e.getMessage());
            throw new RuntimeException(e);
        } catch (UnsupportedEncodingException e) {
            Log.e(AnkiDroidApp.TAG, "Utils.checksum: " + e.getMessage());
            e.printStackTrace();
        }
        BigInteger biginteger = new BigInteger(1, digest);
        result = biginteger.toString(16);

        // pad with zeros to length of 40 This method used to pad
        // to the length of 32. As it turns out, sha1 has a digest
        // size of 160 bits, leading to a hex digest size of 40,
        // not 32.
        if (result.length() < 40) {
            String zeroes = "0000000000000000000000000000000000000000";
            result = zeroes.substring(0, zeroes.length() - result.length()) + result;
        }
    }
    return result;
}

From source file:com.vkassin.mtrade.Common.java

public static String getMd5(String txt) {
    StringBuffer result = new StringBuffer();
    try {//from w ww . j a  va  2s.  c  o  m
        MessageDigest m = MessageDigest.getInstance("MD5");
        m.reset();
        //         m.update(txt.getBytes(Charset.forName("UTF-8")));
        m.update(txt.getBytes());
        byte[] digest = m.digest();
        for (int i = 0; i < digest.length; i++)
            result.append(String.format("%02x", digest[i]));
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        Log.e(TAG, "Error in getMd5!!", e);
    }
    return result.toString();
}