Skip to content

Instantly share code, notes, and snippets.

@luiswolff
Created December 21, 2018 12:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luiswolff/a1c4725b4280584aa3fc7e12623d3350 to your computer and use it in GitHub Desktop.
Save luiswolff/a1c4725b4280584aa3fc7e12623d3350 to your computer and use it in GitHub Desktop.
Example how to encrypt a message with a provided secret using the Data Encryption Standard algorithm. The message is writen to a given file. The provided secret is required to have exactly 8 characters.
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
public class MessageDESEncrypter {
private static final String MESSAGE = System.getProperty("message", "Hello encrypted world");
private static final String PASSWD = System.getProperty("passwd", "__secret");
private static final String SINK = System.getProperty("sink", "target/test.secured");
public static void main(String[] args) throws Exception {
FileOutputStream out = new FileOutputStream(SINK);
Cipher cipher = createCipher(PASSWD.getBytes());
encode(MESSAGE.getBytes(), out, cipher);
}
static Cipher createCipher(byte[] secret) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
Cipher cipher = Cipher.getInstance("DES");
Key key = new SecretKeySpec(secret, "DES");
cipher.init(Cipher.ENCRYPT_MODE, key);
return cipher;
}
static void encode(byte[] bytes, OutputStream out, Cipher cipher) throws Exception {
try ( OutputStream cos = new CipherOutputStream(out, cipher)) {
cos.write(bytes);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment