decrypt String by RSA - Java Security

Java examples for Security:RSA

Description

decrypt String by RSA

Demo Code


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Security;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;

public class Main{
    public static String decrypt(String content, String key) {
        ByteArrayOutputStream bout = null;
        String decryptData = null;

        try {/*from  w ww.j  a va2  s.  c  o  m*/
            PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(
                    Base64.decode(key));
            KeyFactory keyf = KeyFactory.getInstance("RSA");
            PrivateKey privateKey = keyf.generatePrivate(priPKCS8);
            Cipher cipher = Cipher
                    .getInstance("RSA/ECB/PKCS1Padding", "BC");
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            byte plaintext[] = Base64.decode(content);
            final int blockSize = cipher.getBlockSize();
            bout = new ByteArrayOutputStream();

            for (int i = 0; i < plaintext.length; i += blockSize) {
                bout.write(cipher.doFinal(plaintext, i, plaintext.length
                        - i < blockSize ? plaintext.length - i : blockSize));
            }
            decryptData = new String(bout.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bout != null) {
                try {
                    bout.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                bout = null;
            }
        }

        return decryptData;
    }
}

Related Tutorials