Last active
August 17, 2021 08:29
-
-
Save douglarek/04cedb062cbaf832328cc1360891a004 to your computer and use it in GitHub Desktop.
Use https://mvnrepository.com/artifact/org.bouncycastle/bcprov-jdk15on for java aes 128 cbc pcks7.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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