decrypt File By Public Key - Java Security

Java examples for Security:Key

Description

decrypt File By Public Key

Demo Code


//package com.java2s;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import java.io.OutputStream;

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_DECRYPT_BLOCK = 128;

    public static void decryptFileByPublicKey(String srcFilePath,
            String destFilePath, String certificatePath) throws Exception {
        PublicKey publicKey = getPublicKey(certificatePath);
        Cipher cipher = Cipher.getInstance(publicKey.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, publicKey);
        File srcFile = new File(srcFilePath);
        FileInputStream in = new FileInputStream(srcFile);
        File destFile = new File(destFilePath);
        if (!destFile.getParentFile().exists()) {
            destFile.getParentFile().mkdirs();
        }// ww w.  j a  va  2s .c om
        destFile.createNewFile();
        OutputStream out = new FileOutputStream(destFile);
        byte[] data = new byte[MAX_DECRYPT_BLOCK];
        byte[] decryptedData; // ?
        while (in.read(data) != -1) {
            decryptedData = cipher.doFinal(data);
            out.write(decryptedData, 0, decryptedData.length);
            out.flush();
        }
        out.close();
        in.close();
    }

    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