Example usage for javax.crypto SecretKeyFactory generateSecret

List of usage examples for javax.crypto SecretKeyFactory generateSecret

Introduction

In this page you can find the example usage for javax.crypto SecretKeyFactory generateSecret.

Prototype

public final SecretKey generateSecret(KeySpec keySpec) throws InvalidKeySpecException 

Source Link

Document

Generates a SecretKey object from the provided key specification (key material).

Usage

From source file:gov.va.ds4p.ds4pmobileportal.ui.eHealthExchange.java

public String decryptDocument(byte[] processDocBytes, byte[] kekEncryptionKeyBytes, byte[] kekMaskingKeyBytes) {

    Document processedDoc = null;
    String processedDocString = "";
    DESedeKeySpec desedeEncryptKeySpec;
    DESedeKeySpec desedeMaskKeySpec;
    try {/*w ww  . ja  va 2  s  .  com*/

        org.apache.xml.security.Init.init();

        String processDocString = new String(processDocBytes);

        processedDoc = loadDocument(processDocString);

        desedeEncryptKeySpec = new DESedeKeySpec(kekEncryptionKeyBytes);
        SecretKeyFactory skfEncrypt = SecretKeyFactory.getInstance("DESede");
        SecretKey desedeEncryptKey = skfEncrypt.generateSecret(desedeEncryptKeySpec);

        desedeMaskKeySpec = new DESedeKeySpec(kekMaskingKeyBytes);
        SecretKeyFactory skfMask = SecretKeyFactory.getInstance("DESede");
        SecretKey desedeMaskKey = skfMask.generateSecret(desedeMaskKeySpec);

        /*************************************************
         * DECRYPT DOCUMENT
         *************************************************/
        Element encryptedDataElement = (Element) processedDoc.getElementsByTagNameNS(
                EncryptionConstants.EncryptionSpecNS, EncryptionConstants._TAG_ENCRYPTEDDATA).item(0);

        /*
         * The key to be used for decrypting xml data would be obtained from
         * the keyinfo of the EncrypteData using the kek.
         */
        XMLCipher xmlCipher = XMLCipher.getInstance();
        xmlCipher.init(XMLCipher.DECRYPT_MODE, null);
        xmlCipher.setKEK(desedeEncryptKey);

        /*
         * The following doFinal call replaces the encrypted data with
         * decrypted contents in the document.
         */
        if (encryptedDataElement != null)
            xmlCipher.doFinal(processedDoc, encryptedDataElement);

        /*************************************************
         * DECRYPT ELEMENTS
         *************************************************/
        NodeList encryptedDataElements = processedDoc.getElementsByTagNameNS(
                EncryptionConstants.EncryptionSpecNS, EncryptionConstants._TAG_ENCRYPTEDDATA);

        while (encryptedDataElements.getLength() > 0) {
            /*
             * The key to be used for decrypting xml data would be obtained
             * from the keyinfo of the EncrypteData using the kek.
             */
            XMLCipher xmlMaskCipher = XMLCipher.getInstance();
            xmlMaskCipher.init(XMLCipher.DECRYPT_MODE, null);
            xmlMaskCipher.setKEK(desedeMaskKey);

            xmlMaskCipher.doFinal(processedDoc, ((Element) encryptedDataElements.item(0)));

            encryptedDataElements = processedDoc.getElementsByTagNameNS(EncryptionConstants.EncryptionSpecNS,
                    EncryptionConstants._TAG_ENCRYPTEDDATA);
        }

        processedDocString = converXmlDocToString(processedDoc);

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return processedDocString;
}

From source file:dev.ukanth.ufirewall.Api.java

/**
 * Encrypt the password/*from   w  w w . j  av a  2  s .  c  om*/
 * @param key
 * @param data
 * @return
 */
public static String hideCrypt(String key, String data) {
    if (key == null || data == null)
        return null;
    String encodeStr = null;
    try {
        DESKeySpec desKeySpec = new DESKeySpec(key.getBytes(charsetName));
        SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(algorithm);
        SecretKey secretKey = secretKeyFactory.generateSecret(desKeySpec);
        byte[] dataBytes = data.getBytes(charsetName);
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        encodeStr = Base64.encodeToString(cipher.doFinal(dataBytes), base64Mode);

    } catch (Exception e) {
        Log.e(TAG, e.getLocalizedMessage());
    }
    return encodeStr;
}

From source file:dev.ukanth.ufirewall.Api.java

/**
 * Decrypt the password/*from ww w  .j  av a2  s  .c  om*/
 * @param key
 * @param data
 * @return
 */
public static String unhideCrypt(String key, String data) {
    if (key == null || data == null)
        return null;

    String decryptStr = null;
    try {
        byte[] dataBytes = Base64.decode(data, base64Mode);
        DESKeySpec desKeySpec = new DESKeySpec(key.getBytes(charsetName));
        SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(algorithm);
        SecretKey secretKey = secretKeyFactory.generateSecret(desKeySpec);
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] dataBytesDecrypted = (cipher.doFinal(dataBytes));
        decryptStr = new String(dataBytesDecrypted);
    } catch (Exception e) {
        Log.e(TAG, e.getLocalizedMessage());
    }
    return decryptStr;
}

From source file:com.grazerss.EntryManager.java

private static SecretKey getSecretKey() throws InvalidKeyException, UnsupportedEncodingException,
        NoSuchAlgorithmException, InvalidKeySpecException {
    DESKeySpec keySpec = new DESKeySpec("EntryManager.class".getBytes("UTF8"));
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
    SecretKey secretKey = keyFactory.generateSecret(keySpec);
    return secretKey;
}

From source file:com.filelocker.encryption.AES_Encryption.java

/**
 * If a file is being decrypted, we need to know the pasword, the salt and the initialization vector (iv).
 * We have the password from initializing the class. pass the iv and salt here which is
 * obtained when encrypting the file initially.
 *
 * @param inFile - The Encrypted File containing encrypted data , salt and InitVec
 * @throws NoSuchAlgorithmException/*from   w  w  w .ja v a2  s.  c o m*/
 * @throws InvalidKeySpecException
 * @throws NoSuchPaddingException
 * @throws InvalidKeyException
 * @throws InvalidAlgorithmParameterException
 * @throws DecoderException
 * @throws IOException
 */
public void setupDecrypt(File inFile)
        throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException,
        InvalidAlgorithmParameterException, DecoderException, IOException {
    SecretKeyFactory factory = null;
    SecretKey tmp = null;
    SecretKey secret = null;

    byte[] vSalt = new byte[8];
    byte[] vInitVec = new byte[16];

    RandomAccessFile vFile = new RandomAccessFile(inFile, "rw");

    //The last 8 bits are salt so seek to length of file minus 9 bits
    vFile.seek(vFile.length() - 8);
    vFile.readFully(vSalt);

    //The last 8 bits are salt and 16 bits before last 8 are Initialization Vectory so 8+16=24
    //Thus to seek to length of file minus 24 bits
    vFile.seek(vFile.length() - 24);
    vFile.readFully(vInitVec);
    vFile.seek(0);

    File tmpFile = new File(inFile.getAbsolutePath() + ".tmpEncryption.file");

    RandomAccessFile vTmpFile = new RandomAccessFile(tmpFile, "rw");

    for (int i = 0; i < (vFile.length() - 24); ++i) {
        vTmpFile.write(vFile.readByte());
    }
    vFile.close();
    vTmpFile.close();

    inFile.delete();
    tmpFile.renameTo(inFile);

    Db("got salt " + Hex.encodeHexString(vSalt));

    Db("got initvector :" + Hex.encodeHexString(vInitVec));

    /* Derive the key, given password and salt. */
    // in order to do 256 bit crypto, you have to muck with the files for Java's "unlimted security"
    // The end user must also install them (not compiled in) so beware.
    // see here:
    // http://www.javamex.com/tutorials/cryptography/unrestricted_policy_files.shtml
    // PBKDF2WithHmacSHA1,Constructs secret keys using the Password-Based Key Derivation Function function
    //found in PKCS #5 v2.0. (PKCS #5: Password-Based Cryptography Standard)

    factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    KeySpec spec = new PBEKeySpec(vPassword.toCharArray(), vSalt, ITERATIONS, KEYLEN_BITS);

    tmp = factory.generateSecret(spec);
    secret = new SecretKeySpec(tmp.getEncoded(), "AES");

    // Decrypt the message, given derived key and initialization vector.
    vDecipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    vDecipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(vInitVec));
}

From source file:com.flexoodb.common.FlexUtils.java

static public String encryptdes(String passkey, String texttoencrypt) throws Exception {
    Security.addProvider(new com.sun.crypto.provider.SunJCE());
    byte key[] = passkey.trim().getBytes();
    DESKeySpec desKeySpec = new DESKeySpec(key);
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
    SecretKey desKey = keyFactory.generateSecret(desKeySpec);

    Cipher desCipher;/*from  w  ww.  ja va 2 s. co m*/

    // Create the cipher
    desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");

    // Initialize the cipher for encryption
    desCipher.init(Cipher.ENCRYPT_MODE, desKey);

    // initialize base 64 encoding
    //org.apache.axis.encoding.Base64 base64 = new org.apache.axis.encoding.Base64();
    byte[] cleartext = texttoencrypt.getBytes();

    // Encrypt the cleartext
    byte[] ciphertext = desCipher.doFinal(cleartext);

    // encode to base64
    ciphertext = org.apache.axis.encoding.Base64.encode(ciphertext).getBytes();

    return new String(ciphertext);
}

From source file:com.flexoodb.common.FlexUtils.java

static public String decryptdes(String passkey, String texttoencrypt) throws Exception {
    Security.addProvider(new com.sun.crypto.provider.SunJCE());

    byte key[] = passkey.trim().getBytes();
    DESKeySpec desKeySpec = new DESKeySpec(key);
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
    SecretKey desKey = keyFactory.generateSecret(desKeySpec);

    Cipher desCipher;/*  w w  w  . j  a  va  2s  . c  o m*/

    // Create the cipher
    desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");

    // initialize base64 handler
    //org.apache.axis.encoding.Base64 base64 = new org.apache.axis.encoding.Base64();

    // decode from base64 first
    byte[] ciphertext = org.apache.axis.encoding.Base64.decode(new String(texttoencrypt.getBytes()));

    // Initialize the same cipher for decryption
    desCipher.init(Cipher.DECRYPT_MODE, desKey);

    // Decrypt the ciphertext
    byte[] cleartext1 = desCipher.doFinal(ciphertext);

    return new String(cleartext1);

}

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.
 *///from w w w . jav  a 2s . co 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));
    }
}