Skip to content

Instantly share code, notes, and snippets.

@jnizet
Created October 27, 2017 18:52
Show Gist options
  • Save jnizet/5ce2971a94fb6f88a746607243613ca7 to your computer and use it in GitHub Desktop.
Save jnizet/5ce2971a94fb6f88a746607243613ca7 to your computer and use it in GitHub Desktop.
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class Encryption {
public static SecretKey generateKey() throws NoSuchAlgorithmException {
Security.addProvider(new com.sun.crypto.provider.SunJCE());
KeyGenerator keygen = KeyGenerator.getInstance("DESede");
keygen.init(168);
SecretKey klucz = keygen.generateKey();
return klucz;
}
static byte[] encrypt(byte[] plainTextByte, SecretKey klucz)
throws Exception {
Cipher cipher = Cipher.getInstance("DESede");
cipher.init(Cipher.ENCRYPT_MODE, klucz);
byte[] encryptedBytes = cipher.doFinal(plainTextByte);
return encryptedBytes;
}
static byte[] decrypt(byte[] encryptedBytes, SecretKey klucz)
throws Exception {
Cipher cipher = Cipher.getInstance("DESede");
cipher.init(Cipher.DECRYPT_MODE, klucz);
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
return decryptedBytes;
}
public static void main(String[] args) throws Exception {
SecretKey klucz = generateKey();
byte[] plainText = "Hello world".getBytes();
byte[] encrypted = encrypt(plainText, klucz);
String encodedKey = Base64.getEncoder().encodeToString(klucz.getEncoded());
byte[] decodedKey = Base64.getDecoder().decode(encodedKey);
SecretKey klucz2 = new SecretKeySpec(decodedKey, "DESede");
byte[] decrypted = decrypt(encrypted, klucz2);
System.out.println("decrypted = " + new String(decrypted));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment