Created
December 21, 2018 12:47
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode 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