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

98
LINES

< > BotCompany Repo | #684 // Basic password-based encryption function (for StackOverflow)

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 SecretKey makeKey(char[] password, byte[] salt) tex {
45  
    /* Derive the key, given password and salt. */
46  
    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
47  
      
48  
    // only with unlimited strength:
49  
    //KeySpec spec = new PBEKeySpec(password, salt, 65536, 256);
50  
    
51  
    // Let's try this:
52  
    KeySpec spec = new PBEKeySpec(password, salt, 65536, 128);
53  
    
54  
    SecretKey tmp = factory.generateSecret(spec);
55  
    SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
56  
    return secret;
57  
  }
58  
  
59  
  public static byte[] encrypt(byte[] data, char[] password, byte[] salt) {
60  
    try {
61  
      SecretKey secret = makeKey(password, salt);
62  
      
63  
      /* Encrypt the message. */
64  
      Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
65  
      cipher.init(Cipher.ENCRYPT_MODE, secret);
66  
      AlgorithmParameters params = cipher.getParameters();
67  
      byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
68  
      new ByteArrayOutputStream baos;
69  
      baos.write(cipher.update(data));
70  
      baos.write(cipher.doFinal());
71  
      byte[] ciphertext = baos.toByteArray();
72  
      return ciphertext;
73  
    } catch (Exception e) {
74  
      throw new RuntimeException(e);
75  
    }
76  
  }
77  
  
78  
  static byte[] decrypt(byte[] ciphertext, char[] password, byte[] salt) {
79  
    try {
80  
      SecretKey secret = makeKey(password, salt);
81  
     
82  
      Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
83  
      cipher.init(Cipher.ENCRYPT_MODE, secret);
84  
      AlgorithmParameters params = cipher.getParameters();
85  
      byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
86  
87  
      /* Decrypt the message, given derived key and initialization vector. */
88  
      cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
89  
      new ByteArrayOutputStream baos;
90  
      cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv));
91  
      baos.write(cipher.update(ciphertext));
92  
      baos.write(cipher.doFinal());
93  
      return baos.toByteArray(); 
94  
    } catch (Exception e) {
95  
      throw new RuntimeException(e);
96  
    }
97  
  }
98  
}

Author comment

Began life as a copy of #682

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: #684
Snippet name: Basic password-based encryption function (for StackOverflow)
Eternal ID of this version: #684/1
Text MD5: f37ef245c47591ba7d4897e0a4d22af6
Author: stefan
Category:
Type: JavaX source code
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2015-07-26 19:50:16
Source code size: 3277 bytes / 98 lines
Pitched / IR pitched: No / Yes
Views / Downloads: 781 / 708
Referenced in: [show references]