maandag 21 maart 2011

[Java] Encryption and Decryption with JCE

First of all, this is not a tutorial written by me, Qkyrie. It was in fact written by Deque on HF.net. I found this being a useful post and thought I'd present it to a public that doesn't want to create accounts on Hackforums.net :)


This code shows you how to use parts of the Java Cryptography Extension (JCE) to encrypt and decrypt messages.

The program takes three arguments that specify the algorithm for key generation (the first), message transformation (the second) and the key size (the third). The key is generated. If no argument is given it uses AES AES 128 as default. 


Code:
import java.security.InvalidKeyException;
import java.security.InvalidParameterException;
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import java.security.Security;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class EnDecryption {

    private final Cipher cipher;
    private final SecretKeySpec spec;

    public static void main(String[] args) throws Exception {

        printAvailableServices("Cipher");
        printAvailableServices("KeyGenerator");

        String keyAlgorithm = args.length <= 0 ? "AES" : args[0];
        String transformation = args.length <= 1 ? "AES" : args[1];

        try {
            int keysize = Integer.parseInt(args.length <= 2 ? "128" : args[2]);
            System.out.println("Program instantiated with " + keyAlgorithm
                    + " as key generating algorithm, " + transformation
                    + " as transformation algorithm and " + keysize
                    + " as key size.\n");

            Scanner scanner = new Scanner(System.in);
            System.out.println("Your message: ");
            String message = scanner.nextLine();

            EnDecryption d = new EnDecryption(keysize, keyAlgorithm,
                    transformation);

            byte[] encryptedMsg = d.encrypt(message);
            byte[] decryptedMsg = d.decrypt(encryptedMsg);

            System.out.println("\nencrypted message: "
                    + convertToHex(encryptedMsg));
            System.out.println("decrypted message as Hex: "
                    + convertToHex(decryptedMsg));
            System.out.println("decrypted message as String: "
                    + new String(decryptedMsg));

        } catch (NoSuchAlgorithmException e) {
            System.err.println("wrong algorithm input\n" + e.getMessage());
        } catch (NoSuchPaddingException e) {
            System.err.println("wrong padding input\n" + e.getMessage());
        } catch (NumberFormatException e) {
            System.err.println("third argument for key size is not a number\n"
                    + e.getMessage());
        } catch (InvalidParameterException e) {
            System.err.println(e.getMessage());
        } catch (InvalidKeyException e) {
            System.err.println(e.getMessage());
        }
    }

    public EnDecryption(int keysize, String algorithm, String transformation)
            throws NoSuchAlgorithmException, NoSuchPaddingException {
        KeyGenerator keygen = KeyGenerator.getInstance(algorithm);
        keygen.init(keysize);
        SecretKey skey = keygen.generateKey();

        spec = new SecretKeySpec(skey.getEncoded(), algorithm);

        cipher = Cipher.getInstance(transformation);
    }

    private byte[] decrypt(byte[] msg) throws InvalidKeyException,
            IllegalBlockSizeException, BadPaddingException {
        cipher.init(Cipher.DECRYPT_MODE, spec);
        return cipher.doFinal(msg);
    }

    private byte[] encrypt(String msg) throws InvalidKeyException,
            IllegalBlockSizeException, BadPaddingException {

        cipher.init(Cipher.ENCRYPT_MODE, spec);
        return cipher.doFinal(msg.getBytes());
    }

    public static String convertToHex(byte array[]) {
        StringBuilder buffer = new StringBuilder();
        for (int i = 0; i < array.length; i++) {
            if ((array[i] & 0xff) < 0x10)
                buffer.append("0");

            buffer.append(Integer.toString(array[i] & 0xff, 16));
        }
        return buffer.toString();
    }

    public static Set<String> getCryptImplementations(String serviceType) {
        Set<String> result = new HashSet<String>();

        for (Provider provider : Security.getProviders()) {
            Set<Object> keys = provider.keySet();
            for (Object k : keys) {
                String key = ((String) k).split(" ")[0];

                if (key.startsWith(serviceType + ".")) {
                    result.add(key.substring(serviceType.length() + 1));
                } else if (key.startsWith("Alg.Alias." + serviceType + ".")) {
                    result.add(key.substring(serviceType.length() + 11));
                }
            }
        }
        return result;
    }
 
    public static void printAvailableServices(String service) {
        boolean first = true;
        System.out.println("List of available " + service + "s");
        for (String s : getCryptImplementations(service)) {
            System.out.print(first ? s : ", " + s);
            first = false;
        }
        System.out.println();
        System.out.println();
    }
}

Sample output:


Quote:List of available Ciphers
OID.1.2.840.113549.1.12.1.6, Blowfish, DESedeWrap, Rijndael, DESede, ARCFOUR, PBEWithSHA1AndDESede, PBEWithSHA1AndRC2_40, RC2, RC4, RSA, AESWrap, PBEWithMD5AndTripleDES, OID.1.2.840.113549.1.12.1.3, DES, AES, 1.2.840.113549.1.12.1.6, OID.1.2.840.113549.1.5.3, 1.2.840.113549.1.12.1.3, RSA/ECB/PKCS1Padding, 1.2.840.113549.1.5.3, TripleDES, PBEWithMD5AndDES

List of available KeyGenerators
Blowfish, Rijndael, DESede, HmacMD5, SunTlsKeyMaterial, ARCFOUR, RC2, RC4, HmacSHA384, HmacSHA256, SunTlsMasterSecret, DES, SunTlsRsaPremasterSecret, AES, HmacSHA512, HmacSHA1, TripleDES, SunTlsPrf

Program instantiated with AES as key generating algorithm, AES as transformation algorithm and 128 as key size.

Your message:
Hello Hackforums

encrypted message: 4d7c6c8833b9d90694542568b9e18e1199d4906aac5edec43f5a3ae3dd909480
decrypted message as Hex: 48656c6c6f204861636b666f72756d73
decrypted message as String: Hello Hackforums

Deque

Geen opmerkingen:

Een reactie posten