Skip to content

Instantly share code, notes, and snippets.

@fmbenhassine
Last active May 24, 2018 20:51
Show Gist options
  • Save fmbenhassine/875e6fcf47ce200c740c to your computer and use it in GitHub Desktop.
Save fmbenhassine/875e6fcf47ce200c740c to your computer and use it in GitHub Desktop.
Java Crypto hello world #lab
package io.github.benas.labs.javase.crypto;
import javax.crypto.*;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException,
NoSuchAlgorithmException, InvalidKeySpecException,
NoSuchPaddingException, InvalidKeyException,
InvalidAlgorithmParameterException, IllegalBlockSizeException,
BadPaddingException {
// In order to use Password-Based Encryption (PBE) as defined in PKCS
// #5, we have to specify a salt and an iteration count. The same salt
// and iteration count that are used for encryption must be used for
// decryption:
PBEKeySpec pbeKeySpec;
PBEParameterSpec pbeParamSpec;
SecretKeyFactory keyFac;
// Salt
byte[] salt = {(byte) 0xc7, (byte) 0x73, (byte) 0x21, (byte) 0x8c,
(byte) 0x7e, (byte) 0xc8, (byte) 0xee, (byte) 0x99};
// Iteration count
int count = 20;
// Create PBE parameter set
pbeParamSpec = new PBEParameterSpec(salt, count);
// Prompt user for encryption password.
// Collect user password as char array (using the
// "readPasswd" method from above), and
System.out.print("Enter the encrypted message: ");
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
byte[] input = s.getBytes();
System.out.println("string length =" + s.length());
System.out.println("byte length =" + input.length);
System.out.print("Enter the encryption password: ");
System.out.println("password = mbh");
pbeKeySpec = new PBEKeySpec("mbh".toCharArray());
// convert it into a SecretKey object, using a PBE key
// factory
keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);
// Create PBE Cipher
Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
pbeCipher.init(Cipher.DECRYPT_MODE, pbeKey, pbeParamSpec);
byte[] clearTextdecrypted;
try {
clearTextdecrypted = pbeCipher.doFinal(input);
System.out.println("decrypted message is : " + new String(clearTextdecrypted));
} catch (BadPaddingException e) {
System.err.println("wrong password!" + e.getMessage());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment