I want to check my result of encryption and decryption with this website
https://8gwifi.org/CipherFunctions.jsp How do I input in the secret key on the website?
This is my java code.
public static void main(String[] args) throws Exception {
final String secretKey = "PASSWORD";
String originalString = "Java Web Developer";
String encryptedString = AESUtils.encrypt(originalString, secretKey) ;
String decryptedString = AESUtils.decrypt(encryptedString, secretKey) ;
System.out.println("Original : " + originalString); //Original : Java Web Developer
System.out.println("Encryption : " + encryptedString); //Encryption : 43Ak2VHK368eandGGYWX2WvbcimGGAEsPdCSjEatjR0=
System.out.println("Decryption : " + decryptedString); //Decryption : Java Web Developer
}
public class AESUtils {
private static SecretKeySpec secretKey;
private static byte[] key;
public static void setKey(String myKey)
{
MessageDigest sha = null;
try {
key = myKey.getBytes("UTF-8");
sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16);
secretKey = new SecretKeySpec(key, "AES");
byte encoded[] = secretKey.getEncoded();
/*
* Encodes the specified byte array into a String using Base64 encoding
* scheme
*/
String encodedKey = Base64.getEncoder().encodeToString(encoded);
System.out.println("SecretKey: " + encodedKey); //SecretKey: ESu3kTBHkd3PaS4p/VzxSQ==
}
catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
public static String encrypt(String strToEncrypt, String secret)
{
try
{
setKey(secret);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
}
catch (Exception e)
{
System.out.println("Error while encrypting: " + e.toString());
}
return null;
}
public static String decrypt(String strToDecrypt, String secret)
{
try
{
setKey(secret);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
}
catch (Exception e)
{
System.out.println("Error while decrypting: " + e.toString());
}
return null;
}
}
I tried inputting the secret key with "ESu3kTBHkd3PaS4p/VzxSQ==", But the result of encryption does not match the result of encryption from the java program.
My Java program retured encryption to be 43Ak2VHK368eandGGYWX2WvbcimGGAEsPdCSjEatjR0=
Related
I have an AES class in java, my intention to decrypt a JSON string in js which encrypted in java,
here is my encryption code
public static void setKey(String myKey)
{
MessageDigest sha = null;
try {
key = myKey.getBytes("UTF-8");
sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16);
System.out.println(Arrays.toString(key));
secretKey = new SecretKeySpec(key, "AES");
}
catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
public static String encrypt(String strToEncrypt, String secret)
{
try
{
setKey(secret);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
}
catch (Exception e)
{
System.out.println("Error while encrypting: " + e.toString());
}
return null;
}
And I have tried many way using Cryptojs
var secret = "llssshhhhhhhhhhh";
var new_secret = CryptoJS.SHA1(getBytes(secret));
console.log(getBytes(new_secret.toString()));
var test = "<Encrypted Text>";
var bytes = CryptoJS.AES.decrypt(test, new_secret, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
var originalText = bytes.toString(CryptoJS.enc.Utf8);
console.log({originalText});
But I am not getting the original text even its return a blank string.
Can anyone know I am wrong?
I am developing a program for Encryption and Decryption , the Encryption is working fine, but the Decryption is throwing error.
I am not able to find, What is the problem in that code??
key.txt
ssshhhhhhhhhhh!!!!
plaintext.txt
naddarbhatia.com
public class hello {
private static SecretKeySpec secretKey;
private static byte[] key;
public static void setKey(String myKey)
{
MessageDigest sha = null;
try {
key = myKey.getBytes("UTF-8");
sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16);
secretKey = new SecretKeySpec(key, "AES");
}
catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
public static String encrypt(String strToEncrypt, String secret)
{
try
{
setKey(secret);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
}
catch (Exception e)
{
System.out.println("Error while encrypting: " + e.toString());
}
return null;
}
public static String decrypt(String strToDecrypt, String secret)
{
try
{
setKey(secret);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
}
catch (Exception e)
{
System.out.println("Error while decrypting: " + e.toString());
}
return null;
}
static String readFile(String path, Charset encoding)
throws IOException
{
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, encoding);
}
public static void main(String[] args) throws IOException
{
String en_de_flag = args[0];
String secretKey="";
try {
secretKey = readFile("/Users/amulbhatia/Documents/EclipseProjects/HelloProject/src/key.txt",StandardCharsets.UTF_8);
//System.out.println(secretKey);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String originalString="";
String encryptedString="";
try {
originalString = readFile("/Users/amulbhatia/Documents/EclipseProjects/HelloProject/src/plaintext.txt",StandardCharsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
if(en_de_flag.equals("0")) {
encryptedString = hello.encrypt(originalString, secretKey) ;
PrintWriter out = new PrintWriter("encrypt.txt");
out.println(encryptedString);
System.out.println("Encrypted File Generated !! 'encrypt.txt' , Please check now");
out.close();
}
if(en_de_flag.equals("1")) {
String decryptedFileContent = readFile("/Users/amulbhatia/Documents/EclipseProjects/HelloProject/src/encrypt.txt",StandardCharsets.UTF_8);
System.out.println("decryptedFileContent:" + decryptedFileContent);
System.out.println("Secret Key:" + secretKey);
String decryptedString = hello.decrypt(decryptedFileContent, secretKey) ;
//System.out.println("Read Encrypted File, Now Decrypting..");
//System.out.println(decryptedString);
}
}}
STACKTRACE
java.lang.IllegalArgumentException: Input byte array has incorrect ending byte at 44
at java.base/java.util.Base64$Decoder.decode0(Base64.java:771)
at java.base/java.util.Base64$Decoder.decode(Base64.java:535)
at java.base/java.util.Base64$Decoder.decode(Base64.java:558)
at hello.decrypt(hello.java:63)
at hello.main(hello.java:12
8)
While executing the above code at command line with argument as '0' the encrypt.txt file will be generated with the encrypted content, and after that when I entered argument as '1' it reads the encrypted file 'encrypt.txt' and 'key.txt' and calls the decrypt function where the same function is getting failed, pl help
That error is thrown by the Base64 decoder because your ciphertext ends with a line terminator, written by the PrintWriter.
Just .trim() your decryptedFileContent (which is actually the encryptedfilecontent...) to remove the line break.
I need to generate a Key in order to use it for encryption and decryption using an AES cipher.
The key must be generated on runtime using a single id value.
How could I generate a Key taking a single string as source?
Hope this can help you.
package com.lahiru.security;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class AESEncryptionDecryption {
private static SecretKeySpec secretKey;
private static byte[] key;
public static void main(String[] args){
String id = "00001";
String plainText = "This is plain text";
String cipherText = encrypt(plainText, id);
System.out.println("Cipher Text after encrption ::: " + cipherText);
System.out.println("Plain Text after decryption ::: " + decrypt(cipherText, id));
}
public static void setKey(String myKey)
{
MessageDigest sha = null;
try {
key = myKey.getBytes("UTF-8");
sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16);
secretKey = new SecretKeySpec(key, "AES");
}
catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
public static String encrypt(String strToEncrypt, String secret)
{
try
{
setKey(secret);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
}
catch (Exception e)
{
System.out.println("Error while encrypting: " + e.toString());
}
return null;
}
public static String decrypt(String strToDecrypt, String secret)
{
try
{
setKey(secret);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
}
catch (Exception e)
{
System.out.println("Error while decrypting: " + e.toString());
}
return null;
}
}
This is my code for converting a normal string to AES encrypted string :
public class AES2
{
private static AES2 aes = new AES2( );
private AES2() { }
public static AES2 getInstance( ) {
return aes;
}
private static SecretKeySpec secretKey ;
private static byte[] key ;
private static String decryptedString;
private static String encryptedString;
public static void setKey(String myKey){
MessageDigest sha = null;
try {
key = myKey.getBytes("UTF-8");
System.out.println(key.length);
sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16); // use only first 128 bit
System.out.println(key.length);
System.out.println(new String(key,"UTF-8"));
secretKey = new SecretKeySpec(key, "AES");
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String encrypt(String strToEncrypt)
{
try
{
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
encryptedString = (Base64.encodeBase64String(cipher.doFinal(strToEncrypt.getBytes("UTF-8"))));
}
catch (Exception e)
{
System.out.println("Error while encrypting: "+e.toString());
}
return null;
}
public static String decrypt(String strToDecrypt)
{
try
{
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] bytes = cipher.doFinal(Base64.decodeBase64(strToDecrypt));
decryptedString = bytes.toString();
}
catch (Exception e)
{
System.out.println("Error while decrypting: "+e.toString());
}
return null;
}
}
I've included commons-codec-1.10.jar in the /libs folder and added it as library.
I'm getting compilation errors while compiling :
1) error: cannot find symbol method encodeBase64String(byte[]), for
encryptedString = (Base64.encodeBase64String(cipher.doFinal(strToEncrypt.getBytes("UTF-8"))));
2) error: incompatible types: String cannot be converted to byte[], for
byte[] bytes = cipher.doFinal(Base64.decodeBase64(strToDecrypt));
I've checked and the functions calls match perfectly, but I have no idea why I'm getting these errors.
What am I doing wrong?
PS : The code is from : http://aesencryption.net/#Java-aes-encryption-example
My AES encryption program is returning different encrypted values on different machines. Can anyone please help on finding out what needs to be done to ensure the same encrypted value is returned on any machine the program is run..
private static SecretKeySpec secret;
private static String seed;
private static String text;
private static String salt = "Salt123";
private static int pswdIterations = 65536;
private static int keySize = 256;
/**
*
* #param mySeed
*/
public static void setSeed(String mySeed) {
try {
byte[] saltBytes = salt.getBytes("UTF-8");
PBEKeySpec spec = new PBEKeySpec(mySeed.toCharArray(), saltBytes,
pswdIterations, keySize);
SecretKeyFactory factory = SecretKeyFactory
.getInstance("PBKDF2WithHmacSHA1");
SecretKey secretKey = factory.generateSecret(spec);
secret = new SecretKeySpec(secretKey.getEncoded(), "AES");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
}
}
public static String getEncryptedStringFor(String text) {
try {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secret);
byte[] encryptedData = cipher.doFinal(text.getBytes("UTF-8"));
return new String(Base64.encodeBase64(encryptedData));
} catch (Exception e) {
System.out.println("Error while encrypting: " + e.toString());
}
return null;
}
public static String getDecryptedStringFor(String text) {
try {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, secret);
return (new String(cipher.doFinal(Base64
.decodeBase64(text.getBytes("UTF-8")))));
} catch (Exception e) {
System.out.println("Error while decrypting: " + e.toString());
}
return null;
}
Some sample values
seed : seed123
text : #text!
Encrypted value : RoVE3KsjzN0nNxCNsNpRPg==
seed : seed!!
text : #text123!
Encrypted value :X6pfUKCVXXrAEyqKko/kFQ==
The only thing I can see in the code is the following line:
return (new String(cipher.doFinal(Base64.decodeBase64(text.getBytes("UTF-8")))));
Now it looks like this is actually returning a String after decoding with UTF-8. But it doesn't: it uses the platform default:
return (new String(
cipher.doFinal(
Base64.decodeBase64(
text.getBytes("UTF-8")
)
)
));
Of course, the first ( is superfluous anyway, so try this:
byte[] ciphertext = Base64.decodeBase64(text.getBytes("UTF-8"));
byte[] plaintext = cipher.doFinal(ciphertext);
return new String(plaintext, "UTF-8");
Note that you can also use import static java.nio.charsets.StandardCharsets.UTF_8 nowadays, which lets you do away with the exception as well. I wish they would do the same for StandardCiphers.AES_CBC_PKCS7PADDING :)