Skip to content

Instantly share code, notes, and snippets.

@thiagoh
Created September 1, 2015 22:58
Show Gist options
  • Save thiagoh/e0613341a5769620a2f1 to your computer and use it in GitHub Desktop.
Save thiagoh/e0613341a5769620a2f1 to your computer and use it in GitHub Desktop.
Java class that generates a DESede ciphered code so that I can my "crypto-c" repository (encryptation in java decryptation with crypto-c) https://github.com/thiagoh/crypto-c
import java.util.Arrays;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
public class GenerateCipheredText {
static String _iv = "target";
static byte[] out = Arrays.copyOfRange(_iv.getBytes(), 0, 8);
static String password = "The fox jumped over the lazy dog";
static String plain = "imageId:12";
public static void main(String[] args) throws Exception {
byte[] codedtext = new GenerateCipheredText().encrypt(plain);
String decodedtext = new GenerateCipheredText().decrypt(codedtext);
System.out.println("Ciphered and Base64'ed: " + Base64.getEncoder().encodeToString(codedtext));
System.out.println("IV Base64'ed: " + Base64.getEncoder().encodeToString(out));
System.out.println("Decrypted " + decodedtext);
}
public byte[] encrypt(String message) throws Exception {
final byte[] digestOfPassword = password.getBytes("UTF-8");
SecretKeyFactory factory = SecretKeyFactory.getInstance("DESede");
SecretKey key = factory.generateSecret(new DESedeKeySpec(digestOfPassword));
final IvParameterSpec iv = new IvParameterSpec(out);
final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
final byte[] plainTextBytes = message.getBytes("utf-8");
final byte[] cipherText = cipher.doFinal(plainTextBytes);
return cipherText;
}
public String decrypt(byte[] message) throws Exception {
final byte[] digestOfPassword = password.getBytes("UTF-8");
SecretKeyFactory factory = SecretKeyFactory.getInstance("DESede");
SecretKey key = factory.generateSecret(new DESedeKeySpec(digestOfPassword));
final IvParameterSpec iv = new IvParameterSpec(out);
final Cipher decipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
decipher.init(Cipher.DECRYPT_MODE, key, iv);
final byte[] plainText = decipher.doFinal(message);
return new String(plainText, "UTF-8");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment