Encrypts the message the user wants to send thanks to the RSA algorithm with the recipients' 4096bits public key - Android java.security

Android examples for java.security:RSA

Description

Encrypts the message the user wants to send thanks to the RSA algorithm with the recipients' 4096bits public key

Demo Code


//package com.java2s;
import android.util.Base64;

import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

public class Main {
    /**/*from   w w  w .  ja va2 s . c om*/
     * Encrypts the message the user wants to send thanks to the RSA algorithm with the recipients' 4096bits public key
     * @see java.security.interfaces.RSAPublicKey
     * @param plain
     * @param publicKeyString
     * @return
     * @throws NoSuchAlgorithmException
     * @throws NoSuchPaddingException
     * @throws InvalidKeyException
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     * @throws NoSuchProviderException
     * @throws InvalidKeySpecException
     */
    public static byte[] RSAEncrypt(final String plain,
            String publicKeyString) throws NoSuchAlgorithmException,
            NoSuchPaddingException, InvalidKeyException,
            IllegalBlockSizeException, BadPaddingException,
            NoSuchProviderException, InvalidKeySpecException {

        X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(
                Base64.decode(publicKeyString, Base64.DEFAULT));

        KeyFactory keyFactory = KeyFactory.getInstance("RSA");

        PublicKey publicKey = keyFactory.generatePublic(pubKeySpec);

        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);

        return cipher.doFinal(plain.getBytes());
    }
}

Related Tutorials