Decrypts a byte array encrypted with the user's public key by using their private key (RSA) - Android java.security

Android examples for java.security:RSA

Description

Decrypts a byte array encrypted with the user's public key by using their private key (RSA)

Demo Code


//package com.java2s;

import android.util.Log;
import java.security.InvalidKeyException;

import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

public class Main {
    /**//from  w w  w . ja  v  a 2s.com
     *  Decrypts a byte array encrypted with the user's public key by using their private key (RSA)
     *
     * @see java.security.PrivateKey
     * @param encBarr
     * @param privateKey
     * @return
     * @throws NoSuchAlgorithmException
     * @throws NoSuchPaddingException
     * @throws InvalidKeyException
     * @throws IllegalBlockSizeException
     * @throws NoSuchProviderException
     */
    public static byte[] RSADecryptByte(final byte[] encBarr,
            PrivateKey privateKey) throws NoSuchAlgorithmException,
            NoSuchPaddingException, InvalidKeyException,
            IllegalBlockSizeException, NoSuchProviderException {

        Cipher cipher1 = Cipher.getInstance("RSA/ECB/PKCS1Padding",
                "AndroidOpenSSL");
        cipher1.init(Cipher.DECRYPT_MODE, privateKey);

        byte[] decBarr = new byte[0];
        try {
            decBarr = cipher1.doFinal(encBarr);
        } catch (BadPaddingException e) {
            Log.i("myApp", "BadPadding");
            e.printStackTrace();
        }
        return decBarr;
    }
}

Related Tutorials