
write a program to encrypt and decrypt the cipher text "adfgvx"

Hi Friend,
Try the following code:
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.io.*;
public class EncryptAndDecrypt {
public static String asHex (byte buf[]) {
StringBuffer buffer = new StringBuffer(buf.length * 2);
int i;
for (i = 0; i < buf.length; i++) {
if (((int) buf[i] & 0xff) < 0x10)
buffer.append("0");
buffer.append(Long.toString((int) buf[i] & 0xff, 16));
}
return buffer.toString();
}
public static void main(String[] args) throws Exception {
String message="adfgvx";
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128);
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(message.getBytes());
System.out.println("encrypted string: " + asHex(encrypted));
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] original =
cipher.doFinal(encrypted);
String decryptedString = new String(original);
System.out.println("decrypted string: " + decryptedString);
}
}
Thanks
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.