PBE File Encrypt : Password Based Encryption « Security « Java Tutorial

Home
Java Tutorial
1.Language
2.Data Type
3.Operators
4.Statement Control
5.Class Definition
6.Development
7.Reflection
8.Regular Expressions
9.Collections
10.Thread
11.File
12.Generics
13.I18N
14.Swing
15.Swing Event
16.2D Graphics
17.SWT
18.SWT 2D Graphics
19.Network
20.Database
21.Hibernate
22.JPA
23.JSP
24.JSTL
25.Servlet
26.Web Services SOA
27.EJB3
28.Spring
29.PDF
30.Email
31.J2ME
32.J2EE Application
33.XML
34.Design Pattern
35.Log
36.Security
37.Apache Common
38.Ant
39.JUnit
Java Tutorial » Security » Password Based Encryption 




import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.MessageDigest;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;

public class MainClass  {
  public static void main(String[] argsthrows Exception{
    Cipher cipher = createCipher(Cipher.ENCRYPT_MODE);
    applyCipher("file_to_encrypt""encrypted_file", cipher);

    cipher = createCipher(Cipher.DECRYPT_MODE);
    applyCipher("file_to_decrypt""decrypted_file", cipher);

  }

  static Cipher createCipher(int modethrows Exception {
    PBEKeySpec keySpec = new PBEKeySpec("test".toCharArray());
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
    SecretKey key = keyFactory.generateSecret(keySpec);
    MessageDigest md = MessageDigest.getInstance("MD5");
    md.update("input".getBytes());
    byte[] digest = md.digest();
    byte[] salt = new byte[8];
    for (int i = 0; i < 8; ++i)
      salt[i= digest[i];
    PBEParameterSpec paramSpec = new PBEParameterSpec(salt, 20);
    Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");
    cipher.init(mode, key, paramSpec);
    return cipher;
  }

  static void applyCipher(String inFile, String outFile, Cipher cipherthrows Exception {
    CipherInputStream in = new CipherInputStream(new FileInputStream(inFile), cipher);
    BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outFile));
    int BUFFER_SIZE = 8;
    byte[] buffer = new byte[BUFFER_SIZE];
    int numRead = 0;
    do {
      numRead = in.read(buffer);
      if (numRead > 0)
        out.write(buffer, 0, numRead);
    while (numRead == 8);
  }
}














36.28.Password Based Encryption
36.28.1.Read the first 8 bytes of the ciphertext and use that as the salt
36.28.2.PBE With SHA And Two fish
36.28.3.PBE File Encrypt
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.