Example usage for javax.crypto.spec PBEKeySpec PBEKeySpec

List of usage examples for javax.crypto.spec PBEKeySpec PBEKeySpec

Introduction

In this page you can find the example usage for javax.crypto.spec PBEKeySpec PBEKeySpec.

Prototype

public PBEKeySpec(char[] password) 

Source Link

Document

Constructor that takes a password.

Usage

From source file:com.slamd.admin.AdminServlet.java

/**
 * Generates page content based on an MD5-digest of the query string.
 *
 * @param  requestInfo   The state information for this request.
 * @param  digestString  The base64-encoded MD5 digest of the query string to
 *                       use to generate the page.
 *//* w  w w .  j av  a 2 s  .  c o m*/
static void generatePageFromMD5(RequestInfo requestInfo, String digestString) {
    try {
        String dataFile = Constants.MD5_CONTENT_BASE_PATH + '/' + digestString;
        InputStream inputStream = slamdServer.getClass().getClassLoader().getResourceAsStream(dataFile);

        byte[] salt = { 0, 0, 0, 0, 0, 0, 0, 0 };
        char[] queryChars = requestInfo.request.getQueryString().toCharArray();
        int iterations = 1000;
        String cipherName = "PBEWithMD5AndDES";
        StringBuilder htmlBody = requestInfo.htmlBody;

        AlgorithmParameters algorithmParams = AlgorithmParameters.getInstance(cipherName);
        algorithmParams.init(new PBEParameterSpec(salt, iterations));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(cipherName);
        SecretKey key = keyFactory.generateSecret(new PBEKeySpec(queryChars));
        Cipher cipher = Cipher.getInstance(cipherName);
        cipher.init(Cipher.DECRYPT_MODE, key, algorithmParams);

        int bytesIn;
        int bytesOut;
        byte[] inBuffer = new byte[4096];
        byte[] outBuffer = new byte[8192];
        while ((bytesIn = inputStream.read(inBuffer)) > 0) {
            bytesOut = cipher.update(inBuffer, 0, bytesIn, outBuffer);
            htmlBody.append(new String(outBuffer, 0, bytesOut));
        }

        htmlBody.append(new String(cipher.doFinal()));
        inputStream.close();
    } catch (Exception e) {
        requestInfo.htmlBody.append(JobClass.stackTraceToString(e));
    }
}