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.
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 | 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 Set<String> getServiceTypes() {
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("Alg.Alias.")) {
key = key.substring(10);
}
int ix = key.indexOf('.');
result.add(key.substring(0, ix));
}
}
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:
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, SunTls12RsaPremasterSecret, SunTls12Prf, HmacMD5, SunTlsKeyMaterial, ARCFOUR, RC2, SunTls12KeyMaterial, RC4, HmacSHA384, HmacSHA256, SunTlsMasterSecret, DES, SunTlsRsaPremasterSecret, AES, SunTls12MasterSecret, HmacSHA512, HmacSHA1, TripleDES, SunTlsPrf
Program instantiated with AES as key generating algorithm, AES as transformation algorithm and 128 as key size.
Your message:
Hello Evilzone
encrypted message: 12fdde4c237edf668633228d909114d1
decrypted message as Hex: 48656c6c6f204576696c7a6f6e65
decrypted message as String: Hello Evilzone
Sources:
I used this site for the getCryptImplementations() method and updated the code:
http://www.examplede...stServices.htmlDeque