Encrypt the plain text using enc key using RSA. - Android java.security

Android examples for java.security:RSA

Description

Encrypt the plain text using enc key using RSA.

Demo Code


//package com.java2s;

import java.security.PublicKey;

import javax.crypto.Cipher;

public class Main {
    /**/*  w ww  .  ja v a  2s  .  c  om*/
     * String to hold name of the encryption algorithm.
     */
    public static final String ALGORITHM = "RSA";

    /**
     * Encrypt the plain text using enc key.
     *
     * @param text
     *          : original plain text
     * @param key
     *          :The enc key
     * @return Encrypted text
     * @throws java.lang.Exception
     */
    public static byte[] encrypt(String text, PublicKey key) {
        byte[] cipherText = null;
        try {
            // get an RSA cipher object and print the provider
            final Cipher cipher = Cipher.getInstance(ALGORITHM
                    + "/ECB/PKCS1Padding");
            // encrypt the plain text using the enc key
            cipher.init(Cipher.ENCRYPT_MODE, key);
            cipherText = cipher.doFinal(text.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return cipherText;
    }
}

Related Tutorials