Skip to content

Commit

Permalink
Symmetric keygen: JavaThemis (#565)
Browse files Browse the repository at this point in the history
More or less straightforward, if involved implementation. The main class
is SymmetricKey which manages input validation and delegates actual key
generation to JNI code.

JNI returns "null" on errors, just like other methods, because it's
easier to deal with Java exceptions from Java.

Note the cast from jbyte* to uint8_t*. It is necessary because Java
bytes are always signed, but uint8_t is unsigned. Later we cast them
back so this does not cause any problems.

We add more constructors to KeyGenerationException because now we need
to have some messages there as there are two places where keys are
generated.

Do not export new constructors for KeyGenerationException. There is no
reason for the users to construct instances of these exceptions.

Historically we had constructors for other exceptions, but that's
a mistake. We can't hide them without breaking compatibility, but we
can avoid making the same mistake again.
  • Loading branch information
ilammy committed Dec 11, 2019
1 parent 3ff3cca commit 8c808a1
Show file tree
Hide file tree
Showing 6 changed files with 162 additions and 3 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ _Code:_
- Fixed a NullPointerException bug in `SecureSocket` initialisation ([#557](https://github.com/cossacklabs/themis/pull/557)).
- Some Themis exceptions have been converted from checked `Exception` to _unchecked_ `RuntimeException`, relaxing requirements for `throws` specifiers ([#563](https://github.com/cossacklabs/themis/pull/563)).
- Introduced `IKey` interface with accessors to raw key data ([#564](https://github.com/cossacklabs/themis/pull/564)).
- New class `SymmetricKey` can be used to generate symmetric keys for Secure Cell ([#565](https://github.com/cossacklabs/themis/pull/565)).

- **Node.js**

Expand Down
41 changes: 41 additions & 0 deletions jni/themis_keygen.c
Original file line number Diff line number Diff line change
Expand Up @@ -113,3 +113,44 @@ JNIEXPORT jobjectArray JNICALL Java_com_cossacklabs_themis_KeypairGenerator_gene

return keys;
}

JNIEXPORT jbyteArray JNICALL Java_com_cossacklabs_themis_SymmetricKey_generateSymmetricKey(JNIEnv* env,
jobject thiz)
{
themis_status_t res;
jbyteArray key = NULL;
jbyte* key_buffer = NULL;
size_t key_length = 0;

UNUSED(thiz);

res = themis_gen_sym_key(NULL, &key_length);
if (res != THEMIS_BUFFER_TOO_SMALL) {
goto error;
}

key = (*env)->NewByteArray(env, key_length);
if (!key) {
goto error;
}

key_buffer = (*env)->GetByteArrayElements(env, key, NULL);
if (!key_buffer) {
goto error;
}

res = themis_gen_sym_key((uint8_t*)key_buffer, &key_length);
if (res != THEMIS_SUCCESS) {
goto error_release_key;
}

(*env)->ReleaseByteArrayElements(env, key, key_buffer, 0);

return key;

error_release_key:
(*env)->ReleaseByteArrayElements(env, key, key_buffer, JNI_ABORT);

error:
return NULL;
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,12 @@

public class KeyGenerationException extends RuntimeException {

KeyGenerationException(String message) {
super(message);
}

KeyGenerationException(String message, Throwable cause) {
super(message, cause);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public static Keypair generateKeypair() {
try {
return generateKeypair(AsymmetricKey.KEYTYPE_EC);
} catch (InvalidArgumentException e) {
throw new KeyGenerationException();
throw new KeyGenerationException("failed to generate keypair", e);
}
}

Expand All @@ -60,9 +60,9 @@ public static Keypair generateKeypair(int keyType) {
byte[][] keys = generateKeys(keyType);

if (null == keys) {
throw new KeyGenerationException();
throw new KeyGenerationException("failed to generate keypair");
}

return new Keypair(new PrivateKey(keys[0]), new PublicKey(keys[1]));
}
}
}
54 changes: 54 additions & 0 deletions src/wrappers/themis/java/com/cossacklabs/themis/SymmetricKey.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/*
* Copyright (c) 2019 Cossack Labs Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.cossacklabs.themis;

/**
* Symmetric encryption key.
*
* These keys are used with Secure Cell cryptosystem.
*/
public class SymmetricKey extends KeyBytes {

/**
* Generates a new symmetric key.
*/
public SymmetricKey() {
super(newSymmetricKey());
}

/**
* Creates a symmetric key from byte array.
*
* @param key byte array
*
* @throws NullArgumentException if `key` is null.
* @throws InvalidArgumentException if `key` is empty.
*/
public SymmetricKey(byte[] key) {
super(key);
}

private static native byte[] generateSymmetricKey();

private static byte[] newSymmetricKey() {
byte[] key = generateSymmetricKey();
if (key == null || key.length == 0) {
throw new KeyGenerationException("failed to generate symmetric key");
}
return key;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/*
* Copyright (c) 2019 Cossack Labs Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.cossacklabs.themis.test;

import com.cossacklabs.themis.SymmetricKey;
import com.cossacklabs.themis.InvalidArgumentException;
import com.cossacklabs.themis.NullArgumentException;

import static org.junit.Assert.*;
import org.junit.Test;

public class SymmetricKeyTest {

private static final int defaultLength = 32;

@Test
public void generateNewKey() {
SymmetricKey key = new SymmetricKey();

byte[] keyBytes = key.toByteArray();
assertNotNull(keyBytes);
assertEquals(keyBytes.length, defaultLength);
}

@Test
public void restoreKeyFromBytes() {
byte[] buffer = { 3, 14, 15, 92, 6 };
SymmetricKey key = new SymmetricKey(buffer);
assertArrayEquals(buffer, key.toByteArray());
}

@Test(expected = NullArgumentException.class)
public void restoreKeyFromNull() {
SymmetricKey key = new SymmetricKey(null);
}

@Test(expected = InvalidArgumentException.class)
public void restoreKeyFromEmpty() {
SymmetricKey key = new SymmetricKey(new byte[0]);
}
}

0 comments on commit 8c808a1

Please sign in to comment.