encrypt By Public Key - Java Security

Java examples for Security:Key

Description

encrypt By Public Key

Demo Code


//package com.java2s;

import java.io.ByteArrayOutputStream;

import java.io.FileInputStream;

import java.security.KeyStore;

import java.security.PublicKey;

import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;

import javax.crypto.Cipher;

public class Main {

    public static final String KEY_STORE = "JKS";
    public static final String X509 = "X.509";

    private static final int MAX_ENCRYPT_BLOCK = 117;

    public static byte[] encryptByPublicKey(byte[] data,
            String certificatePath) throws Exception {

        PublicKey publicKey = getPublicKey(certificatePath);
        Cipher cipher = Cipher.getInstance(publicKey.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        int inputLen = data.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;

        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(data, offSet, inputLen - offSet);
            }//from   w w w .j a va 2  s  .  c  o m
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();
        return encryptedData;
    }

    private static PublicKey getPublicKey(String certificatePath)
            throws Exception {
        Certificate certificate = getCertificate(certificatePath);
        PublicKey publicKey = certificate.getPublicKey();
        return publicKey;
    }

    private static Certificate getCertificate(String certificatePath)
            throws Exception {
        CertificateFactory certificateFactory = CertificateFactory
                .getInstance(X509);
        FileInputStream in = new FileInputStream(certificatePath);
        Certificate certificate = certificateFactory
                .generateCertificate(in);
        in.close();
        return certificate;
    }

    private static Certificate getCertificate(String keyStorePath,
            String alias, String password) throws Exception {
        KeyStore keyStore = getKeyStore(keyStorePath, password);
        Certificate certificate = keyStore.getCertificate(alias);
        return certificate;
    }

    private static KeyStore getKeyStore(String keyStorePath, String password)
            throws Exception {
        FileInputStream in = new FileInputStream(keyStorePath);
        KeyStore keyStore = KeyStore.getInstance(KEY_STORE);
        keyStore.load(in, password.toCharArray());
        in.close();
        return keyStore;
    }
}

Related Tutorials