encrypt Asymmetric - Android java.security

Android examples for java.security:Decrypt Encrypt

Description

encrypt Asymmetric

Demo Code


//package com.java2s;

import java.io.UnsupportedEncodingException;

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[] encryptAsymmetric(String message,
            boolean encryptWithPrivateKey, Key key) {

        try {//from   w  w w  .java 2s  .  c  o m

            PrivateKey priv = null;
            PublicKey pub = null;
            // TODO: Check if PKCS7 and CBC is available
            Cipher cip = Cipher.getInstance("RSA/None/PKCS1Padding");
            if (!encryptWithPrivateKey) {
                pub = (PublicKey) key;
                cip.init(Cipher.ENCRYPT_MODE, pub);
            } else {
                priv = (PrivateKey) key;
                cip.init(Cipher.ENCRYPT_MODE, priv);
            }

            byte[] input = message.getBytes("UTF-8");

            byte[] encrypted = cip.doFinal(input);
            return encrypted;

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

        return null;
    }
}

Related Tutorials