Month: March 2016

ME-Mydoc 3.7 Released!

ME-Mydoc 3.7 has several attractive features.

Import Code from a directory
import code 1

import code 2

import code 3

Enhanced full text search and Chinese now supported
mydoc-highlighter

Note preview in main window
mydoc-note-preview

Recently visited items
mydoc-menu-history

Read desire, rate and series for Ebook and custom search
mydoc-book-search-custom

Fast search in tag view component
mydoc-tag-search

Auto filling certain fields when adding an Ebook by clipboard content detection
mydoc-book-new-menu

Java RSA encrypt and decrypt using generated key pair

The code demo generates RSA key pair and persists it to local file using Java specific object serialization format. The demo then restores private/public key objects by de-serializing from files it just created. Further, the public key is used to encrypt a clear text and the private key to decrypt.

import java.io.FileInputStream;
import java.io.FileOutputStream;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import sun.security.tools.keytool.CertAndKeyGen;

/**
 * RSA encryption/decryption util.
 *
 */
public class RSAUtil {

    private RSAPublicKey pubkey;
    private RSAPrivateKey prikey;

    public RSAUtil(RSAPrivateKey prikey, RSAPublicKey pubkey) {
        this.prikey = prikey;
        this.pubkey = pubkey;
    }

    public byte[] encrypt(byte[] bytes) throws BadPaddingException, IllegalBlockSizeException,
            InvalidKeyException, NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, pubkey);
        return cipher.doFinal(bytes);
    }

    public byte[] decrypt(byte[] bytes) throws NoSuchPaddingException, NoSuchAlgorithmException,
            InvalidKeyException, BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, prikey);
        return cipher.doFinal(bytes);
    }

    public static RSAUtil loadKeys(String privateKeyFile, String publicKeyFile) throws Exception {
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(privateKeyFile));
        RSAPrivateKey privateKey = (RSAPrivateKey) ois.readObject();

        ois = new ObjectInputStream(new FileInputStream(publicKeyFile));
        RSAPublicKey publicKey = (RSAPublicKey) ois.readObject();
        return new RSAUtil(privateKey, publicKey);
    }

    public static void genRSAKeyPair(String privateKeyFile, String publicKeyFile) {
        try {
            CertAndKeyGen keyPair = new CertAndKeyGen("RSA", "SHA1WithRSA", null);

            keyPair.generate(1024);
            RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivateKey();

            RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublicKey();

            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(privateKeyFile));
            oos.writeObject(privateKey);
            oos.flush();
            oos.close();

            oos = new ObjectOutputStream(new FileOutputStream(publicKeyFile));
            oos.writeObject(publicKey);
            oos.flush();
            oos.close();

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
        String clearText = "this is the text";
        genRSAKeyPair("privatekey", "publickey");
        RSAUtil rsaUtil = loadKeys("privatekey", "publickey");
        byte[] encryptedBytes = rsaUtil.encrypt(clearText.getBytes(StandardCharsets.UTF_8));
        String decryptedText = new String(rsaUtil.decrypt(encryptedBytes), StandardCharsets.UTF_8);
        System.out.println(decryptedText.equals(clearText));
    }
}

Java symmetric encryption decryption demo

In symmetric cryptograph, there are padding mode and blocking cipher that have restrictions on input byte length. SymmetricCryptoUtil in this demo adopts AES/CFB8/NoPadding mode that accepts any input without byte length restriction. In the Java main method, a string is first encrypted as byte array and then decrypted to string again without any loss.

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * Symmetric key encryption/decryption util.
 *
 */
public class SymmetricCryptoUtil {

    private String secretKey = "18345678800knarf";
    private String iv = "S23r87I090qYer9z";
    private static final String CIPHER_MODE = "AES/CFB8/NoPadding";

    private SecretKey keySpec;
    private IvParameterSpec ivSpec;

    public SymmetricCryptoUtil() {
        try {
            keySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "AES");
            ivSpec = new IvParameterSpec(iv.getBytes(StandardCharsets.UTF_8));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public byte[] encrypt(byte[] bytes) throws BadPaddingException, IllegalBlockSizeException,
            InvalidKeyException, NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException {
        Cipher cipher = Cipher.getInstance(CIPHER_MODE);
        cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
        return cipher.doFinal(bytes);
    }

    public byte[] decrypt(byte[] bytes) throws NoSuchPaddingException, NoSuchAlgorithmException,
            InvalidKeyException, BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException {
        Cipher cipher = Cipher.getInstance(CIPHER_MODE);
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
        return cipher.doFinal(bytes);
    }

    public static void main(String[] args) throws Exception {
        String clearText = "this is the text";
        SymmetricCryptoUtil cryptoUtil = new SymmetricCryptoUtil();
        byte[] encryptedBytes = cryptoUtil.encrypt(clearText.getBytes(StandardCharsets.UTF_8));
        String decryptedText = new String(cryptoUtil.decrypt(encryptedBytes), StandardCharsets.UTF_8);
        System.out.println(decryptedText.equals(clearText));
    }
}

Powered by WordPress & Theme by Anders Norén