Java Tutorial/Security/DES Data Encryption Standard
Содержание
- 1 Basic symmetric encryption example with CTR using DES
- 2 CBC using DES with an IV based on a nonce. In this case a hypothetical message number.
- 3 Decrypt an object with DES
- 4 Encrypt an object with DES
- 5 Encrypting a File or Stream with DES
- 6 Encrypting a String with DES
- 7 Encrypting with DES Using a Pass Phrase
- 8 Message without tampering with MAC (DES), encryption AES in CTR mode
Basic symmetric encryption example with CTR using DES
<source lang="java">
import java.security.Security; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; public class MainClass {
public static void main(String[] args) throws Exception { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); byte[] input = "input".getBytes(); byte[] keyBytes = "12345678".getBytes(); byte[] ivBytes = "input123".getBytes(); SecretKeySpec key = new SecretKeySpec(keyBytes, "DES"); IvParameterSpec ivSpec = new IvParameterSpec(ivBytes); Cipher cipher = Cipher.getInstance("DES/CTR/NoPadding", "BC"); cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec); byte[] cipherText = new byte[cipher.getOutputSize(input.length)]; int ctLength = cipher.update(input, 0, input.length, cipherText, 0); ctLength += cipher.doFinal(cipherText, ctLength); System.out.println("cipher: " + new String(cipherText)); cipher.init(Cipher.DECRYPT_MODE, key, ivSpec); byte[] plainText = new byte[cipher.getOutputSize(ctLength)]; int ptLength = cipher.update(cipherText, 0, ctLength, plainText, 0); ptLength += cipher.doFinal(plainText, ptLength); System.out.println("plain : " + new String(plainText)); }
}</source>
CBC using DES with an IV based on a nonce. In this case a hypothetical message number.
<source lang="java">
import java.security.Security; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; public class MainClass {
public static void main(String[] args) throws Exception { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); byte[] input = "input".getBytes(); byte[] keyBytes = "input123".getBytes(); byte[] msgNumber = "input".getBytes(); IvParameterSpec zeroIv = new IvParameterSpec(new byte[8]); SecretKeySpec key = new SecretKeySpec(keyBytes, "DES"); Cipher cipher = Cipher.getInstance("DES/CBC/PKCS7Padding", "BC"); cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv); IvParameterSpec encryptionIv = new IvParameterSpec(cipher.doFinal(msgNumber), 0, 8); cipher.init(Cipher.ENCRYPT_MODE, key, encryptionIv); byte[] cipherText = new byte[cipher.getOutputSize(input.length)]; int ctLength = cipher.update(input, 0, input.length, cipherText, 0); ctLength += cipher.doFinal(cipherText, ctLength); System.out.println("cipher: " + new String(cipherText) + " bytes: " + ctLength); cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv); IvParameterSpec decryptionIv = new IvParameterSpec(cipher.doFinal(msgNumber), 0, 8); cipher.init(Cipher.DECRYPT_MODE, key, decryptionIv); byte[] plainText = new byte[cipher.getOutputSize(ctLength)]; int ptLength = cipher.update(cipherText, 0, ctLength, plainText, 0); ptLength += cipher.doFinal(plainText, ptLength); System.out.println("plain : " + new String(plainText, ptLength)); }
}</source>
Decrypt an object with DES
<source lang="java">
import java.io.File; import java.io.FileInputStream; import java.io.ObjectInputStream; import javax.crypto.Cipher; import javax.crypto.SealedObject; import javax.crypto.SecretKey; public class Main {
private static Object readFromFile(String filename) throws Exception { ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File(filename))); Object object = ois.readObject(); ois.close(); return object; } public static void main(String[] args) throws Exception { SecretKey key = (SecretKey) readFromFile("secretkey.dat"); SealedObject sealedObject = (SealedObject) readFromFile("sealed.dat"); String algorithmName = sealedObject.getAlgorithm(); Cipher cipher = Cipher.getInstance(algorithmName); cipher.init(Cipher.DECRYPT_MODE, key); String text = (String) sealedObject.getObject(cipher); System.out.println("Text = " + text); }
}</source>
Encrypt an object with DES
<source lang="java">
import java.io.File; import java.io.FileOutputStream; import java.io.ObjectOutputStream; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SealedObject; import javax.crypto.SecretKey; public class Main {
private static void writeToFile(String filename, Object object) throws Exception { ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File(filename))); oos.writeObject(object); oos.flush(); oos.close(); } public static void main(String[] args) throws Exception { SecretKey key = KeyGenerator.getInstance("DES").generateKey(); writeToFile("secretkey.dat", key); Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.ENCRYPT_MODE, key); SealedObject sealedObject = new SealedObject("THIS IS A SECRET MESSAGE!", cipher); writeToFile("sealed.dat", sealedObject); }
}</source>
Encrypting a File or Stream with DES
<source lang="java">
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.security.spec.AlgorithmParameterSpec; import javax.crypto.Cipher; import javax.crypto.CipherInputStream; import javax.crypto.CipherOutputStream; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.IvParameterSpec; class DesEncrypter {
byte[] buf = new byte[1024]; Cipher ecipher; Cipher dcipher; DesEncrypter(SecretKey key) throws Exception{ byte[] iv = new byte[] { (byte) 0x8E, 0x12, 0x39, (byte) 0x9C, 0x07, 0x72, 0x6F, 0x5A }; AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv); ecipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); dcipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec); dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec); }
public void encrypt(InputStream in, OutputStream out) throws Exception{ out = new CipherOutputStream(out, ecipher); int numRead = 0; while ((numRead = in.read(buf)) >= 0) { out.write(buf, 0, numRead); } out.close(); } public void decrypt(InputStream in, OutputStream out) throws Exception{ in = new CipherInputStream(in, dcipher); int numRead = 0; while ((numRead = in.read(buf)) >= 0) { out.write(buf, 0, numRead); } out.close(); }
} public class Main {
public static void main(String[] argv) throws Exception { SecretKey key = KeyGenerator.getInstance("DES").generateKey(); DesEncrypter encrypter = new DesEncrypter(key); encrypter.encrypt(new FileInputStream("cleartext1"), new FileOutputStream("ciphertext")); encrypter.decrypt(new FileInputStream("ciphertext"), new FileOutputStream("cleartext2")); }
}</source>
Encrypting a String with DES
<source lang="java">
import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; class DesEncrypter {
Cipher ecipher; Cipher dcipher; DesEncrypter(SecretKey key) throws Exception { ecipher = Cipher.getInstance("DES"); dcipher = Cipher.getInstance("DES"); ecipher.init(Cipher.ENCRYPT_MODE, key); dcipher.init(Cipher.DECRYPT_MODE, key); } public String encrypt(String str) throws Exception { // Encode the string into bytes using utf-8 byte[] utf8 = str.getBytes("UTF8"); // Encrypt byte[] enc = ecipher.doFinal(utf8); // Encode bytes to base64 to get a string return new sun.misc.BASE64Encoder().encode(enc); } public String decrypt(String str) throws Exception { // Decode base64 to get bytes byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str); byte[] utf8 = dcipher.doFinal(dec); // Decode using utf-8 return new String(utf8, "UTF8"); }
} public class Main {
public static void main(String[] argv) throws Exception { SecretKey key = KeyGenerator.getInstance("DES").generateKey(); DesEncrypter encrypter = new DesEncrypter(key); String encrypted = encrypter.encrypt("Don"t tell anybody!"); String decrypted = encrypter.decrypt(encrypted); }
}</source>
Encrypting with DES Using a Pass Phrase
<source lang="java">
import java.security.spec.AlgorithmParameterSpec; import java.security.spec.KeySpec; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.PBEParameterSpec; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; class DesEncrypter {
Cipher ecipher; Cipher dcipher; byte[] salt = { (byte) 0xA9, (byte) 0x9B, (byte) 0xC8, (byte) 0x32, (byte) 0x56, (byte) 0x35, (byte) 0xE3, (byte) 0x03 }; DesEncrypter(String passPhrase) throws Exception { int iterationCount = 2; KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount); SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec); ecipher = Cipher.getInstance(key.getAlgorithm()); dcipher = Cipher.getInstance(key.getAlgorithm()); AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount); ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec); dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec); } public String encrypt(String str) throws Exception { return new BASE64Encoder().encode(ecipher.doFinal(str.getBytes())); } public String decrypt(String str) throws Exception { return new String(dcipher.doFinal(new BASE64Decoder().decodeBuffer(str))); }
} public class Main {
public static void main(String[] argv) throws Exception { DesEncrypter encrypter = new DesEncrypter("My Pass Phrase!"); String encrypted = encrypter.encrypt("Don"t tell anybody!"); String decrypted = encrypter.decrypt(encrypted); }
}</source>
Message without tampering with MAC (DES), encryption AES in CTR mode
<source lang="java">
import java.security.Key; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.SecureRandom; import java.security.Security; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.Mac; import javax.crypto.SecretKey; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; public class MainClass {
public static void main(String[] args) throws Exception { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); SecureRandom random = new SecureRandom(); IvParameterSpec ivSpec = createCtrIvForAES(); Key key = createKeyForAES(256, random); Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding", "BC"); String input = "12345678"; Mac mac = Mac.getInstance("DES", "BC"); byte[] macKeyBytes = new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 }; Key macKey = new SecretKeySpec(macKeyBytes, "DES"); cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec); byte[] cipherText = new byte[cipher.getOutputSize(input.length() + mac.getMacLength())]; int ctLength = cipher.update(input.getBytes(), 0, input.length(), cipherText, 0); mac.init(macKey); mac.update(input.getBytes()); ctLength += cipher.doFinal(mac.doFinal(), 0, mac.getMacLength(), cipherText, ctLength); cipher.init(Cipher.DECRYPT_MODE, key, ivSpec); byte[] plainText = cipher.doFinal(cipherText, 0, ctLength); int messageLength = plainText.length - mac.getMacLength(); mac.init(macKey); mac.update(plainText, 0, messageLength); byte[] messageHash = new byte[mac.getMacLength()]; System.arraycopy(plainText, messageLength, messageHash, 0, messageHash.length); System.out.println("plain : " + new String(plainText) + " verified: " + MessageDigest.isEqual(mac.doFinal(), messageHash)); } public static SecretKey createKeyForAES(int bitLength, SecureRandom random) throws NoSuchAlgorithmException, NoSuchProviderException { KeyGenerator generator = KeyGenerator.getInstance("AES", "BC"); generator.init(128, random); return generator.generateKey(); } public static IvParameterSpec createCtrIvForAES() { return new IvParameterSpec("1234567812345678".getBytes()); }
}</source>