3

I made a class which has a method to encrypt data using SHA1PRNG and AES algorithm.

public String encrypt(String str, String pw) throws Exception{ 
    byte[] bytes = pw.getBytes();
    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
    sr.setSeed(bytes);
    KeyGenerator kgen = KeyGenerator.getInstance("AES");    
    kgen.init(128,sr);

    SecretKey skey = kgen.generateKey();
    SecretKeySpec skeySpec = new SecretKeySpec(skey.getEncoded(),"AES");
    Cipher c = Cipher.getInstance("AES");
    c.init(Cipher.ENCRYPT_MODE, skeySpec);

    byte[] encrypted = c.doFinal(str.getBytes());
    return Hex.encodeHexString(encrypted); 
}

I used this method in my main.

public static void main(String[] args) throws Exception{
    Encrytion enc = new Encrytion();  //my class name has a typo :(
    enc.encrypt("abcde", "abcdfg");
    System.out.println(enc);

}

My result is

com.dsmentoring.kmi.Encrytion@34340fab

just my packagename + class name + and some number ( I'm guessing this is reference address to the actual data?)

I want to see the result of my encryption like 'a13efx34123fdv....... ' like this. What do I need to add in my main method? Any advice?

Jin Lee
  • 3,194
  • 12
  • 46
  • 86
  • 1
    You are printing the instance rather than the value it returns – karthick Nov 26 '18 at 08:07
  • @karthick How can I print the value? I tried to print 'str' or 'pw' or 'decrypted' but can't figure out how – Jin Lee Nov 26 '18 at 08:11
  • 1
    Just a few feedback. Java 8 onwards, you should use `SecureRandom.getInstanceStrong()` instead of `SHA1PRNG`. `Cipher.getInstance("AES")` defaults to ECB mode which is not secured. You should ideally use an authenticated encryption mode like GCM. You should avoid storing password in `String` as `String` is immutable and you can't clear it. Therefore in heap dumps it may appear. You should also clear `SecretKey` and `SecretKeySpec` after use. I recommend that you read. https://stackoverflow.com/a/53015144/1235935 for complete Java implementation – Saptarshi Basu Nov 26 '18 at 16:29
  • @Saptarshi Basu Thank you so much. It is very helpful~~ – Jin Lee Nov 26 '18 at 23:43

1 Answers1

3

You're printing the Encryption object instead of the result of the function call. You can do this instead:

public static void main(String[] args) throws Exception{
    Encrytion enc = new Encrytion();  //my class name has a typo :(
    String result = enc.encrypt("abcde", "abcdfg");
    System.out.println(result);
}
Kraylog
  • 7,383
  • 1
  • 24
  • 35