According publickey algorithm to do encode for data. - Java Security

Java examples for Security:Key

Description

According publickey algorithm to do encode for data.

Demo Code


//package com.java2s;
import java.security.PublicKey;

import javax.crypto.Cipher;
import sun.misc.BASE64Encoder;

public class Main {
    /**//from  w  ww.j  a  va 2  s. c o  m
     * According publickey algorithm to do encode for data.
     * @param data
     * @param publicKey
     * @return
     * @throws Exception
     */
    public static String encryptByPublicKey(byte[] data, PublicKey publicKey)
            throws Exception {
        Cipher cipher = Cipher.getInstance(publicKey.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] encryptedData = cipher.doFinal(data);
        return new BASE64Encoder().encode(encryptedData);
    }
}

Related Tutorials