Last active
December 21, 2018 12:47
-
-
Save luiswolff/d8b93dcf3fe28491f8d97bf1c394058e to your computer and use it in GitHub Desktop.
Example how to decrypt a protected message with a provided secret using the Data Encryption Standard algorithm. The messaged is readed from a provided file and the printed to the console. 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.ByteArrayOutputStream; | |
import java.io.FileInputStream; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import java.io.OutputStream; | |
import java.security.InvalidKeyException; | |
import java.security.Key; | |
import java.security.NoSuchAlgorithmException; | |
import javax.crypto.Cipher; | |
import javax.crypto.CipherInputStream; | |
import javax.crypto.NoSuchPaddingException; | |
import javax.crypto.spec.SecretKeySpec; | |
public class MessageDESDecrypter { | |
private static final String PASSWD = System.getProperty("passwd", "__secret"); | |
private static final String SOURCE = System.getProperty("source", "target/test.secured"); | |
public static void main(String[] args) throws Exception { | |
ByteArrayOutputStream sink = new ByteArrayOutputStream(); | |
FileInputStream in = new FileInputStream(SOURCE); | |
Cipher cipher = createCipher(PASSWD.getBytes()); | |
decode(in, cipher, sink); | |
String decoded = new String(sink.toByteArray()); | |
System.out.println(decoded); | |
} | |
static Cipher createCipher(byte[] secret) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException { | |
Cipher cipher = Cipher.getInstance("DES"); | |
Key key = new SecretKeySpec(secret, "DES"); | |
cipher.init(Cipher.DECRYPT_MODE, key); | |
return cipher; | |
} | |
static void decode(InputStream in, Cipher cipher, OutputStream sink) throws IOException { | |
try (CipherInputStream cis = new CipherInputStream(in, cipher)) { | |
for (int b; (b = cis.read()) != -1;) { | |
sink.write(b); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment