decrypt Asymmetric - Android java.security

Android examples for java.security:Decrypt Encrypt

Description

decrypt Asymmetric

Demo Code


//package com.java2s;

import java.security.InvalidKeyException;
import java.security.Key;

import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;

import javax.crypto.IllegalBlockSizeException;

import javax.crypto.NoSuchPaddingException;

public class Main {
    public static byte[] decryptAsymmetric(byte[] encrypted,
            boolean decryptWithPublicKey, Key key) {
        try {//from  w  w  w.j a v a  2  s . co m
            PrivateKey priv = null;
            PublicKey pub = null;

            Cipher cip = Cipher.getInstance("RSA/None/PKCS1Padding");

            if (decryptWithPublicKey) {
                pub = (PublicKey) key;
                cip.init(Cipher.DECRYPT_MODE, pub);
            } else {
                priv = (PrivateKey) key;
                cip.init(Cipher.DECRYPT_MODE, priv);
            }

            byte[] decrypted = cip.doFinal();
            return decrypted;

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }

        return null;
    }
}

Related Tutorials