Skip to content

Instantly share code, notes, and snippets.

@douglarek
Last active August 17, 2021 08:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save douglarek/04cedb062cbaf832328cc1360891a004 to your computer and use it in GitHub Desktop.
Save douglarek/04cedb062cbaf832328cc1360891a004 to your computer and use it in GitHub Desktop.
package hello;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Base64;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import java.security.spec.AlgorithmParameterSpec;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class MyAES {
static {
Security.addProvider(new BouncyCastleProvider());
}
private final SecretKeySpec secretKeySpec;
private final AlgorithmParameterSpec paramSpec;
private Cipher cipher;
public MyAES(final String iv, final String key) {
this.secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
this.paramSpec = new IvParameterSpec(iv.getBytes(StandardCharsets.UTF_8));
try {
this.cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
// Never should be here
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
Security.addProvider(new BouncyCastleProvider());
final String plainText = "hello world";
final MyAES aes = new MyAES("J@JAFU&zcVyFyuA5", "cUa8tPn4UCYVa%Vw");
final String encryptedText = aes.encrypt(plainText);
System.out.printf("Original string: %s\n", plainText);
System.out.printf("Encrypted string: %s\n", encryptedText);
System.out.printf("Encrypted string: %s\n", aes.decrypt(encryptedText));
}
public String encrypt(final String value) throws Exception {
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, paramSpec);
return new String(Base64.encode(cipher.doFinal(value.getBytes(StandardCharsets.UTF_8))));
}
public String decrypt(final String value) throws Exception {
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, paramSpec);
return new String(cipher.doFinal(Base64.decode(value.getBytes(StandardCharsets.UTF_8))));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment