Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

131
LINES

< > BotCompany Repo | #682 // Basic password-based encryption function (developing)

JavaX source code - run with: x30.jar

1  
!636
2  
!quicknew
3  
4  
import java.security.*;
5  
import java.security.spec.*;
6  
import javax.crypto.*;
7  
import javax.crypto.spec.*;
8  
9  
main {
10  
  psvm {
11  
    byte[] data = "hello".getBytes("UTF-8");
12  
    printHex(data);
13  
14  
    Random ranGen = new SecureRandom();
15  
    byte[] salt = new byte[8]; // 8 grains of salt
16  
    ranGen.nextBytes(salt);
17  
    
18  
    String pw = "pw";
19  
    byte[] enc = encrypt(data, pw.toCharArray(), salt);
20  
    printHex(enc);
21  
    System.out.println("enc length: " + enc.length);
22  
    
23  
    byte[] dec = decrypt(enc, pw.toCharArray(), salt);
24  
    System.out.println("decrypted: " + new String(dec, "UTF-8"));
25  
  }
26  
  
27  
  static void printHex(byte[] data) {
28  
    System.out.println(bytesToHex(data));
29  
  }
30  
  
31  
  static String bytesToHex(byte[] bytes) {
32  
    return bytesToHex(bytes, 0, bytes.length);
33  
  }
34  
35  
  static String bytesToHex(byte[] bytes, int ofs, int len) {
36  
    StringBuilder stringBuilder = new StringBuilder(len*2);
37  
    for (int i = 0; i < len; i++) {
38  
      String s = "0" + Integer.toHexString(bytes[ofs+i]);
39  
      stringBuilder.append(s.substring(s.length()-2, s.length()));
40  
    }
41  
    return stringBuilder.toString();
42  
  }
43  
44  
  /*static byte[] encrypt(byte[] data, char[] password,
45  
    byte[] salt) {
46  
    try {
47  
      int noIterations = 1500;
48  
      String method = "PBEWithMD5AndTripleDES";
49  
      SecretKeyFactory kf = SecretKeyFactory.getInstance(method);
50  
      PBEKeySpec keySpec = new PBEKeySpec(password);
51  
      SecretKey key = kf.generateSecret(keySpec);
52  
      Cipher ciph = Cipher.getInstance(method);
53  
      ciph.init(Cipher.DECRYPT_MODE, key);
54  
      PBEParameterSpec params = new PBEParameterSpec(salt, noIterations);
55  
      return ciph.doFinal(data);
56  
    } catch (Exception e) {
57  
      throw new RuntimeException(e);
58  
    }
59  
  }*/
60  
  
61  
  /*public static byte[] encrypt(byte[] data, char[] password, byte[] salt) {
62  
    try {
63  
      String algorithmName = "PBEWithMD5AndTripleDES";
64  
      int count = 1500;
65  
      PBEParameterSpec pbeParamSpec=new PBEParameterSpec(salt,count);
66  
      PBEKeySpec pbeKeySpec=new PBEKeySpec(password);
67  
      SecretKeyFactory keyFac=SecretKeyFactory.getInstance(algorithmName);
68  
      SecretKey pbeKey=keyFac.generateSecret(pbeKeySpec);
69  
      Cipher pbeCipher=Cipher.getInstance(algorithmName);
70  
      pbeCipher.init(Cipher.ENCRYPT_MODE,pbeKey,pbeParamSpec);
71  
      return pbeCipher.doFinal(data);
72  
    } catch (Exception e) {
73  
      throw new RuntimeException(e);
74  
    }
75  
  }*/
76  
  
77  
  static SecretKey makeKey(char[] password, byte[] salt) tex {
78  
    /* Derive the key, given password and salt. */
79  
    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
80  
      
81  
    // only with unlimited strength:
82  
    //KeySpec spec = new PBEKeySpec(password, salt, 65536, 256);
83  
    
84  
    // Let's try this:
85  
    KeySpec spec = new PBEKeySpec(password, salt, 65536, 128);
86  
    
87  
    SecretKey tmp = factory.generateSecret(spec);
88  
    SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
89  
    return secret;
90  
  }
91  
  
92  
  public static byte[] encrypt(byte[] data, char[] password, byte[] salt) {
93  
    try {
94  
      SecretKey secret = makeKey(password, salt);
95  
      
96  
      /* Encrypt the message. */
97  
      Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
98  
      cipher.init(Cipher.ENCRYPT_MODE, secret);
99  
      AlgorithmParameters params = cipher.getParameters();
100  
      byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
101  
      new ByteArrayOutputStream baos;
102  
      baos.write(cipher.update(data));
103  
      baos.write(cipher.doFinal());
104  
      byte[] ciphertext = baos.toByteArray();
105  
      return ciphertext;
106  
    } catch (Exception e) {
107  
      throw new RuntimeException(e);
108  
    }
109  
  }
110  
  
111  
  static byte[] decrypt(byte[] ciphertext, char[] password, byte[] salt) {
112  
    try {
113  
      SecretKey secret = makeKey(password, salt);
114  
     
115  
      Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
116  
      cipher.init(Cipher.ENCRYPT_MODE, secret);
117  
      AlgorithmParameters params = cipher.getParameters();
118  
      byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
119  
120  
      /* Decrypt the message, given derived key and initialization vector. */
121  
      cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
122  
      new ByteArrayOutputStream baos;
123  
      cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv));
124  
      baos.write(cipher.update(ciphertext));
125  
      baos.write(cipher.doFinal());
126  
      return baos.toByteArray(); 
127  
    } catch (Exception e) {
128  
      throw new RuntimeException(e);
129  
    }
130  
  }
131  
}

download  show line numbers  debug dex  old transpilations   

Travelled to 14 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, gwrvuhgaqvyk, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, teubizvjbppd, tslmcundralx, tvejysmllsmz, vouqrxazstgt

No comments. add comment

Snippet ID: #682
Snippet name: Basic password-based encryption function (developing)
Eternal ID of this version: #682/1
Text MD5: 9e08eb54d1456099fbfe006b0133de19
Author: stefan
Category:
Type: JavaX source code
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2015-07-26 19:49:31
Source code size: 4584 bytes / 131 lines
Pitched / IR pitched: No / Yes
Views / Downloads: 778 / 759
Referenced in: [show references]