Java Code Examples for javax.crypto.Cipher#update()

The following examples show how to use javax.crypto.Cipher#update() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SameBuffer.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
private void runGCMWithSameArray(int mode, byte[] array, int txtOffset,
        int length, AlgorithmParameters params) throws Exception {
    // first, generate cipher text at an allocated buffer
    Cipher cipher = createCipher(mode, params);
    cipher.updateAAD(array, 0, AADLength);
    byte[] outputText = cipher.doFinal(array, txtOffset, length);

    // new cipher for encrypt operation
    Cipher anotherCipher = createCipher(mode, params);
    anotherCipher.updateAAD(array, 0, AADLength);

    // next, generate cipher text again at the same buffer of plain text
    int off = anotherCipher.update(array, txtOffset, length,
            array, txtOffset);
    anotherCipher.doFinal(array, txtOffset + off);

    // check if two results are equal or not
    if (!isEqual(array, txtOffset, outputText, 0,
            outputText.length)) {
        throw new RuntimeException(
                "Two results are not equal, mode:" + mode);
    }
}
 
Example 2
Source File: RSAManager.java    From apollo-DuerOS with Apache License 2.0 6 votes vote down vote up
/**
 *  encrypted by public key
 *
 * @param data
 * @param publicKey
 *
 * @return
 */
public String encrypt(String data, PublicKey publicKey) {
    byte[] rst = null;
    String rstStr = null;
    try {
        Cipher cipher = Cipher.getInstance(EncryptConfig.TRANSFORMATION_SETTING);
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        cipher.update(data.getBytes("UTF-8"));

        rst = cipher.doFinal();
        rstStr = Base64.encodeToString(rst, Base64.NO_WRAP);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return rstStr;
}
 
Example 3
Source File: Encrypt.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
private void combination_9(List<byte[]> results, int mode, byte[] AAD,
        byte[] plainText, AlgorithmParameters params) throws Exception {

    // prepare ByteBuffer to test
    ByteBuffer buf = ByteBuffer.allocate(AAD.length);
    buf.put(AAD);
    buf.position(0);
    buf.limit(AAD.length);

    // Get Cipher object and do the combination
    Cipher c = createCipher(mode, params);
    c.updateAAD(buf);
    byte[] part91 = c.update(plainText, 0, plainText.length);
    int part91_length = part91 == null ? 0 : part91.length;
    byte[] part92 = c.doFinal();
    byte[] outputText9 = new byte[part91_length + part92.length];

    // form result of the combination
    if (part91 != null) {
        System.arraycopy(part91, 0, outputText9, 0, part91_length);
    }
    System.arraycopy(part92, 0, outputText9, part91_length, part92.length);
    results.add(outputText9);
}
 
Example 4
Source File: CryptoApi.java    From mercury with Apache License 2.0 6 votes vote down vote up
public void aesDecrypt(InputStream encryptedIn, OutputStream clearOut, byte[] key) throws GeneralSecurityException, IOException {
    byte[] iv = new byte[IV_LENGTH];
    int len = encryptedIn.read(iv);
    if (len < IV_LENGTH) {
        throw new IOException(CORRUPTED_IV);
    }
    SecretKeySpec secret = new SecretKeySpec(key, AES);
    Cipher cipher = Cipher.getInstance(AES_PADDING);
    cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv));

    byte[] buffer = new byte[BUFFER_SIZE];
    while ((len = encryptedIn.read(buffer, 0, buffer.length)) != -1) {
        byte[] decrypted = cipher.update(buffer, 0, len);
        clearOut.write(decrypted);
    }
    byte[] finalBlk = cipher.doFinal();
    if (finalBlk.length > 0) {
        clearOut.write(finalBlk);
    }
}
 
Example 5
Source File: Encrypt.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
private void combination_12(List<byte[]> results, int mode, byte[] AAD,
        byte[] plainText, AlgorithmParameters params) throws Exception {

    // prepare ByteBuffer to test
    ByteBuffer buf = ByteBuffer.allocate(AAD.length);
    buf.put(AAD);
    buf.position(0);
    buf.limit(AAD.length);
    Cipher ci = createCipher(mode, params);
    ci.updateAAD(buf);

    // prepare an empty ByteBuffer
    ByteBuffer emptyBuf = ByteBuffer.allocate(0);
    emptyBuf.put(new byte[0]);
    ci.updateAAD(emptyBuf);
    byte[] part12_1 = new byte[ci.getOutputSize(plainText.length)];
    int offset = plainText.length > ARRAY_OFFSET ? ARRAY_OFFSET : 0;
    int len12 = ci.update(plainText, 0, plainText.length - offset,
            part12_1, 0);
    int rest12 = ci.doFinal(plainText, plainText.length - offset, offset,
            part12_1, len12);
    byte[] outputText12 = new byte[len12 + rest12];
    System.arraycopy(part12_1, 0, outputText12, 0, outputText12.length);
    results.add(outputText12);
}
 
Example 6
Source File: Encrypt.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
private void combination_12(List<byte[]> results, int mode, byte[] AAD,
        byte[] plainText, AlgorithmParameters params) throws Exception {

    // prepare ByteBuffer to test
    ByteBuffer buf = ByteBuffer.allocate(AAD.length);
    buf.put(AAD);
    buf.position(0);
    buf.limit(AAD.length);
    Cipher ci = createCipher(mode, params);
    ci.updateAAD(buf);

    // prepare an empty ByteBuffer
    ByteBuffer emptyBuf = ByteBuffer.allocate(0);
    emptyBuf.put(new byte[0]);
    ci.updateAAD(emptyBuf);
    byte[] part12_1 = new byte[ci.getOutputSize(plainText.length)];
    int offset = plainText.length > ARRAY_OFFSET ? ARRAY_OFFSET : 0;
    int len12 = ci.update(plainText, 0, plainText.length - offset,
            part12_1, 0);
    int rest12 = ci.doFinal(plainText, plainText.length - offset, offset,
            part12_1, len12);
    byte[] outputText12 = new byte[len12 + rest12];
    System.arraycopy(part12_1, 0, outputText12, 0, outputText12.length);
    results.add(outputText12);
}
 
Example 7
Source File: SameBuffer.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
private void runGCMWithSeparateArray(int mode, byte[] AAD, byte[] text,
        int txtOffset, int lenght, int offset, AlgorithmParameters params)
        throws Exception {
    // first, generate the cipher text at an allocated buffer
    Cipher cipher = createCipher(mode, params);
    cipher.updateAAD(AAD);
    byte[] outputText = cipher.doFinal(text, txtOffset, lenght);

    // new cipher for encrypt operation
    Cipher anotherCipher = createCipher(mode, params);
    anotherCipher.updateAAD(AAD);

    // next, generate cipher text again at the same buffer of plain text
    int myoff = offset;
    int off = anotherCipher.update(text, txtOffset, lenght, text, myoff);
    anotherCipher.doFinal(text, myoff + off);

    // check if two resutls are equal
    if (!isEqual(text, myoff, outputText, 0, outputText.length)) {
        throw new RuntimeException("Two results not equal, mode:" + mode);
    }
}
 
Example 8
Source File: Encrypt.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private void combination_7(List<byte[]> results, int mode, byte[] AAD,
        byte[] plainText, AlgorithmParameters params) throws Exception {
    Cipher ci = createCipher(mode, params);
    ci.updateAAD(AAD, 0, AAD.length);
    ci.updateAAD(AAD, AAD.length, 0);
    byte[] part71 = new byte[ci.getOutputSize(plainText.length)];
    int offset = plainText.length > ARRAY_OFFSET ? ARRAY_OFFSET : 0;
    int len = ci.update(plainText, 0, plainText.length - offset, part71, 0);
    byte[] part72 = ci.doFinal(plainText, plainText.length - offset, offset);
    byte[] outputText7 = new byte[len + part72.length];
    System.arraycopy(part71, 0, outputText7, 0, len);
    System.arraycopy(part72, 0, outputText7, len, part72.length);
    results.add(outputText7);
}
 
Example 9
Source File: Encrypt.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
private void combination_4(List<byte[]> results, int mode, byte[] AAD,
        byte[] plainText, AlgorithmParameters params) throws Exception {
    Cipher ci = createCipher(mode, params);
    ci.updateAAD(AAD);
    byte[] part41 = new byte[ci.getOutputSize(plainText.length)];
    int offset = plainText.length > ARRAY_OFFSET ? ARRAY_OFFSET : 0;
    int len = ci.update(plainText, 0, plainText.length - offset, part41, 0);
    int rest4 = ci.doFinal(plainText, plainText.length - offset, offset,
            part41, len);
    byte[] outputText4 = new byte[len + rest4];
    System.arraycopy(part41, 0, outputText4, 0, outputText4.length);
    results.add(outputText4);
}
 
Example 10
Source File: Encrypt.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private void combination_11(List<byte[]> results, int mode, byte[] AAD,
        byte[] plainText, AlgorithmParameters params) throws Exception {

    // prepare ByteBuffer1 to test
    ByteBuffer buf1 = ByteBuffer.allocate(AAD.length / 2);
    buf1.put(AAD, 0, AAD.length / 2);
    buf1.position(0);
    buf1.limit(AAD.length / 2);

    // get a Cipher object and do combination
    Cipher ci = createCipher(mode, params);

    // process the first half of AAD data
    ci.updateAAD(buf1);

    // prepare ByteBuffer2 to test
    ByteBuffer buf2 = ByteBuffer.allocate(AAD.length - AAD.length / 2);
    buf2.put(AAD, AAD.length / 2, AAD.length - AAD.length / 2);
    buf2.position(0);
    buf2.limit(AAD.length - AAD.length / 2);

    // process the rest of AAD data
    ci.updateAAD(buf2);

    // encrypt plain text
    byte[] part11_1 = new byte[ci.getOutputSize(plainText.length)];
    int offset = plainText.length > ARRAY_OFFSET ? ARRAY_OFFSET : 0;
    int len_11 = ci.update(plainText, 0, plainText.length - offset,
            part11_1, 0);
    byte[] part11_2 = ci.doFinal(plainText, plainText.length - offset,
            offset);
    byte[] outputText11 = new byte[len_11 + part11_2.length];
    System.arraycopy(part11_1, 0, outputText11, 0, len_11);
    System.arraycopy(part11_2, 0, outputText11, len_11, part11_2.length);
    results.add(outputText11);
}
 
Example 11
Source File: clientUtil.java    From fido2 with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static String decryptKeyHandle(String keyHandleWithIV) throws DecoderException, NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, ShortBufferException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException, InvalidKeySpecException, SignatureException {

        //get secure element key to decrypt
        byte[] Seckeybytes = Hex.decodeHex(CSConstants.SECURE_ELEMENT_SECRET_KEY.toCharArray());
        SecretKeySpec sks = new SecretKeySpec(Seckeybytes, "AES");

        byte[] receivedkeyHandle = DatatypeConverter.parseBase64Binary(keyHandleWithIV);

        //get IV
        byte[] receivedIV = new byte[16];
        System.arraycopy(receivedkeyHandle, 0, receivedIV, 0, 16);

        //unwrap the key handle
        //get the wrapped key handle bytes
        byte[] wrappedKeyHandleBytes = new byte[receivedkeyHandle.length - receivedIV.length];
        System.arraycopy(receivedkeyHandle, receivedIV.length, wrappedKeyHandleBytes, 0, wrappedKeyHandleBytes.length);

        //unwrapping received key handle
        //decrypt
        Cipher cipher1 = Cipher.getInstance("AES/CBC/PKCS7Padding", "BCFIPS");
        IvParameterSpec ivspec = new IvParameterSpec(receivedIV);
        cipher1.init(Cipher.DECRYPT_MODE, sks, ivspec);

        byte[] receivedunwrappedKeyHandle = new byte[cipher1.getOutputSize(wrappedKeyHandleBytes.length)];
        int p = cipher1.update(wrappedKeyHandleBytes, 0, wrappedKeyHandleBytes.length, receivedunwrappedKeyHandle, 0);
        cipher1.doFinal(receivedunwrappedKeyHandle, p);

        //put decrypted key in a BCPrivate key object //to test
        String privateKey = keyHandleDecode(new String(receivedunwrappedKeyHandle, "UTF-8"), 0); //0 for key
        byte[] prk = Base64.decodeBase64(privateKey);

        //get private key into BC understandable form -- test working
        ECPrivateKeySpec ecpks = new ECPrivateKeySpec(new BigInteger(prk), null);
        KeyFactory kf = KeyFactory.getInstance("ECDSA", "BCFIPS");
        PrivateKey privatetest = kf.generatePrivate(ecpks);

        return new String(receivedunwrappedKeyHandle, "UTF-8");

    }
 
Example 12
Source File: Encrypt.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private void combination_13(List<byte[]> results, int mode, byte[] AAD,
        byte[] plainText, AlgorithmParameters params) throws Exception {
    Cipher c = createCipher(mode, params);

    // prepare ByteBuffer to test
    ByteBuffer buf = ByteBuffer.allocateDirect(AAD.length);
    buf.put(AAD);
    buf.position(0);
    buf.limit(AAD.length);
    c.updateAAD(buf);

    // prepare buffers to encrypt/decrypt
    ByteBuffer in = ByteBuffer.allocateDirect(plainText.length);
    in.put(plainText);
    in.position(0);
    in.limit(plainText.length);
    ByteBuffer output = ByteBuffer.allocateDirect(
            c.getOutputSize(in.limit()));
    output.position(0);
    output.limit(c.getOutputSize(in.limit()));

    // process input text
    c.update(in, output);
    c.doFinal(in, output);
    int resultSize = output.position();
    byte[] result13 = new byte[resultSize];
    output.position(0);
    output.limit(resultSize);
    output.get(result13, 0, resultSize);
    results.add(result13);
}
 
Example 13
Source File: Encrypt.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
private void combination_3(List<byte[]> results, int mode, byte[] AAD,
        byte[] plainText, AlgorithmParameters params) throws Exception {
    Cipher ci = createCipher(mode, params);
    ci.updateAAD(AAD);
    byte[] part31 = new byte[ci.getOutputSize(plainText.length)];
    int offset = plainText.length > ARRAY_OFFSET ? ARRAY_OFFSET : 0;
    int len = ci.update(plainText, 0, plainText.length - offset, part31, 0);
    byte[] part32 = ci.doFinal(plainText, plainText.length - offset,
            offset);
    byte[] outputText3 = new byte[len + part32.length];
    System.arraycopy(part31, 0, outputText3, 0, len);
    System.arraycopy(part32, 0, outputText3, len, part32.length);
    results.add(outputText3);
}
 
Example 14
Source File: Encrypt.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
private void combination_14(List<byte[]> results, int mode, byte[] AAD,
        byte[] plainText, AlgorithmParameters params) throws Exception {
    Cipher c = createCipher(mode, params);
    // prepare ByteBuffer to test
    ByteBuffer buf = ByteBuffer.allocateDirect(AAD.length);
    buf.put(AAD);

    // process the first half of AAD data
    buf.position(0);
    buf.limit(AAD.length / 2);
    c.updateAAD(buf);

    // process the rest of AAD data
    buf.limit(AAD.length);
    c.updateAAD(buf);

    // prepare buffers to encrypt/decrypt
    ByteBuffer in = ByteBuffer.allocate(plainText.length);
    in.put(plainText);
    in.position(0);
    in.limit(plainText.length);
    ByteBuffer out = ByteBuffer.allocate(c.getOutputSize(in.limit()));
    out.position(0);
    out.limit(c.getOutputSize(in.limit()));

    // process input text
    c.update(in, out);
    c.doFinal(in, out);
    int resultSize = out.position();
    byte[] result14 = new byte[resultSize];
    out.position(0);
    out.limit(resultSize);
    out.get(result14, 0, resultSize);
    results.add(result14);
}
 
Example 15
Source File: Encrypt.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private void combination_3(List<byte[]> results, int mode, byte[] AAD,
        byte[] plainText, AlgorithmParameters params) throws Exception {
    Cipher ci = createCipher(mode, params);
    ci.updateAAD(AAD);
    byte[] part31 = new byte[ci.getOutputSize(plainText.length)];
    int offset = plainText.length > ARRAY_OFFSET ? ARRAY_OFFSET : 0;
    int len = ci.update(plainText, 0, plainText.length - offset, part31, 0);
    byte[] part32 = ci.doFinal(plainText, plainText.length - offset,
            offset);
    byte[] outputText3 = new byte[len + part32.length];
    System.arraycopy(part31, 0, outputText3, 0, len);
    System.arraycopy(part32, 0, outputText3, len, part32.length);
    results.add(outputText3);
}
 
Example 16
Source File: CipherHelper.java    From jdk8u-dev-jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Computes the DesCbc checksum based on the algorithm published in FIPS
 * Publication 113. This involves applying padding to the data passed
 * in, then performing DesCbc encryption on the data with a zero initial
 * vector, and finally returning the last 8 bytes of the encryption
 * result.
 *
 * @param key the bytes for the DES key
 * @param header a header to process first before the data is.
 * @param data the data to checksum
 * @param offset the offset where the data begins
 * @param len the length of the data
 * @throws GSSException when an error occuse in the encryption
 */
private byte[] getDesCbcChecksum(byte key[],
                                 byte[] header,
                                 byte[] data, int offset, int len)
    throws GSSException {

    Cipher des = getInitializedDes(true, key, ZERO_IV);

    int blockSize = des.getBlockSize();

    /*
     * Here the data need not be a multiple of the blocksize
     * (8). Encrypt and throw away results for all blocks except for
     * the very last block.
     */

    byte[] finalBlock = new byte[blockSize];

    int numBlocks = len / blockSize;
    int lastBytes = len % blockSize;
    if (lastBytes == 0) {
        // No need for padding. Save last block from application data
        numBlocks -= 1;
        System.arraycopy(data, offset + numBlocks*blockSize,
                         finalBlock, 0, blockSize);
    } else {
        System.arraycopy(data, offset + numBlocks*blockSize,
                         finalBlock, 0, lastBytes);
        // Zero padding automatically done
    }

    try {
        byte[] temp = new byte[Math.max(blockSize,
            (header == null? blockSize : header.length))];

        if (header != null) {
            // header will be null when doing DES-MD5 Checksum
            des.update(header, 0, header.length, temp, 0);
        }

        // Iterate over all but the last block
        for (int i = 0; i < numBlocks; i++) {
            des.update(data, offset, blockSize,
                       temp, 0);
            offset += blockSize;
        }

        // Now process the final block
        byte[] retVal = new byte[blockSize];
        des.update(finalBlock, 0, blockSize, retVal, 0);
        des.doFinal();

        return retVal;
    } catch (GeneralSecurityException e) {
        GSSException ge = new GSSException(GSSException.FAILURE, -1,
            "Could not use DES Cipher - " + e.getMessage());
        ge.initCause(e);
        throw ge;
    }
}
 
Example 17
Source File: DirectBBRemaining.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
private static void encrypt(Cipher cipher, int size,
        ByteBuffer heapIn, ByteBuffer heapOut,
        ByteBuffer directIn, ByteBuffer directOut,
        boolean output) throws Exception {

    ByteBuffer inBB = null;
    ByteBuffer outBB = null;

    // Set up data and encrypt to known/expected values.
    byte[] testdata = new byte[size];
    random.nextBytes(testdata);
    byte[] expected = cipher.doFinal(testdata);

    for (TestVariant tv : TestVariant.values()) {
        if (output) {
            System.out.print(" " + tv);
        }

        switch (tv) {
        case HEAP_HEAP:
            inBB = heapIn;
            outBB = heapOut;
            break;
        case HEAP_DIRECT:
            inBB = heapIn;
            outBB = directOut;
            break;
        case DIRECT_HEAP:
            inBB = directIn;
            outBB = heapOut;
            break;
        case DIRECT_DIRECT:
            inBB = directIn;
            outBB = directOut;
            break;
        }

        inBB.clear();
        outBB.clear();

        inBB.put(testdata);
        inBB.flip();

        // Process all data in one shot, but don't call doFinal() yet.
        // May store up to n-1 bytes (w/block size n) internally.
        cipher.update(inBB, outBB);
        if (inBB.hasRemaining()) {
            throw new Exception("buffer not empty");
        }

        // finish encryption and process all data buffered
        cipher.doFinal(inBB, outBB);
        outBB.flip();

        // validate output size
        if (outBB.remaining() != expected.length) {
            throw new Exception(
                    "incomplete encryption output, expected "
                    + expected.length + " bytes but was only "
                    + outBB.remaining() + " bytes");
        }

        // validate output data
        byte[] encrypted = new byte[outBB.remaining()];
        outBB.get(encrypted);
        if (!Arrays.equals(expected, encrypted)) {
            throw new Exception("bad encryption output");
        }

        if (!Arrays.equals(cipher.doFinal(), cipher.doFinal())) {
            throw new Exception("Internal buffers still held data!");
        }
    }
}
 
Example 18
Source File: CipherHelper.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Computes the DesCbc checksum based on the algorithm published in FIPS
 * Publication 113. This involves applying padding to the data passed
 * in, then performing DesCbc encryption on the data with a zero initial
 * vector, and finally returning the last 8 bytes of the encryption
 * result.
 *
 * @param key the bytes for the DES key
 * @param header a header to process first before the data is.
 * @param data the data to checksum
 * @param offset the offset where the data begins
 * @param len the length of the data
 * @throws GSSException when an error occuse in the encryption
 */
private byte[] getDesCbcChecksum(byte key[],
                                 byte[] header,
                                 byte[] data, int offset, int len)
    throws GSSException {

    Cipher des = getInitializedDes(true, key, ZERO_IV);

    int blockSize = des.getBlockSize();

    /*
     * Here the data need not be a multiple of the blocksize
     * (8). Encrypt and throw away results for all blocks except for
     * the very last block.
     */

    byte[] finalBlock = new byte[blockSize];

    int numBlocks = len / blockSize;
    int lastBytes = len % blockSize;
    if (lastBytes == 0) {
        // No need for padding. Save last block from application data
        numBlocks -= 1;
        System.arraycopy(data, offset + numBlocks*blockSize,
                         finalBlock, 0, blockSize);
    } else {
        System.arraycopy(data, offset + numBlocks*blockSize,
                         finalBlock, 0, lastBytes);
        // Zero padding automatically done
    }

    try {
        byte[] temp = new byte[Math.max(blockSize,
            (header == null? blockSize : header.length))];

        if (header != null) {
            // header will be null when doing DES-MD5 Checksum
            des.update(header, 0, header.length, temp, 0);
        }

        // Iterate over all but the last block
        for (int i = 0; i < numBlocks; i++) {
            des.update(data, offset, blockSize,
                       temp, 0);
            offset += blockSize;
        }

        // Now process the final block
        byte[] retVal = new byte[blockSize];
        des.update(finalBlock, 0, blockSize, retVal, 0);
        des.doFinal();

        return retVal;
    } catch (GeneralSecurityException e) {
        GSSException ge = new GSSException(GSSException.FAILURE, -1,
            "Could not use DES Cipher - " + e.getMessage());
        ge.initCause(e);
        throw ge;
    }
}
 
Example 19
Source File: CipherHelper.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Computes the DesCbc checksum based on the algorithm published in FIPS
 * Publication 113. This involves applying padding to the data passed
 * in, then performing DesCbc encryption on the data with a zero initial
 * vector, and finally returning the last 8 bytes of the encryption
 * result.
 *
 * @param key the bytes for the DES key
 * @param header a header to process first before the data is.
 * @param data the data to checksum
 * @param offset the offset where the data begins
 * @param len the length of the data
 * @throws GSSException when an error occuse in the encryption
 */
private byte[] getDesCbcChecksum(byte key[],
                                 byte[] header,
                                 byte[] data, int offset, int len)
    throws GSSException {

    Cipher des = getInitializedDes(true, key, ZERO_IV);

    int blockSize = des.getBlockSize();

    /*
     * Here the data need not be a multiple of the blocksize
     * (8). Encrypt and throw away results for all blocks except for
     * the very last block.
     */

    byte[] finalBlock = new byte[blockSize];

    int numBlocks = len / blockSize;
    int lastBytes = len % blockSize;
    if (lastBytes == 0) {
        // No need for padding. Save last block from application data
        numBlocks -= 1;
        System.arraycopy(data, offset + numBlocks*blockSize,
                         finalBlock, 0, blockSize);
    } else {
        System.arraycopy(data, offset + numBlocks*blockSize,
                         finalBlock, 0, lastBytes);
        // Zero padding automatically done
    }

    try {
        byte[] temp = new byte[Math.max(blockSize,
            (header == null? blockSize : header.length))];

        if (header != null) {
            // header will be null when doing DES-MD5 Checksum
            des.update(header, 0, header.length, temp, 0);
        }

        // Iterate over all but the last block
        for (int i = 0; i < numBlocks; i++) {
            des.update(data, offset, blockSize,
                       temp, 0);
            offset += blockSize;
        }

        // Now process the final block
        byte[] retVal = new byte[blockSize];
        des.update(finalBlock, 0, blockSize, retVal, 0);
        des.doFinal();

        return retVal;
    } catch (GeneralSecurityException e) {
        GSSException ge = new GSSException(GSSException.FAILURE, -1,
            "Could not use DES Cipher - " + e.getMessage());
        ge.initCause(e);
        throw ge;
    }
}
 
Example 20
Source File: SQRLStorage.java    From secure-quick-reliable-login with MIT License 4 votes vote down vote up
private byte[] decryptIdentityKeyQuickPass(String password) {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
    String quickPassStringData = sharedPreferences.getString("quickpass", null);
    if(quickPassStringData == null) return null;

    byte[] quickPassData = EncryptionUtils.hex2Byte(quickPassStringData);
    int quickPassIterationCount = getIntFromFourBytes(quickPassData, 0);
    byte[] quickPassRandomSalt = Arrays.copyOfRange(quickPassData, 4, 20);
    byte[] quickPassInitializationVector = Arrays.copyOfRange(quickPassData, 20, 32);
    byte[] quickPassKeyEncrypted = Arrays.copyOfRange(quickPassData, 32, 64);
    byte[] quickPassVerificationTag = Arrays.copyOfRange(quickPassData, 64, 80);

    this.progressionUpdater.setState(R.string.progress_state_descrypting_identity);
    this.progressionUpdater.setMax(quickPassIterationCount);

    password = password.substring(0, this.getHintLength());

    byte[] quickPassKey = null;

    try {
        byte[] key = EncryptionUtils.enSCryptIterations(password, quickPassRandomSalt, logNFactor, 32, quickPassIterationCount, this.progressionUpdater);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            Key keySpec = new SecretKeySpec(key, "AES");
            Cipher cipher = Cipher.getInstance("AES_256/GCM/NoPadding");
            GCMParameterSpec params = new GCMParameterSpec(128, quickPassInitializationVector);
            cipher.init(Cipher.DECRYPT_MODE, keySpec, params);
            cipher.update(quickPassKeyEncrypted);
            try {
                quickPassKey = cipher.doFinal(quickPassVerificationTag);
            } catch (AEADBadTagException badTag) {
                return quickPassKey;
            }
        } else {
            byte[] emptyPlainText = new byte[0];
            quickPassKey = new byte[32];

            Grc_aesgcm.gcm_setkey(key, key.length);
            int res = Grc_aesgcm.gcm_auth_decrypt(
                    quickPassInitializationVector, quickPassInitializationVector.length,
                    emptyPlainText, emptyPlainText.length,
                    quickPassKeyEncrypted, quickPassKey, quickPassKeyEncrypted.length,
                    quickPassVerificationTag, quickPassVerificationTag.length
            );
            Grc_aesgcm.gcm_zero_ctx();

            if (res == 0x55555555) return quickPassKey;
        }
    } catch (Exception e) {
        Log.e(SQRLStorage.TAG, e.getMessage(), e);
        return quickPassKey;
    }
    return quickPassKey;
}