Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * JBoss, Home of Professional Open Source.
   * Copyright 2012, Red Hat, Inc., and individual contributors
   * as indicated by the @author tags. See the copyright.txt file in the
   * distribution for a full listing of individual contributors.
   *
   * This is free software; you can redistribute it and/or modify it
   * under the terms of the GNU Lesser General Public License as
   * published by the Free Software Foundation; either version 2.1 of
  * the License, or (at your option) any later version.
  *
  * This software is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
  * License along with this software; if not, write to the Free
  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
  */
 package org.picketbox.json.enc;
 
 import static org.picketbox.json.PicketBoxJSONConstants.COMMON.PERIOD;
 
 import java.util.UUID;
 
 
 import  org.json.JSONException;
Represents JSON Web Encryption http://tools.ietf.org/html/draft-jones-json-web-encryption

Author(s):
anil saldhana
Since:
Jul 27, 2012
 
 public class JSONWebEncryption {
     protected JSONWebEncryptionHeader jsonWebEncryptionHeader;

    
Create an attached Header

Returns:
 
     public JSONWebEncryptionHeader createHeader() {
         if ( == null) {
              = new JSONWebEncryptionHeader();
         }
         return ;
     }

    
Get the JSONWebEncryptionHeader

Returns:
 
         return ;
     }

    
Set the JSONWebEncryptionHeader

Parameters:
jsonWebEncryptionHeader
 
     public void setJsonWebEncryptionHeader(JSONWebEncryptionHeader jsonWebEncryptionHeader) {
         this. = jsonWebEncryptionHeader;
     }

    
Encrypt

Parameters:
plainText
recipientPublicKey
Returns:
Throws:
ProcessingException
 
     public String encrypt(String plainTextPublicKey recipientPublicKeythrows ProcessingException {
         if ( == null) {
         }
         if (plainText == null) {
             throw ..invalidNullArgument("plainText");
         }
         if (recipientPublicKey == null) {
             throw ..invalidNullArgument("recipientPublicKey");
         }
         byte[] contentMasterKey = createContentMasterKey();
        return encrypt(plainTextrecipientPublicKeycontentMasterKey);
    }

    
Encrypt

Parameters:
plainText
recipientPublicKey
contentMasterKey
Returns:
Throws:
ProcessingException
    public String encrypt(String plainTextPublicKey recipientPublicKeybyte[] contentMasterKeythrows ProcessingException {
        if ( == null) {
        }
        if (plainText == null) {
            throw ..invalidNullArgument("plainText");
        }
        if (recipientPublicKey == null) {
            throw ..invalidNullArgument("recipientPublicKey");
        }
        if (contentMasterKey == null) {
            return encrypt(plainTextrecipientPublicKey);
        }
        SecretKey contentEncryptionKey = new SecretKeySpec(contentMasterKey.);
        // Encrypt using Recipient's public key to yield JWE Encrypted Key
        byte[] jweEncryptedKey = encryptKey(recipientPublicKeycontentMasterKey);
        String encodedJWEKey = PicketBoxJSONUtil.b64Encode(jweEncryptedKey);
        StringBuilder builder = new StringBuilder(PicketBoxJSONUtil.b64Encode(.toString()));
        builder.append();
        builder.append(encodedJWEKey);
        if (.needIntegrity()) {
            int cekLength = .getCEKLength();
            byte[] cek = generateCEK(contentEncryptionKey.getEncoded(), cekLength);
            // Deal with IV
            String iv;
            try {
                iv = .getDelegate().getString("iv");
            } catch (JSONException e) {
                throw ..ignorableError(e);
            }
            IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes());
            byte[] encryptedText = EncUtil.encryptUsingAES_CBC(plainTextcekivParameterSpec);
            String encodedJWEText = PicketBoxJSONUtil.b64Encode(encryptedText);
            builder.append();
            builder.append(encodedJWEText);
            int cikLength = .getCIKLength();
            byte[] cik = generateCIK(contentEncryptionKey.getEncoded(), cikLength);
            byte[] integrityValue = performMac(cikbuilder.toString().getBytes());
            String encodedIntegrityValue = PicketBoxJSONUtil.b64Encode(integrityValue);
            builder.append();
            builder.append(encodedIntegrityValue);
        } else {
            // Encrypt the plain text
            byte[] encryptedText = encryptText(plainTextrecipientPublicKey);
            String encodedJWEText = PicketBoxJSONUtil.b64Encode(encryptedText);
            builder.append();
            builder.append(encodedJWEText);
        }
        return builder.toString();
    }

    
Decrypt using a PrivateKey

Parameters:
encryptedText
privateKey
Returns:
Throws:
ProcessingException
    public String decrypt(String encryptedTextPrivateKey privateKeythrows ProcessingException {
        if (privateKey == null) {
            throw ..invalidNullArgument("privateKey");
        }
        try {
            String[] splitBits = encryptedText.split("\\.");
            int length = splitBits.length;
            String encodedHeader = splitBits[0];
            String encodedKey = splitBits[1];
            String encodedValue = splitBits[2];
            String encodedIntegrity = null;
            if (length == 4) {
                encodedIntegrity = splitBits[3];
            }
            String decodedHeader = new String(Base64.decode(encodedHeader));
            JSONWebEncryptionHeader header = new JSONWebEncryptionHeader();
            header.load(decodedHeader);
            if (header.needIntegrity()) {
                byte[] decodedKey = Base64.decode(encodedKey);
                byte[] secretKey = decryptKey(privateKeydecodedKey);
                int cekLength = header.getCEKLength();
                byte[] cek = generateCEK(secretKeycekLength);
                // Deal with IV
                String iv;
                try {
                    iv = header.getDelegate().getString("iv");
                } catch (JSONException e) {
                    throw ..ignorableError(e);
                }
                IvParameterSpec ivParameter = new IvParameterSpec(iv.getBytes());
                byte[] decodedText = Base64.decode(encodedValue);
                byte[] plainText = EncUtil.decryptUsingAES_CBC(decodedTextcekivParameter);
                int cikLength = header.getCIKLength();
                byte[] cik = generateCIK(secretKeycikLength);
                StringBuilder builder = new StringBuilder(PicketBoxJSONUtil.b64Encode(header.toString()));
                builder.append().append(encodedKey).append().append(encodedValue);
                byte[] integrityValue = performMac(cikbuilder.toString().getBytes());
                String encodedIntegrityValue = PicketBoxJSONUtil.b64Encode(integrityValue);
                if (byteEquals(encodedIntegrityValue.getBytes(), encodedIntegrity.getBytes())) {
                    return new String(plainText);
                } else {
                    throw new RuntimeException("Integrity Checks Failed");
                }
            }
            Cipher textCipher = header.getCipherBasedOnAlg();
            textCipher.init(.privateKey);
            byte[] decodedText = Base64.decode(encodedValue);
            byte[] plainText = textCipher.doFinal(decodedText);
            return new String(plainText);
        } catch (Exception e) {
            throw ..processingException(e);
        }
    }
    private byte[] encryptText(String plainTextPublicKey recipientPublicKeythrows ProcessingException {
        if (recipientPublicKey == null) {
            throw ..invalidNullArgument("recipientPublicKey");
        }
        try {
            Cipher cipher = .getCipherBasedOnAlg();
            cipher.init(.recipientPublicKey);
            return cipher.doFinal(plainText.getBytes());
        } catch (Exception e) {
            throw ..processingException(e);
        }
    }
    private byte[] encryptKey(PublicKey publicKeybyte[] contentMasterKeythrows ProcessingException {
        if (publicKey == null) {
            throw ..invalidNullArgument("publicKey");
        }
        try {
            Cipher cipher = .getCipherBasedOnAlg();
            cipher.init(.publicKey);
            return cipher.doFinal(contentMasterKey);
        } catch (Exception e) {
            throw ..processingException(e);
        }
    }
    private byte[] decryptKey(PrivateKey privateKeybyte[] encryptedKeythrows ProcessingException {
        if (privateKey == null) {
            throw ..invalidNullArgument("privateKey");
        }
        try {
            Cipher cipher = .getCipherBasedOnAlg();
            cipher.init(.privateKey);
            return cipher.doFinal(encryptedKey);
        } catch (Exception e) {
            throw ..processingException(e);
        }
    }

    
Generate a random byte array.

Returns:
    private byte[] createContentMasterKey() {
        return UUID.randomUUID().toString().getBytes();
    }

    
Content Integrity Key (CIK) A key used with a MAC function to ensure the integrity of the Ciphertext and the parameters used to create it.

Parameters:
keyBytes
cikByteLength
Returns:
Throws:
ProcessingException
    private byte[] generateCIK(byte[] keyBytesint cikByteLengththrows ProcessingException {
        // "Integrity"
        final byte[] otherInfo = { 73, 110, 116, 101, 103, 114, 105, 116, 121 };
        return kdfGen.concatKDF(keyBytescikByteLengthotherInfo);
    }

    
Content Encryption Key (CEK) A symmetric key used to encrypt the Plaintext for the recipient to produce the Ciphertext.

Parameters:
keyBytes
cekByteLength
Returns:
Throws:
ProcessingException
    private byte[] generateCEK(byte[] keyBytesint cekByteLengththrows ProcessingException {
        // "Encryption"
        final byte[] otherInfo = { 69, 110, 99, 114, 121, 112, 116, 105, 111, 110 };
        return kdfGen.concatKDF(keyBytescekByteLengthotherInfo);
    }
    private byte[] performMac(byte[] keybyte[] datathrows ProcessingException {
        Mac mac = null;
        try {
            mac.init(new SecretKeySpec(keymac.getAlgorithm()));
            mac.update(data);
            return mac.doFinal();
        } catch (Exception e) {
            throw ..processingException(e);
        }
    }
    private boolean byteEquals(byte[] b1byte[] b2) {
        // Check if the addresses match
        if (b1 == b2) {
            return true;
        }
        // Check if either one is null
        if (b1 == null || b2 == null) {
            return false;
        }
        // Match on the lengths
        if (b1.length != b2.length) {
            return false;
        }
        // Match each byte
        int notMatching = 0;
        for (int index = 0; index != b1.lengthindex++) {
            notMatching |= (b1[index] ^ b2[index]);
        }
        return notMatching == 0;
    }
New to GrepCode? Check out our FAQ X