Skip to content

Instantly share code, notes, and snippets.

@kencharos
Created May 20, 2019 01:27
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 kencharos/9604dad10b26b8ba8ba2bbcb53f5a6f2 to your computer and use it in GitHub Desktop.
Save kencharos/9604dad10b26b8ba8ba2bbcb53f5a6f2 to your computer and use it in GitHub Desktop.
GraalVM native-image encryption memo(set --enable-all-security-services and set path of libsunjce.so)
package sample;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.Random;
import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
/**
* to native image
* install graalvm
* for setup native-image `gu install native-image`
* `javac src/sample/Main.java`
* `cd src`
* `native-image sample.Main`
*
* got error
* ````Exception in thread "main" java.security.NoSuchAlgorithmException: Cannot find any provider supporting AES/GCM/NoPadding
* at javax.crypto.Cipher.getInstance(Cipher.java:539)
* at sample.Main.main(Main.java:25)`
*
* see https://github.com/oracle/graal/blob/master/substratevm/JCA-SECURITY-SERVICES.md
* build with option
* `native-image sample.Main --enable-all-security-services`
*
* got warning.
```
WARNING: The sunec native library, required by the SunEC provider, could not be loaded. This library is usually shipped as part of the JDK and can be found under <JAVA_HOME>/jre/lib/<platform>/libsunec.so. It is loaded at run time via System.loadLibrary("sunec"), the first time services from SunEC are accessed. To use this provider's services the java.library.path system property needs to be set accordingly to point to a location that contains libsunec.so. Note that if java.library.path is not set it defaults to the current working directory.
```
run with java.library.path
* `./sample.main -Djava.library.path=<JAVA_HOME>/jre/lib `
*/
public class Main {
private static final String TRANSFORMATION = "AES/GCM/NoPadding";
private static final int NONCE_LENGTH = 12;
private static final int TAG_LENGTH_BITS = 128;
public static void main(String[] args) throws Exception{
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
GCMParameterSpec gcm = new GCMParameterSpec(TAG_LENGTH_BITS, nonce());
byte[] sec = "testtesttesttesttesttesttesttest".getBytes();
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(sec, "AES"), gcm);
byte[] enc = cipher.doFinal("plainText".getBytes());
System.out.println(Base64.getEncoder().encodeToString(enc));
}
private static byte[] nonce() {
byte[] nonce = new byte[NONCE_LENGTH];
// fixed for testing.
//Random random = new SecureRandom();
//random.nextBytes(nonce);
return nonce;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment