Skip to content

Instantly share code, notes, and snippets.

@rredpoppy
Created September 1, 2017 23:11
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save rredpoppy/df6ac333e9aacdf32bd587ef5372a87f to your computer and use it in GitHub Desktop.
Save rredpoppy/df6ac333e9aacdf32bd587ef5372a87f to your computer and use it in GitHub Desktop.
BouncyCastle AES 256 CBC Java <-> Js
/*
* Unrestricted security policy files for Java JRE need to be installed from Oracle for 256 keys to work
*/
package com.mycompany.mavenproject1;
import java.security.SecureRandom;
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Arrays;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
public class Main {
private static final int keyLength = 32;
private static final SecureRandom random = new SecureRandom();
private static SecretKey key;
private static byte[] iv;
public static void main(String [] args) throws Exception {
Security.addProvider(new BouncyCastleProvider());
String plaintext = "hello world";
byte [] ciphertext = encrypt(plaintext);
String recoveredPlaintext = decrypt(ciphertext);
System.out.println(recoveredPlaintext);
}
private static void printByteArr(byte[] arr) {
System.out.print("[");
for (int i = 0; i < arr.length; i++) {
System.out.printf(i == 0 ? "%d" : ",%d", (arr[i] & 0xFF));
}
System.out.println("]");
}
private static byte [] encrypt(String plaintext) throws Exception {
key = generateKey();
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
String ivStr = "0123456789abcdef";
iv = ivStr.getBytes("US-ASCII");
cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));
System.out.println(
Base64.getEncoder().withoutPadding()
.encodeToString(key.getEncoded())
);
printByteArr(iv);
return cipher.doFinal(plaintext.getBytes());
}
private static String decrypt(byte [] ciphertext) throws Exception {
printByteArr(ciphertext);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
return new String(cipher.doFinal(ciphertext));
}
private static SecretKey generateKey() throws Exception {
byte[] keyBytes = new byte[keyLength];
random.nextBytes(keyBytes);
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
return keySpec;
}
private static IvParameterSpec generateIV(Cipher cipher) throws Exception {
byte [] ivBytes = new byte[cipher.getBlockSize()];
random.nextBytes(ivBytes);
return new IvParameterSpec(ivBytes);
}
}
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mycompany</groupId>
<artifactId>mavenproject1</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.bouncycastle/bcprov-jdk15on -->
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.58</version>
</dependency>
</dependencies>
</project>
var key;
crypto.subtle.importKey(
"jwk",
{ kty: "oct", k: "3xWUgMp33fKgl8xTYgn7Ono5yE9H4I879znj2fUxBYU", alg: "A256CBC", ext: true },
{ name: "AES-CBC" },
true,
["encrypt", "decrypt"]
)
.then(function(importedKey) {
key = importedKey;
})
.catch(function(err) {
console.error(err);
});
var iv = Uint8Array.from([48,49,50,51,52,53,54,55,56,57,97,98,99,100,101,102])
var data = Uint8Array.from([225,175,9,149,146,159,199,27,171,164,230,135,152,103,23,189])
var decrypted;
crypto.subtle.decrypt(
{ name: "AES-CBC", iv: iv },
key,
data
)
.then(function(decr) {
decrypted = new Uint8Array(decr);
decrypted.map( function(b) { console.log(String.fromCharCode(b)) } )
})
.catch(function(err) {
console.error(err, data);
});
@Newbiedev39
Copy link

Hi! Is there anyway I can reach you about this code? I'd like to implement this in Go but I have some questions about where you got some values. Thank you!

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