Decrypt piece of data - Android java.security

Android examples for java.security:Decrypt Encrypt

Description

Decrypt piece of data

Demo Code


//package com.java2s;

import android.util.Base64;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;

public class Main {
    private static final String ENCODING = "UTF-8";

    /**/*from   www.  ja  v  a 2s  . c  om*/
     * Decrypt piece of data
     *
     * @param decryptCipher an instance of {@link javax.crypto.Cipher} initialized for decryption
     * @param encryptedBytes an encrypted piece of data to decrypt
     * @return a decrypted data
     * @throws IOException
     */
    public static byte[] decrypt(Cipher decryptCipher, byte[] encryptedBytes)
            throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ByteArrayInputStream inStream = new ByteArrayInputStream(
                encryptedBytes);
        CipherInputStream cipherInputStream = new CipherInputStream(
                inStream, decryptCipher);
        byte[] buf = new byte[1024];
        int bytesRead;
        while ((bytesRead = cipherInputStream.read(buf)) >= 0) {
            outputStream.write(buf, 0, bytesRead);
        }
        return outputStream.toByteArray();
    }

    /**
     * Decrypt piece of text data. Encrypted data is represented with a Base64 encoded string here.
     *
     * @param decryptCipher an instance of {@link javax.crypto.Cipher} initialized for decryption
     * @param encryptedStringBase64 encrypted data represented with a Base64 encoded string
     * @return decrypted string. It is implied here that original unencrypted data is a text string
     * @throws IOException
     */
    public static String decrypt(Cipher decryptCipher,
            String encryptedStringBase64) throws IOException {
        if (encryptedStringBase64 == null
                || encryptedStringBase64.length() == 0) {
            return null;
        }

        byte[] encryptedData = Base64.decode(encryptedStringBase64,
                Base64.DEFAULT);
        return new String(decrypt(decryptCipher, encryptedData), ENCODING);
    }
}

Related Tutorials