1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
|
import java.io.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.security.*;
public class DecryptData
{
public static void main(String[] args)
{
try
{
// Create an array to hold the key
byte[] encryptKey = "This is a test DESede key".getBytes();
// Create a DESede key spec from the key
DESedeKeySpec spec = new DESedeKeySpec(encryptKey);
// Get the secret key factor for generating DESede keys
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(
"DESede");
// Generate a DESede SecretKey object
SecretKey theKey = keyFactory.generateSecret(spec);
// Create a DESede Cipher
Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
// Create the initialization vector required for CBC mode
IvParameterSpec ivParameters = new IvParameterSpec(
new byte[] { 12, 34, 56, 78, 90, 87, 65, 43 } );
// Initialize the cipher and put it in decrypt mode
cipher.init(Cipher.DECRYPT_MODE, theKey, ivParameters);
File encryptedFile = new File("encrypted.dat");
// Create a byte block to hold the entire encrypted file
byte[] encryptedText = new byte[(int) encryptedFile.length()];
FileInputStream fileIn = new FileInputStream(encryptedFile);
// Read the entire encrypted file
fileIn.read(encryptedText);
fileIn.close();
// Decrypt the data
byte[] plaintext = cipher.doFinal(encryptedText);
String plaintextStr = new String(plaintext);
System.out.println("The plaintext is:");
System.out.println(plaintextStr);
}
catch (Exception exc)
{
exc.printStackTrace();
}
}
} |
Partager