Decrypt text using private key using RSA. - Android java.security

Android examples for java.security:RSA

Description

Decrypt text using private key using RSA.

Demo Code


//package com.java2s;

import java.security.PrivateKey;

import javax.crypto.Cipher;

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

    /**
     * Decrypt text using private key.
     *
     * @param text
     *          :encrypted text
     * @param key
     *          :The private key
     * @return plain text
     * @throws java.lang.Exception
     */
    public static String decrypt(byte[] text, PrivateKey key) {
        byte[] decryptedText = null;
        try {
            // get an RSA cipher object and print the provider
            final Cipher cipher = Cipher.getInstance(ALGORITHM
                    + "/ECB/PKCS1Padding");

            // decrypt the text using the private key
            cipher.init(Cipher.DECRYPT_MODE, key);
            decryptedText = cipher.doFinal(text);

        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return new String(decryptedText);
    }
}

Related Tutorials