Skip to content

Instantly share code, notes, and snippets.

@netkiller
Created June 9, 2015 10:44
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save netkiller/8167ff2397320c38c946 to your computer and use it in GitHub Desktop.
Save netkiller/8167ff2397320c38c946 to your computer and use it in GitHub Desktop.
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64.*;
//import org.apache.commons.codec.binary.Base64;
/**
* @author netkiller
*
*/
public class aes {
public static String encrypt(String input, String key) {
byte[] crypted = null;
try {
SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skey);
crypted = cipher.doFinal(input.getBytes());
} catch (Exception e) {
System.out.println(e.toString());
}
java.util.Base64.Encoder encoder = java.util.Base64.getEncoder();
return new String(encoder.encodeToString(crypted));
}
public static String decrypt(String input, String key) {
byte[] output = null;
try {
java.util.Base64.Decoder decoder = java.util.Base64.getDecoder();
SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, skey);
output = cipher.doFinal(decoder.decode(input));
} catch (Exception e) {
System.out.println(e.toString());
}
return new String(output);
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String key = "mvLBiZsiTbGwrfJB";
String data = "ABC";
System.out.println(aes.encrypt(data, key));
System.out.println(aes.decrypt(aes.encrypt(data, key), key));
}
}
@jacksonn455
Copy link

I can leave space in the key string and data string ?

@modione
Copy link

modione commented Jan 29, 2021

I can leave space in the key string and data string ?

yes

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment