View Javadoc
1   /*
2    * The contents of this file are subject to the terms of the Common Development and
3    * Distribution License (the License). You may not use this file except in compliance with the
4    * License.
5    *
6    * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
7    * specific language governing permission and limitations under the License.
8    *
9    * When distributing Covered Software, include this CDDL Header Notice in each file and include
10   * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
11   * Header, with the fields enclosed by brackets [] replaced by your own identifying
12   * information: "Portions copyright [year] [name of copyright owner]".
13   *
14   * Copyright 2015-2016 ForgeRock AS.
15   */
16  
17  package org.forgerock.json.jose.jwe.handlers.encryption;
18  
19  import static java.security.spec.MGF1ParameterSpec.SHA256;
20  import static javax.crypto.spec.PSource.PSpecified.DEFAULT;
21  import static org.forgerock.json.jose.jwe.JweAlgorithm.RSA_OAEP_256;
22  import static org.forgerock.json.jose.jwe.JweAlgorithmType.RSA;
23  import static org.forgerock.util.Reject.checkNotNull;
24  
25  import java.security.GeneralSecurityException;
26  import java.security.Key;
27  import java.security.interfaces.RSAPublicKey;
28  import java.security.spec.AlgorithmParameterSpec;
29  
30  import javax.crypto.Cipher;
31  import javax.crypto.spec.OAEPParameterSpec;
32  
33  import org.forgerock.json.jose.exceptions.JweDecryptionException;
34  import org.forgerock.json.jose.exceptions.JweEncryptionException;
35  import org.forgerock.json.jose.jwe.EncryptionMethod;
36  import org.forgerock.json.jose.jwe.JweAlgorithm;
37  import org.forgerock.json.jose.jwe.JweEncryption;
38  import org.forgerock.util.Reject;
39  
40  /**
41   * Abstract base class for implementations of the RSAES-PKCS1-v1_5 and RSA-OAEP encryption schemes.
42   *
43   * @see <a href="https://tools.ietf.org/html/rfc7518#section-4.2">RFC 7518 Section 4.2 and 4.3</a>
44   */
45  public final class RSAEncryptionHandler implements EncryptionHandler {
46      private static final OAEPParameterSpec RSA_OAEP_256_PARAMS = new OAEPParameterSpec("SHA-256", "MGF1", SHA256,
47              DEFAULT);
48      private final EncryptionMethod encryptionMethod;
49      private final ContentEncryptionHandler contentEncryptionHandler;
50      private final JweAlgorithm jweAlgorithm;
51      private final AlgorithmParameterSpec parameterSpec;
52  
53      /**
54       * Constructs a new RSAEncryptionHandler instance.
55       *
56       * @param encryptionMethod the content encryption method. Must not be null.
57       * @param jweAlgorithm the JWE algorithm. Must not be null. Must be an RSA encryption algorithm.
58       */
59      public RSAEncryptionHandler(EncryptionMethod encryptionMethod, final JweAlgorithm jweAlgorithm) {
60          this.encryptionMethod = checkNotNull(encryptionMethod, "EncryptionMethod must not be null");
61          this.jweAlgorithm = checkNotNull(jweAlgorithm, "JweAlgorithm must not be null");
62          Reject.ifFalse(jweAlgorithm.getAlgorithmType() == RSA, "JweAlgorithm type must be RSA");
63          this.contentEncryptionHandler = ContentEncryptionHandler.getInstance(encryptionMethod);
64          // RSA-OAEP-256 requires non-default algorithm parameters to conform to the JWE spec. The JRE defaults are
65          // correct for all other modes, so leave as null.
66          this.parameterSpec = jweAlgorithm == RSA_OAEP_256 ? RSA_OAEP_256_PARAMS : null;
67      }
68  
69      /**
70       * Creates a Content Encryption Key (CEK) by generating a random key value with a length equal to the
71       * EncryptionMethod A128CBC_HS256 key size.
72       * <p>
73       * See point 2 in <a href="http://tools.ietf.org/html/draft-ietf-jose-json-web-encryption-11#section-5.1">
74       *     Section 5.1</a> of the JWE Specification.
75       *
76       * @return {@inheritDoc}
77       */
78      @Override
79      public Key getContentEncryptionKey() {
80          return contentEncryptionHandler.generateEncryptionKey();
81      }
82  
83      /**
84       * Generates the JWE Encrypted Key by encrypting the Content Encryption Key (CEK) using the JweAlgorithm
85       * RSAES_PCKCS1_V1_5.
86       * <p>
87       * See point 4 in <a href="http://tools.ietf.org/html/draft-ietf-jose-json-web-encryption-11#section-5.1">
88       *     Section 5.1</a> of the JWE Specification.
89       *
90       * @param key {@inheritDoc}
91       * @param contentEncryptionKey {@inheritDoc}
92       * @return {@inheritDoc}
93       */
94      @Override
95      public byte[] generateJWEEncryptedKey(Key key, Key contentEncryptionKey) {
96          return encryptKey((RSAPublicKey) key, contentEncryptionKey);
97      }
98  
99      /**
100      * Generates a random JWE Initialisation Vector of the correct size for the encryption algorithm.
101      * <p>
102      * See points 9 in <a href="http://tools.ietf.org/html/draft-ietf-jose-json-web-encryption-11#section-5.1">
103      *     Section 5.1</a> of the JWE Specification.
104      *
105      * @return {@inheritDoc}
106      */
107     @Override
108     public byte[] generateInitialisationVector() {
109         return contentEncryptionHandler.generateInitialisationVector();
110     }
111 
112     /**
113      * {@inheritDoc}
114      */
115     @Override
116     public JweEncryption encryptPlaintext(Key contentEncryptionKey, byte[] initialisationVector, byte[] plaintext,
117                                           byte[] additionalAuthenticatedData) {
118 
119         return contentEncryptionHandler.encrypt(contentEncryptionKey, initialisationVector, plaintext,
120                 additionalAuthenticatedData);
121     }
122 
123     /**
124      * Decrypts the JWE Encrypted Key to produce the Content Encryption Key (CEK).
125      * <p>
126      * See points 10 in <a href="http://tools.ietf.org/html/draft-ietf-jose-json-web-encryption-11#section-5.2">
127      *     Section 5.2</a> of the JWE Specification.
128      *
129      * @param key {@inheritDoc}
130      * @param encryptedContentEncryptionKey {@inheritDoc}
131      * @return {@inheritDoc}
132      */
133     @Override
134     public Key decryptContentEncryptionKey(Key key, byte[] encryptedContentEncryptionKey) {
135         try {
136             final Cipher cipher = Cipher.getInstance(jweAlgorithm.getAlgorithm());
137             cipher.init(Cipher.UNWRAP_MODE, key, parameterSpec);
138             return cipher.unwrap(encryptedContentEncryptionKey, encryptionMethod.getEncryptionAlgorithm(),
139                     Cipher.SECRET_KEY);
140         } catch (GeneralSecurityException e) {
141             throw new JweDecryptionException();
142         }
143     }
144 
145     /**
146      * {@inheritDoc}
147      */
148     @Override
149     public byte[] decryptCiphertext(Key contentEncryptionKey, byte[] initialisationVector, byte[] ciphertext,
150                                     byte[] authenticationTag, byte[] additionalAuthenticatedData) {
151         return contentEncryptionHandler.decrypt(contentEncryptionKey, initialisationVector,
152                 new JweEncryption(ciphertext, authenticationTag), additionalAuthenticatedData);
153     }
154 
155     private byte[] encryptKey(final RSAPublicKey keyEncryptionKey, final Key contentKey) {
156         try {
157             final Cipher cipher = Cipher.getInstance(jweAlgorithm.getAlgorithm());
158             cipher.init(Cipher.WRAP_MODE, keyEncryptionKey, parameterSpec);
159             return cipher.wrap(contentKey);
160         } catch (GeneralSecurityException e) {
161             throw new JweEncryptionException(e);
162         }
163     }
164 }