Encrypt the data with the RSA public key. - Java Security

Java examples for Security:RSA

Description

Encrypt the data with the RSA public key.

Demo Code


import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;
import java.security.SignatureException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

public class Main{
    /**// w  w  w . j  a  v a  2s. co  m
     * Key algorithm to be used in this class.
     */
    public static final String KEY_ALGORITHM = "RSA";
    /**
     * Encrypt the data with the public key.
     *
     * @param data           data to be encrypted.
     * @param offset         offset of data to be encrypted.
     * @param length         length of data to be encrypted.
     * @param publicKeyBytes public key in binary format.
     * @return encrypted data.
     */
    public static byte[] encryptWithPublicKey(byte[] data, int offset,
            int length, byte[] publicKeyBytes) {

        byte[] encryptedData = null;

        try {
            //Create a new X509EncodedKeySpec with the given encoded key.
            X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(
                    publicKeyBytes);

            //RSA key factory.
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);

            //Get the public key from the provided key specification.
            PublicKey publicKey = keyFactory
                    .generatePublic(x509EncodedKeySpec);

            //Init the ciper.
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());

            //Encrypt mode!
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);

            //Do the encryption now !!!!
            encryptedData = cipher.doFinal(data, offset, length);

        } catch (NoSuchAlgorithmException | InvalidKeySpecException
                | NoSuchPaddingException | InvalidKeyException
                | IllegalBlockSizeException | BadPaddingException ex) {
            Logger.getLogger(RSAHelper.class.getName()).log(Level.SEVERE,
                    null, ex);
        }

        return encryptedData;
    }
}

Related Tutorials