Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add SealedBox support #127

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions src/main/java/org/libsodium/jni/crypto/SealedBox.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package org.libsodium.jni.crypto;

import org.libsodium.jni.encoders.Encoder;
import org.libsodium.jni.keys.KeyPair;

import static org.libsodium.jni.NaCl.sodium;
import static org.libsodium.jni.SodiumConstants.SEAL_BYTES;

public class SealedBox {

private byte[] mPublicKey;

public SealedBox(byte[] publicKey) {
if (publicKey == null) {
throw new IllegalArgumentException("Public key must not be null");
}
mPublicKey = publicKey;
}

public SealedBox(String publicKey, Encoder encoder) {
this(encoder.decode(publicKey));
}

public byte[] encrypt(byte[] message) {
byte[] ct = new byte[message.length + SEAL_BYTES];
if (sodium().crypto_box_seal(ct, message, message.length, mPublicKey) != 0) {
throw new IllegalArgumentException("Failed to encrypt");
}
return ct;
}

public static byte[] decrypt(byte[] ciphertext, byte[] pubicKey, byte[] privateKey) {
byte[] message = new byte[ciphertext.length - SEAL_BYTES];
if (sodium().crypto_box_seal_open(
message, ciphertext, ciphertext.length, pubicKey, privateKey) != 0) {
throw new IllegalArgumentException(
"Failed to decrypt, ensure to provide the correct combination of parameters");
}
return message;
}

public static byte[] decrypt(byte[] ciphertext, KeyPair keyPair) {
return decrypt(ciphertext, keyPair.getPublicKey().toBytes(),
keyPair.getPrivateKey().toBytes());
}
}