Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check the result of encryption (SHA1PRNG and AES) in Java?

Tags:

java

sha1

aes

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?

like image 246
Jin Lee Avatar asked Jan 27 '26 10:01

Jin Lee


1 Answers

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);
}
like image 184
Kraylog Avatar answered Jan 28 '26 23:01

Kraylog



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!