Re: Encripting with PBE key
Hi,
thanks a lot for all very useful hints.
Below the working code.
regards,
Krzysztof
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
public class Test05
{
public static void main( String args[] ) throws Exception
{
byte[] salt = {
(byte)0xA9, (byte)0x9B, (byte)0xC8, (byte)0x32,
(byte)0x56, (byte)0x35, (byte)0xE3, (byte)0x03
};
int iterationCount = 19;
String password = "password";
// String password = "different password";
PBEKeySpec keySpec = new PBEKeySpec( password.toCharArray(), salt,
iterationCount, 8 );
System.out.println( "keySpec: " +
String.valueOf( keySpec.getPassword() ) );
System.out.println( "keySpec: " + keySpec.getKeyLength() );
PBEParameterSpec paramSpec = new
PBEParameterSpec( keySpec.getSalt(), keySpec.getIterationCount() );
SecretKeyFactory keyFactory =
SecretKeyFactory.getInstance( "PBE" );
System.out.println( "keyFactory: " + keyFactory.getAlgorithm() );
SecretKey key = keyFactory.generateSecret( keySpec );
System.out.println( "key: " + key.getAlgorithm() );
Cipher cipher = Cipher.getInstance( key.getAlgorithm() );
System.out.println( "cipher.getInstance" );
cipher.init( Cipher.ENCRYPT_MODE, key, paramSpec );
System.out.println( "cipher.init" );
String sinput = "clear text";
System.out.println( "-> " + sinput );
byte bencrypt[] = cipher.doFinal( sinput.getBytes() );
Cipher dcipher = Cipher.getInstance( key.getAlgorithm() );
dcipher.init( Cipher.DECRYPT_MODE, key, paramSpec );
byte bdecrypt[] = dcipher.doFinal( bencrypt );
String soutput = new String( bdecrypt );
System.out.println( "<- " + soutput );
}
}