001package com.pusher.rest.crypto.nacl; 002 003import java.security.SecureRandom; 004import java.util.HashMap; 005import java.util.Map; 006 007/** 008 * SecretBox class controls access to TweetNaclFast to prevent users from 009 * reaching out to TweetNaclFast. TweetNaclFast must stay package private. 010 */ 011public class SecretBox { 012 013 private final static int NONCE_LENGTH = 24; 014 015 public static Map<String, byte[]> box(final byte[] key, final byte[] message) { 016 TweetNaclFast.SecretBox secretBox = new TweetNaclFast.SecretBox(key); 017 018 final byte[] nonce = new byte[NONCE_LENGTH]; 019 new SecureRandom().nextBytes(nonce); 020 final byte[] cipher = secretBox.box(message, nonce); 021 022 final Map<String, byte[]> res = new HashMap<>(); 023 res.put("cipher", cipher); 024 res.put("nonce", nonce); 025 026 return res; 027 } 028 029 public static byte[] open(final byte[] key, final byte[] nonce, final byte[] cipher) { 030 TweetNaclFast.SecretBox secretBox = new TweetNaclFast.SecretBox(key); 031 032 final byte[] decryptedMessage = secretBox.open(cipher, nonce); 033 034 if (decryptedMessage == null) { 035 throw new RuntimeException("can't decrypt"); 036 } 037 038 return decryptedMessage; 039 } 040}