Java – How do I check the results of encryption in Java (SHA1PRNG and AES)?

How do I check the results of encryption in Java (SHA1PRNG and AES)?… here is a solution to the problem.

How do I check the results of encryption in Java (SHA1PRNG and AES)?

I made a class with methods to encrypt data using SHA1PRNG and AES algorithms.

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 the main program.

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 package name + class name + and some numbers (I guess this is a reference address to the actual data?). )

I want to see my encryption results like “a13efx34123fdv…”. What do I need to add to my primary method? Any suggestions?

Solution

You are printing the Encryption object instead of the result of a function call.
You can do this:

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);
}

Related Problems and Solutions