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

!636
!quicknew

import java.security.*;
import java.security.spec.*;
import javax.crypto.*;
import javax.crypto.spec.*;

main {
  psvm {
    byte[] data = "hello".getBytes("UTF-8");
    printHex(data);

    Random ranGen = new SecureRandom();
    byte[] salt = new byte[8]; // 8 grains of salt
    ranGen.nextBytes(salt);
    
    String pw = "pw";
    byte[] enc = encrypt(data, pw.toCharArray(), salt);
    printHex(enc);
    System.out.println("enc length: " + enc.length);
    
    byte[] dec = decrypt(enc, pw.toCharArray(), salt);
    System.out.println("decrypted: " + new String(dec, "UTF-8"));
  }
  
  static void printHex(byte[] data) {
    System.out.println(bytesToHex(data));
  }
  
  static String bytesToHex(byte[] bytes) {
    return bytesToHex(bytes, 0, bytes.length);
  }

  static String bytesToHex(byte[] bytes, int ofs, int len) {
    StringBuilder stringBuilder = new StringBuilder(len*2);
    for (int i = 0; i < len; i++) {
      String s = "0" + Integer.toHexString(bytes[ofs+i]);
      stringBuilder.append(s.substring(s.length()-2, s.length()));
    }
    return stringBuilder.toString();
  }

  static SecretKey makeKey(char[] password, byte[] salt) tex {
    /* Derive the key, given password and salt. */
    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
      
    // only with unlimited strength:
    //KeySpec spec = new PBEKeySpec(password, salt, 65536, 256);
    
    // Let's try this:
    KeySpec spec = new PBEKeySpec(password, salt, 65536, 128);
    
    SecretKey tmp = factory.generateSecret(spec);
    SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
    return secret;
  }
  
  public static byte[] encrypt(byte[] data, char[] password, byte[] salt) {
    try {
      SecretKey secret = makeKey(password, salt);
      
      /* Encrypt the message. */
      Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
      cipher.init(Cipher.ENCRYPT_MODE, secret);
      AlgorithmParameters params = cipher.getParameters();
      byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
      new ByteArrayOutputStream baos;
      baos.write(cipher.update(data));
      baos.write(cipher.doFinal());
      byte[] ciphertext = baos.toByteArray();
      return ciphertext;
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
  
  static byte[] decrypt(byte[] ciphertext, char[] password, byte[] salt) {
    try {
      SecretKey secret = makeKey(password, salt);
     
      Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
      cipher.init(Cipher.ENCRYPT_MODE, secret);
      AlgorithmParameters params = cipher.getParameters();
      byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();

      /* Decrypt the message, given derived key and initialization vector. */
      cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
      new ByteArrayOutputStream baos;
      cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv));
      baos.write(cipher.update(ciphertext));
      baos.write(cipher.doFinal());
      return baos.toByteArray(); 
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
}

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: 849 / 781
Referenced in: [show references]