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

79
LINES

< > BotCompany Repo | #1005117 // Symmetric encryption/decryption test (OK)

JavaX source code [tags: use-pretranspiled] - run with: x30.jar

Libraryless. Click here for Pure Java version (1213L/9K/31K).

!7

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

p {
  S original = "hello";
  byte[] data = original.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, salt);
  printHex(enc);
  System.out.println("enc length: " + enc.length);
  
  byte[] dec = decrypt(enc, pw, salt);
  S decoded = fromUtf8(dec);
  System.out.println("decrypted: " + decoded);
  assertEquals(original, decoded);
  print("OK!!!!");
}

static IvParameterSpec makeIV() {
  ret new IvParameterSpec(new byte[16]);
}

static SecretKey makeKey(S password, byte[] salt) throws Exception {
  /* 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(toCharArray(password), salt, 65536, 128);
  
  SecretKey tmp = factory.generateSecret(spec);
  SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
  return secret;
}

public static byte[] encrypt(byte[] data, S 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, makeIV());
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    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, S password, byte[] salt) {
  try {
    SecretKey secret = makeKey(password, salt);
   
    /* Decrypt the message, given derived key and initialization vector. */
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    cipher.init(Cipher.DECRYPT_MODE, secret, makeIV());
    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 #1000344

download  show line numbers  debug dex  old transpilations   

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

No comments. add comment

Snippet ID: #1005117
Snippet name: Symmetric encryption/decryption test (OK)
Eternal ID of this version: #1005117/3
Text MD5: 4bef5495c36390d6a1fbaaf8f47e1952
Transpilation MD5: 53eb9e203f9832fcb311cd986d27f624
Author: stefan
Category:
Type: JavaX source code
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2018-11-13 23:57:10
Source code size: 2423 bytes / 79 lines
Pitched / IR pitched: No / No
Views / Downloads: 556 / 731
Version history: 2 change(s)
Referenced in: [show references]