Вы находитесь на странице: 1из 9

byte[] input;

byte[] keyBytes="12345678".getBytes();
byte[] ivBytes="input123"getBytes();
SecretKeySpec key=new SecretKeySpec(keyBytes,"DES");
IvParameterSpec ivSpec=new IvParameterSpec(ivBytes);
Cipher cipher;
byte[] ciphertext;
int cipherlength;
try{
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
input=simple_text.getText.getBytes();
SecretKeySpec key=new SecretKeySpec(keyBytes,"DES");
IvParameterSpec ivSpec=new IvParameterSpec(ivBytes);
cipher=Cipher.getInstance("DES/CTR/NoPadding","BC");
cipher.init(Cipher.ENCRYPT_MODE,key,ivSpec);
ciphertext=new byte[cipher.getOutputSize(input.length)];
cipherlength=cipher.update(input,0,input.length,ciphertext);
cipherlength+=cipher.doFinal(ciphertext,cipherlength);
Encrypt_text.setText(new String(ciphertext));
System.out.println(" cipher"+ new String(ciphertext));
}catch(Exception e)
{
JOptionPane.showMessageDialog(null,e);
}

decrypt

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
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));
}
}

CBC using DES with an IV based on a nonce. In this case a hypothetical message n
umber.
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: " + ctLeng
th);
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));
}
}

Decrypt an object with DES

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(f
ilename)));
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);
}
}

Encrypt an object with DES


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 Excepti
on {
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!", ci
pher);
writeToFile("sealed.dat", sealedObject);
}
}

Encrypting a File or Stream with DES


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, 0
x6F, 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("c
iphertext"));
encrypter.decrypt(new FileInputStream("ciphertext"), new FileOutputStream("c
leartext2"));
}
}

Encrypting a String with DES

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);
}
}

Encrypting with DES Using a Pass Phrase


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) 0x5
6, (byte) 0x35,
(byte) 0xE3, (byte) 0x03 };
DesEncrypter(String passPhrase) throws Exception {
int iterationCount = 2;

KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCo


unt);
SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSec
ret(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);
}
}

Message without tampering with MAC (DES), encryption AES in CTR mode
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.getMa
cLength())];
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.lengt
h);
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());
}
}
package com.journaldev.misc;
import
import
import
import
import
import
import
import
import

java.io.FileInputStream;
java.io.FileOutputStream;
java.io.IOException;
java.io.InputStream;
java.io.OutputStream;
java.security.InvalidAlgorithmParameterException;
java.security.InvalidKeyException;
java.security.NoSuchAlgorithmException;
java.security.spec.AlgorithmParameterSpec;

import
import
import
import
import
import
import

javax.crypto.Cipher;
javax.crypto.CipherInputStream;
javax.crypto.CipherOutputStream;
javax.crypto.KeyGenerator;
javax.crypto.NoSuchPaddingException;
javax.crypto.SecretKey;
javax.crypto.spec.IvParameterSpec;

public class DESEncryptionExample {


private static Cipher encryptCipher;
private static Cipher decryptCipher;
private static final byte[] iv = {11, 22, 33, 44, 99, 88, 77, 66};
public static void main(String[] args) {
String clearTextFile = "/Users/pankaj/source.txt";
String cipherTextFile = "/Users/pankaj/cipher.txt";
String clearTextNewFile = "/Users/pankaj/source-new.txt";

try {
//create SecretKey using KeyGenerator
SecretKey key = KeyGenerator.getInstance("DES").generateKey();
AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv);
//get Cipher instance and initiate in encrypt mode
encryptCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
encryptCipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
//get Cipher instance and initiate in decrypt mode
decryptCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
decryptCipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
//method to encrypt clear text file to encrypted file
encrypt(new FileInputStream(clearTextFile), new FileOutputStream(cip
herTextFile));
//method to decrypt encrypted file to clear text file
decrypt(new FileInputStream(cipherTextFile), new FileOutputStream(cl
earTextNewFile));
System.out.println("DONE");
} catch (NoSuchAlgorithmException |
NoSuchPaddingException |
InvalidKeyException |
InvalidAlgorithmParameterException |
IOException e) {
e.printStackTrace();
}
}
private static void encrypt(InputStream is, OutputStream os) throws IOExcept
ion {
//create CipherOutputStream to encrypt the data using encryptCipher
os = new CipherOutputStream(os, encryptCipher);
writeData(is, os);
}
private static void decrypt(InputStream is, OutputStream os) throws IOExcept
ion {
//create CipherOutputStream to decrypt the data using decryptCipher
is = new CipherInputStream(is, decryptCipher);
writeData(is, os);
}
//utility method to read data from input stream and write to output stream
private static void writeData(InputStream is, OutputStream os) throws IOExce
ption{
byte[] buf = new byte[1024];
int numRead = 0;
//read and write operation
while ((numRead = is.read(buf)) >= 0) {
os.write(buf, 0, numRead);
}
os.close();
is.close();

}
}

Вам также может понравиться