Hi, all

I have code like this for encrypt - decrypt. but every time i run, result encrypt always different.
so how to value in varible key constant.
then result same every time run

thanks.

import java.io.*;
> import java.security. *;
> import javax.crypto. *;
> import sun.misc.*;
> import com.sun.crypto. provider. *;
> public class SecretWriting {
> public static void main(String[ ] args) throws
> Exception {
> Key key;
> KeyGenerator generator =
> KeyGenerator. getInstance( "DES");
>
> key = generator.generateK ey();
>
> Cipher cipher =
> Cipher.getInstance( "DES/ECB/ PKCS5Padding" );
> cipher.init( Cipher.ENCRYPT_ MODE,key) ;
>
> String amalgam = "ABCD1234";
>
> //encrypt
> for (int i = 2; i < args.length; i++)
> amalgam += " " + args;
> byte[] stringBytes = amalgam.getBytes( "UTF8");
> byte[] raw = cipher.doFinal( stringBytes) ;
> BASE64Encoder encoder = new BASE64Encoder( );
>
> String base64 = encoder.encode( raw);
>
> //decrypt
> cipher.init( Cipher.DECRYPT_ MODE, key);
> BASE64Decoder decoder = new BASE64Decoder( );
> byte[] raw2 = decoder.decodeBuffe r(base64) ;
> byte[] stringBytes2 = cipher.doFinal( raw2);
> String result = new String(stringBytes, "UTF8");
>
> System.out.println( "Text = " + amalgam);
> System.out.println( "result encrypt = " + base64);
> System.out.println( "result decrypt = " + result);
>
> }
> }

If I have understood your question correctly, you are trying to ask - Way to have encrypted and encoded string same, every time you execute your code.

Don't generate key upon every request, keep it a constant, and your problem would probably get solved.

If you want to extend your code from main method to something which does far more critical tasks, it would be better if you keep your keys in a separate file or DB, and read it in a static block in your code. Keeping it in DB will keep your keys safe.

For trying your hands on some better Java cryptographic implementations try using PGP implementations of OpenPGP(Cryptix implementation) or BouncyCastle. Both are widely used, and are easily available.

" Don't generate key upon every request, keep it a constant. "

how make it , where is i put and how i get key for value key variable?

Hmm something like:

private static String key = "*DQWERT*DX&S^DKQWERTYUIOPDYCNSLLD:KJCJDJEYU#!XZVBSGHEJIS";

and then try using it using getBytes().

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.