Hy ,
I have to encrypt a message and then decrypt it.
I have this code , but i need to save the encrypted string in a database and the code generates a random key every time.
I could save the string and the key in the database but that is not ok .
How can i make my own key without needing to generate it every time?
import java.security.InvalidKeyException;
import java.security.Key;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
public class LocalEncrypter {
private static String algorithm = "DESede";
private static Key key = null;
//private static int[] key = new int[24];
private static Cipher cipher = null;
private static void setUp() throws Exception {
key = KeyGenerator.getInstance(algorithm).generateKey();
//SecretKey key = key.getAlgorithm().
cipher = Cipher.getInstance(algorithm);
}
public static void main(String[] args)
throws Exception {
setUp();
byte[] encryptionBytes = null;
String input = "1234";
System.out.println("Entered: " + input);
encryptionBytes = encrypt(input);
System.out.println(
"Recovered: " + decrypt(encryptionBytes));
}
private static byte[] encrypt(String input)
throws InvalidKeyException,
BadPaddingException,
IllegalBlockSizeException {
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] inputBytes = input.getBytes();
return cipher.doFinal(inputBytes);
}
private static String decrypt(byte[] encryptionBytes)
throws InvalidKeyException,
BadPaddingException,
IllegalBlockSizeException {
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] recoveredBytes =
cipher.doFinal(encryptionBytes);
String recovered =
new String(recoveredBytes);
return recovered;
}
}
I don`t want to use sun.misc.base64 ....