http://git-wip-us.apache.org/repos/asf/cxf/blob/66a81773/rt/rs/security/jose/src/main/java/org/apache/cxf/rs/security/jose/jwe/JweEncryptionOutput.java ---------------------------------------------------------------------- diff --git a/rt/rs/security/jose/src/main/java/org/apache/cxf/rs/security/jose/jwe/JweEncryptionOutput.java b/rt/rs/security/jose/src/main/java/org/apache/cxf/rs/security/jose/jwe/JweEncryptionOutput.java deleted file mode 100644 index 5036887..0000000 --- a/rt/rs/security/jose/src/main/java/org/apache/cxf/rs/security/jose/jwe/JweEncryptionOutput.java +++ /dev/null @@ -1,78 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you 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 org.apache.cxf.rs.security.jose.jwe; - -import javax.crypto.Cipher; - -import org.apache.cxf.rt.security.crypto.KeyProperties; - -public class JweEncryptionOutput { - private Cipher cipher; - private JweHeaders headers; - private byte[] contentEncryptionKey; - private byte[] iv; - private AuthenticationTagProducer authTagProducer; - private byte[] encryptedContent; - private byte[] authTag; - private KeyProperties keyProps; - - //CHECKSTYLE:OFF - public JweEncryptionOutput(Cipher cipher, - JweHeaders headers, - byte[] contentEncryptionKey, - byte[] iv, - AuthenticationTagProducer authTagProducer, - KeyProperties keyProps, - byte[] encryptedContent, - byte[] authTag) { - //CHECKSTYLE:ON - this.cipher = cipher; - this.headers = headers; - this.contentEncryptionKey = contentEncryptionKey; - this.iv = iv; - this.authTagProducer = authTagProducer; - this.keyProps = keyProps; - this.encryptedContent = encryptedContent; - this.authTag = authTag; - } - public Cipher getCipher() { - return cipher; - } - public JweHeaders getHeaders() { - return headers; - } - public byte[] getContentEncryptionKey() { - return contentEncryptionKey; - } - public byte[] getIv() { - return iv; - } - public boolean isCompressionSupported() { - return keyProps.isCompressionSupported(); - } - public AuthenticationTagProducer getAuthTagProducer() { - return authTagProducer; - } - public byte[] getEncryptedContent() { - return encryptedContent; - } - public byte[] getAuthTag() { - return authTag; - } -}
http://git-wip-us.apache.org/repos/asf/cxf/blob/66a81773/rt/rs/security/jose/src/main/java/org/apache/cxf/rs/security/jose/jwe/JweEncryptionProvider.java ---------------------------------------------------------------------- diff --git a/rt/rs/security/jose/src/main/java/org/apache/cxf/rs/security/jose/jwe/JweEncryptionProvider.java b/rt/rs/security/jose/src/main/java/org/apache/cxf/rs/security/jose/jwe/JweEncryptionProvider.java deleted file mode 100644 index 615212b..0000000 --- a/rt/rs/security/jose/src/main/java/org/apache/cxf/rs/security/jose/jwe/JweEncryptionProvider.java +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you 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 org.apache.cxf.rs.security.jose.jwe; - - - -public interface JweEncryptionProvider extends JweKeyProperties { - /** - * JWE compact encryption - */ - String encrypt(byte[] jweContent, JweHeaders jweHeaders); - /** - * Prepare JWE state for completing either - * JWE compact or JSON encryption - */ - JweEncryptionOutput getEncryptionOutput(JweEncryptionInput jweInput); -} http://git-wip-us.apache.org/repos/asf/cxf/blob/66a81773/rt/rs/security/jose/src/main/java/org/apache/cxf/rs/security/jose/jwe/JweException.java ---------------------------------------------------------------------- diff --git a/rt/rs/security/jose/src/main/java/org/apache/cxf/rs/security/jose/jwe/JweException.java b/rt/rs/security/jose/src/main/java/org/apache/cxf/rs/security/jose/jwe/JweException.java deleted file mode 100644 index 6a6adc1..0000000 --- a/rt/rs/security/jose/src/main/java/org/apache/cxf/rs/security/jose/jwe/JweException.java +++ /dev/null @@ -1,53 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you 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 org.apache.cxf.rs.security.jose.jwe; - -import org.apache.cxf.rs.security.jose.JoseException; - -public class JweException extends JoseException { - - private static final long serialVersionUID = 4118589816228511524L; - private Error status; - public JweException(Error status) { - this(status, null); - } - public JweException(Error status, Throwable cause) { - super(cause); - this.status = status; - } - public Error getError() { - return status; - } - public enum Error { - NO_ENCRYPTOR, - NO_DECRYPTOR, - NO_INIT_PROPERTIES, - KEY_ALGORITHM_NOT_SET, - CUSTOM_IV_REUSED, - INVALID_KEY_ALGORITHM, - INVALID_CONTENT_ALGORITHM, - INVALID_CONTENT_KEY, - KEY_ENCRYPTION_FAILURE, - CONTENT_ENCRYPTION_FAILURE, - KEY_DECRYPTION_FAILURE, - CONTENT_DECRYPTION_FAILURE, - INVALID_COMPACT_JWE, - INVALID_JSON_JWE - } -} http://git-wip-us.apache.org/repos/asf/cxf/blob/66a81773/rt/rs/security/jose/src/main/java/org/apache/cxf/rs/security/jose/jwe/JweHeaders.java ---------------------------------------------------------------------- diff --git a/rt/rs/security/jose/src/main/java/org/apache/cxf/rs/security/jose/jwe/JweHeaders.java b/rt/rs/security/jose/src/main/java/org/apache/cxf/rs/security/jose/jwe/JweHeaders.java deleted file mode 100644 index be28f1c..0000000 --- a/rt/rs/security/jose/src/main/java/org/apache/cxf/rs/security/jose/jwe/JweHeaders.java +++ /dev/null @@ -1,118 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you 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 org.apache.cxf.rs.security.jose.jwe; - -import java.util.Map; - -import org.apache.cxf.common.util.Base64UrlUtility; -import org.apache.cxf.common.util.StringUtils; -import org.apache.cxf.jaxrs.provider.json.JsonMapObjectReaderWriter; -import org.apache.cxf.rs.security.jose.JoseConstants; -import org.apache.cxf.rs.security.jose.JoseHeaders; -import org.apache.cxf.rs.security.jose.JoseType; -import org.apache.cxf.rs.security.jose.jwa.ContentAlgorithm; -import org.apache.cxf.rs.security.jose.jwa.KeyAlgorithm; - - - - -public class JweHeaders extends JoseHeaders { - private JweHeaders protectedHeaders; - public JweHeaders() { - } - public JweHeaders(JoseType type) { - super(type); - } - public JweHeaders(JoseHeaders headers) { - super(headers.asMap()); - } - - public JweHeaders(Map<String, Object> values) { - super(values); - } - public JweHeaders(KeyAlgorithm keyEncAlgo, ContentAlgorithm ctEncAlgo) { - this(keyEncAlgo, ctEncAlgo, false); - } - public JweHeaders(ContentAlgorithm ctEncAlgo) { - this(null, ctEncAlgo, false); - } - public JweHeaders(ContentAlgorithm ctEncAlgo, boolean deflate) { - this(null, ctEncAlgo, deflate); - } - public JweHeaders(KeyAlgorithm keyEncAlgo, ContentAlgorithm ctEncAlgo, boolean deflate) { - init(keyEncAlgo, ctEncAlgo, deflate); - } - private void init(KeyAlgorithm keyEncAlgo, ContentAlgorithm ctEncAlgo, boolean deflate) { - if (keyEncAlgo != null) { - setKeyEncryptionAlgorithm(keyEncAlgo); - } - setContentEncryptionAlgorithm(ctEncAlgo); - if (deflate) { - setZipAlgorithm(JoseConstants.JWE_DEFLATE_ZIP_ALGORITHM); - } - } - - public void setKeyEncryptionAlgorithm(KeyAlgorithm algo) { - super.setAlgorithm(algo.getJwaName()); - } - - public KeyAlgorithm getKeyEncryptionAlgorithm() { - String algo = super.getAlgorithm(); - return algo == null ? null : KeyAlgorithm.getAlgorithm(algo); - } - - public void setContentEncryptionAlgorithm(ContentAlgorithm algo) { - setHeader(JoseConstants.JWE_HEADER_CONTENT_ENC_ALGORITHM, algo.getJwaName()); - } - - public ContentAlgorithm getContentEncryptionAlgorithm() { - Object prop = getHeader(JoseConstants.JWE_HEADER_CONTENT_ENC_ALGORITHM); - return prop == null ? null : ContentAlgorithm.getAlgorithm(prop.toString()); - } - - public void setZipAlgorithm(String type) { - setHeader(JoseConstants.JWE_HEADER_ZIP_ALGORITHM, type); - } - - public String getZipAlgorithm() { - return (String)getHeader(JoseConstants.JWE_HEADER_ZIP_ALGORITHM); - } - - @Override - public JoseHeaders setHeader(String name, Object value) { - return (JoseHeaders)super.setHeader(name, value); - } - public byte[] toCipherAdditionalAuthData() { - return toCipherAdditionalAuthData(new JsonMapObjectReaderWriter().toJson(this)); - } - public static byte[] toCipherAdditionalAuthData(String headersJson) { - byte[] headerBytes = StringUtils.toBytesUTF8(headersJson); - String base64UrlHeadersInJson = Base64UrlUtility.encode(headerBytes); - return StringUtils.toBytesASCII(base64UrlHeadersInJson); - } - - public JweHeaders getProtectedHeaders() { - return protectedHeaders; - } - - public void setProtectedHeaders(JweHeaders protectedHeaders) { - this.protectedHeaders = protectedHeaders; - } -} http://git-wip-us.apache.org/repos/asf/cxf/blob/66a81773/rt/rs/security/jose/src/main/java/org/apache/cxf/rs/security/jose/jwe/JweJsonConsumer.java ---------------------------------------------------------------------- diff --git a/rt/rs/security/jose/src/main/java/org/apache/cxf/rs/security/jose/jwe/JweJsonConsumer.java b/rt/rs/security/jose/src/main/java/org/apache/cxf/rs/security/jose/jwe/JweJsonConsumer.java deleted file mode 100644 index 0a86a14..0000000 --- a/rt/rs/security/jose/src/main/java/org/apache/cxf/rs/security/jose/jwe/JweJsonConsumer.java +++ /dev/null @@ -1,191 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you 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 org.apache.cxf.rs.security.jose.jwe; - -import java.io.UnsupportedEncodingException; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.logging.Logger; - -import org.apache.cxf.common.logging.LogUtils; -import org.apache.cxf.helpers.CastUtils; -import org.apache.cxf.jaxrs.provider.json.JsonMapObjectReaderWriter; -import org.apache.cxf.rs.security.jose.JoseException; -import org.apache.cxf.rs.security.jose.JoseUtils; -import org.apache.cxf.rs.security.jose.jwa.KeyAlgorithm; - -public class JweJsonConsumer { - protected static final Logger LOG = LogUtils.getL7dLogger(JweJsonConsumer.class); - private String protectedHeaderJson; - private JweHeaders protectedHeaderJwe; - private JweHeaders sharedUnprotectedHeader; - private List<JweJsonEncryptionEntry> recipients = new LinkedList<JweJsonEncryptionEntry>(); - private Map<JweJsonEncryptionEntry, JweHeaders> recipientsMap = - new LinkedHashMap<JweJsonEncryptionEntry, JweHeaders>(); - private byte[] aad; - private byte[] iv; - private byte[] cipherBytes; - private byte[] authTag; - - private JsonMapObjectReaderWriter reader = new JsonMapObjectReaderWriter(); - - public JweJsonConsumer(String payload) { - prepare(payload); - } - - public JweDecryptionOutput decryptWith(JweDecryptionProvider jwe) { - JweJsonEncryptionEntry entry = getJweDecryptionEntry(jwe); - return decryptWith(jwe, entry); - } - public JweDecryptionOutput decryptWith(JweDecryptionProvider jwe, JweJsonEncryptionEntry entry) { - JweDecryptionInput jweDecryptionInput = getJweDecryptionInput(jwe, entry); - byte[] content = jwe.decrypt(jweDecryptionInput); - return new JweDecryptionOutput(jweDecryptionInput.getJweHeaders(), content); - } - - private JweDecryptionInput getJweDecryptionInput(JweDecryptionProvider jwe, JweJsonEncryptionEntry entry) { - if (entry == null) { - LOG.warning("JWE JSON Entry is not available"); - throw new JweException(JweException.Error.INVALID_JSON_JWE); - } - JweHeaders unionHeaders = recipientsMap.get(entry); - if (unionHeaders == null) { - LOG.warning("JWE JSON Entry union headers are not available"); - throw new JweException(JweException.Error.INVALID_JSON_JWE); - } - JweDecryptionInput input = new JweDecryptionInput(entry.getEncryptedKey(), - iv, - cipherBytes, - authTag, - aad, - protectedHeaderJson, - unionHeaders); - return input; - } - - private JweJsonEncryptionEntry getJweDecryptionEntry(JweDecryptionProvider jwe) { - for (Map.Entry<JweJsonEncryptionEntry, JweHeaders> entry : recipientsMap.entrySet()) { - KeyAlgorithm keyAlgo = entry.getValue().getKeyEncryptionAlgorithm(); - if (keyAlgo != null && keyAlgo.equals(jwe.getKeyAlgorithm()) - || keyAlgo == null && jwe.getKeyAlgorithm() == null) { - return entry.getKey(); - } - } - return null; - } - - private void prepare(String payload) { - Map<String, Object> jsonObjectMap = reader.fromJson(payload); - String encodedProtectedHeader = (String)jsonObjectMap.get("protected"); - if (encodedProtectedHeader != null) { - protectedHeaderJson = JoseUtils.decodeToString(encodedProtectedHeader); - protectedHeaderJwe = - new JweHeaders(reader.fromJson(protectedHeaderJson)); - } - Map<String, Object> unprotectedHeader = CastUtils.cast((Map<?, ?>)jsonObjectMap.get("unprotected")); - sharedUnprotectedHeader = unprotectedHeader == null ? null : new JweHeaders(unprotectedHeader); - List<Map<String, Object>> encryptionArray = CastUtils.cast((List<?>)jsonObjectMap.get("recipients")); - if (encryptionArray != null) { - if (jsonObjectMap.containsKey("encryption_key")) { - LOG.warning("JWE JSON encryption_key is missing"); - throw new JweException(JweException.Error.INVALID_JSON_JWE); - } - for (Map<String, Object> encryptionEntry : encryptionArray) { - this.recipients.add(getEncryptionObject(encryptionEntry)); - } - } else { - this.recipients.add(getEncryptionObject(jsonObjectMap)); - } - aad = getDecodedBytes(jsonObjectMap, "aad"); - cipherBytes = getDecodedBytes(jsonObjectMap, "ciphertext"); - iv = getDecodedBytes(jsonObjectMap, "iv"); - authTag = getDecodedBytes(jsonObjectMap, "tag"); - } - protected JweJsonEncryptionEntry getEncryptionObject(Map<String, Object> encryptionEntry) { - Map<String, Object> header = CastUtils.cast((Map<?, ?>)encryptionEntry.get("header")); - JweHeaders recipientUnprotected = header == null ? null : new JweHeaders(header); - String encodedKey = (String)encryptionEntry.get("encrypted_key"); - JweJsonEncryptionEntry entry = new JweJsonEncryptionEntry(recipientUnprotected, encodedKey); - - JweHeaders unionHeaders = new JweHeaders(); - if (protectedHeaderJwe != null) { - unionHeaders.asMap().putAll(protectedHeaderJwe.asMap()); - unionHeaders.setProtectedHeaders(protectedHeaderJwe); - } - if (sharedUnprotectedHeader != null) { - if (!Collections.disjoint(unionHeaders.asMap().keySet(), - sharedUnprotectedHeader.asMap().keySet())) { - LOG.warning("Protected and unprotected headers have duplicate values"); - throw new JweException(JweException.Error.INVALID_JSON_JWE); - } - unionHeaders.asMap().putAll(sharedUnprotectedHeader.asMap()); - } - if (recipientUnprotected != null) { - if (!Collections.disjoint(unionHeaders.asMap().keySet(), - recipientUnprotected.asMap().keySet())) { - LOG.warning("Union and recipient unprotected headers have duplicate values"); - throw new JweException(JweException.Error.INVALID_JSON_JWE); - } - unionHeaders.asMap().putAll(recipientUnprotected.asMap()); - } - - recipientsMap.put(entry, unionHeaders); - return entry; - - } - protected byte[] getDecodedBytes(Map<String, Object> map, String name) { - String value = (String)map.get(name); - if (value != null) { - return JoseUtils.decode(value); - } - return null; - } - - public JweHeaders getProtectedHeader() { - return protectedHeaderJwe; - } - - public JweHeaders getSharedUnprotectedHeader() { - return sharedUnprotectedHeader; - } - - public byte[] getAad() { - return aad; - } - public String getAadText() { - if (aad == null) { - return null; - } - try { - return new String(aad, "UTF-8"); - } catch (UnsupportedEncodingException ex) { - throw new JoseException(ex); - } - } - public List<JweJsonEncryptionEntry> getRecipients() { - return recipients; - } - - public Map<JweJsonEncryptionEntry, JweHeaders> getRecipientsMap() { - return recipientsMap; - } -} http://git-wip-us.apache.org/repos/asf/cxf/blob/66a81773/rt/rs/security/jose/src/main/java/org/apache/cxf/rs/security/jose/jwe/JweJsonEncryptionEntry.java ---------------------------------------------------------------------- diff --git a/rt/rs/security/jose/src/main/java/org/apache/cxf/rs/security/jose/jwe/JweJsonEncryptionEntry.java b/rt/rs/security/jose/src/main/java/org/apache/cxf/rs/security/jose/jwe/JweJsonEncryptionEntry.java deleted file mode 100644 index caa6d9f..0000000 --- a/rt/rs/security/jose/src/main/java/org/apache/cxf/rs/security/jose/jwe/JweJsonEncryptionEntry.java +++ /dev/null @@ -1,60 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you 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 org.apache.cxf.rs.security.jose.jwe; - -import java.util.LinkedHashMap; -import java.util.Map; - -import org.apache.cxf.jaxrs.provider.json.JsonMapObjectReaderWriter; -import org.apache.cxf.rs.security.jose.JoseUtils; - -public class JweJsonEncryptionEntry { - private JweHeaders unprotectedHeader; - private String encodedEncryptedKey; - public JweJsonEncryptionEntry(String encodedEncryptedKey) { - this(null, encodedEncryptedKey); - } - public JweJsonEncryptionEntry(JweHeaders unprotectedHeader, String encodedEncryptedKey) { - this.unprotectedHeader = unprotectedHeader; - this.encodedEncryptedKey = encodedEncryptedKey; - } - public JweHeaders getUnprotectedHeader() { - return unprotectedHeader; - } - public String getEncodedEncryptedKey() { - return encodedEncryptedKey; - } - public byte[] getEncryptedKey() { - return encodedEncryptedKey == null ? null : JoseUtils.decode(encodedEncryptedKey); - } - public String toJson() { - JsonMapObjectReaderWriter jsonWriter = new JsonMapObjectReaderWriter(); - Map<String, Object> recipientsEntry = new LinkedHashMap<String, Object>(); - if (unprotectedHeader != null) { - recipientsEntry.put("header", this.unprotectedHeader); - } - if (encodedEncryptedKey != null) { - recipientsEntry.put("encrypted_key", this.encodedEncryptedKey); - } - return jsonWriter.toJson(recipientsEntry); - } - public String toString() { - return toJson(); - } -} http://git-wip-us.apache.org/repos/asf/cxf/blob/66a81773/rt/rs/security/jose/src/main/java/org/apache/cxf/rs/security/jose/jwe/JweJsonProducer.java ---------------------------------------------------------------------- diff --git a/rt/rs/security/jose/src/main/java/org/apache/cxf/rs/security/jose/jwe/JweJsonProducer.java b/rt/rs/security/jose/src/main/java/org/apache/cxf/rs/security/jose/jwe/JweJsonProducer.java deleted file mode 100644 index ba5365e..0000000 --- a/rt/rs/security/jose/src/main/java/org/apache/cxf/rs/security/jose/jwe/JweJsonProducer.java +++ /dev/null @@ -1,192 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you 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 org.apache.cxf.rs.security.jose.jwe; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.logging.Logger; - -import org.apache.cxf.common.logging.LogUtils; -import org.apache.cxf.common.util.Base64UrlUtility; -import org.apache.cxf.jaxrs.provider.json.JsonMapObjectReaderWriter; -import org.apache.cxf.rs.security.jose.JoseConstants; - -public class JweJsonProducer { - protected static final Logger LOG = LogUtils.getL7dLogger(JweJsonProducer.class); - private JsonMapObjectReaderWriter writer = new JsonMapObjectReaderWriter(); - private JweHeaders protectedHeader; - private JweHeaders unprotectedHeader; - private byte[] content; - private byte[] aad; - private boolean canBeFlat; - public JweJsonProducer(JweHeaders protectedHeader, byte[] content) { - this(protectedHeader, content, false); - } - public JweJsonProducer(JweHeaders protectedHeader, byte[] content, boolean canBeFlat) { - this(protectedHeader, content, null, canBeFlat); - } - public JweJsonProducer(JweHeaders protectedHeader, byte[] content, byte[] aad, boolean canBeFlat) { - this.protectedHeader = protectedHeader; - this.content = content; - this.aad = aad; - this.canBeFlat = canBeFlat; - } - public JweJsonProducer(JweHeaders protectedHeader, - JweHeaders unprotectedHeader, - byte[] content, - byte[] aad, - boolean canBeFlat) { - this(protectedHeader, content, aad, canBeFlat); - this.unprotectedHeader = unprotectedHeader; - } - public String encryptWith(JweEncryptionProvider encryptor) { - return encryptWith(Collections.singletonList(encryptor), null); - } - public String encryptWith(JweEncryptionProvider encryptor, JweHeaders recipientUnprotected) { - return encryptWith(Collections.singletonList(encryptor), - Collections.singletonList(recipientUnprotected)); - } - public String encryptWith(List<JweEncryptionProvider> encryptors) { - return encryptWith(encryptors, null); - } - public String encryptWith(List<JweEncryptionProvider> encryptors, - List<JweHeaders> recipientUnprotected) { - checkAndGetContentAlgorithm(encryptors); - if (recipientUnprotected != null - && recipientUnprotected.size() != encryptors.size()) { - throw new IllegalArgumentException(); - } - JweHeaders unionHeaders = new JweHeaders(); - if (protectedHeader != null) { - unionHeaders.asMap().putAll(protectedHeader.asMap()); - } - if (unprotectedHeader != null) { - if (!Collections.disjoint(unionHeaders.asMap().keySet(), - unprotectedHeader.asMap().keySet())) { - LOG.warning("Protected and unprotected headers have duplicate values"); - throw new JweException(JweException.Error.INVALID_JSON_JWE); - } - checkCriticalHeaders(unprotectedHeader); - unionHeaders.asMap().putAll(unprotectedHeader.asMap()); - } - - List<JweJsonEncryptionEntry> entries = new ArrayList<JweJsonEncryptionEntry>(encryptors.size()); - Map<String, Object> jweJsonMap = new LinkedHashMap<String, Object>(); - byte[] cipherText = null; - byte[] authTag = null; - byte[] iv = null; - for (int i = 0; i < encryptors.size(); i++) { - JweEncryptionProvider encryptor = encryptors.get(i); - JweHeaders perRecipientUnprotected = - recipientUnprotected == null ? null : recipientUnprotected.get(i); - JweHeaders jsonHeaders = null; - if (perRecipientUnprotected != null) { - checkCriticalHeaders(perRecipientUnprotected); - if (!Collections.disjoint(unionHeaders.asMap().keySet(), - perRecipientUnprotected.asMap().keySet())) { - LOG.warning("union and recipient unprotected headers have duplicate values"); - throw new JweException(JweException.Error.INVALID_JSON_JWE); - } - jsonHeaders = new JweHeaders(unionHeaders.asMap()); - jsonHeaders.asMap().putAll(perRecipientUnprotected.asMap()); - } else { - jsonHeaders = unionHeaders; - } - jsonHeaders.setProtectedHeaders(protectedHeader); - - JweEncryptionInput input = createEncryptionInput(jsonHeaders); - if (i > 0) { - input.setContent(null); - } - JweEncryptionOutput state = encryptor.getEncryptionOutput(input); - byte[] currentCipherText = state.getEncryptedContent(); - byte[] currentAuthTag = state.getAuthTag(); - byte[] currentIv = state.getIv(); - if (cipherText == null) { - cipherText = currentCipherText; - } - if (authTag == null) { - authTag = currentAuthTag; - } - if (iv == null) { - iv = currentIv; - } - - byte[] encryptedCek = state.getContentEncryptionKey(); - if (encryptedCek.length == 0 && encryptor.getKeyAlgorithm() != null) { - LOG.warning("Unexpected key encryption algorithm"); - throw new JweException(JweException.Error.INVALID_JSON_JWE); - } - String encodedCek = encryptedCek.length == 0 ? null : Base64UrlUtility.encode(encryptedCek); - entries.add(new JweJsonEncryptionEntry(perRecipientUnprotected, encodedCek)); - - } - if (protectedHeader != null) { - jweJsonMap.put("protected", - Base64UrlUtility.encode(writer.toJson(protectedHeader))); - } - if (unprotectedHeader != null) { - jweJsonMap.put("unprotected", unprotectedHeader); - } - if (entries.size() == 1 && canBeFlat) { - JweHeaders unprotectedEntryHeader = entries.get(0).getUnprotectedHeader(); - if (unprotectedEntryHeader != null) { - jweJsonMap.put("header", unprotectedEntryHeader); - } - String encryptedKey = entries.get(0).getEncodedEncryptedKey(); - if (encryptedKey != null) { - jweJsonMap.put("encrypted_key", encryptedKey); - } - } else { - jweJsonMap.put("recipients", entries); - } - if (aad != null) { - jweJsonMap.put("aad", Base64UrlUtility.encode(aad)); - } - jweJsonMap.put("iv", Base64UrlUtility.encode(iv)); - jweJsonMap.put("ciphertext", Base64UrlUtility.encode(cipherText)); - jweJsonMap.put("tag", Base64UrlUtility.encode(authTag)); - return writer.toJson(jweJsonMap); - } - protected JweEncryptionInput createEncryptionInput(JweHeaders jsonHeaders) { - return new JweEncryptionInput(jsonHeaders, content, aad); - } - private String checkAndGetContentAlgorithm(List<JweEncryptionProvider> encryptors) { - Set<String> set = new HashSet<String>(); - for (JweEncryptionProvider encryptor : encryptors) { - set.add(encryptor.getContentAlgorithm().getJwaName()); - } - if (set.size() != 1) { - LOG.warning("Invalid content encryption algorithm"); - throw new JweException(JweException.Error.INVALID_CONTENT_ALGORITHM); - } - return set.iterator().next(); - } - private static void checkCriticalHeaders(JweHeaders unprotected) { - if (unprotected.asMap().containsKey(JoseConstants.HEADER_CRITICAL)) { - LOG.warning("Unprotected headers contain critical headers"); - throw new JweException(JweException.Error.INVALID_JSON_JWE); - } - } -} http://git-wip-us.apache.org/repos/asf/cxf/blob/66a81773/rt/rs/security/jose/src/main/java/org/apache/cxf/rs/security/jose/jwe/JweJwtCompactConsumer.java ---------------------------------------------------------------------- diff --git a/rt/rs/security/jose/src/main/java/org/apache/cxf/rs/security/jose/jwe/JweJwtCompactConsumer.java b/rt/rs/security/jose/src/main/java/org/apache/cxf/rs/security/jose/jwe/JweJwtCompactConsumer.java deleted file mode 100644 index d7a76b9..0000000 --- a/rt/rs/security/jose/src/main/java/org/apache/cxf/rs/security/jose/jwe/JweJwtCompactConsumer.java +++ /dev/null @@ -1,63 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you 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 org.apache.cxf.rs.security.jose.jwe; -import java.security.interfaces.RSAPrivateKey; - -import javax.crypto.SecretKey; - -import org.apache.cxf.rs.security.jose.jwk.JsonWebKey; -import org.apache.cxf.rs.security.jose.jwt.JwtClaims; -import org.apache.cxf.rs.security.jose.jwt.JwtToken; -import org.apache.cxf.rs.security.jose.jwt.JwtTokenReaderWriter; - - -public class JweJwtCompactConsumer { - private JweCompactConsumer jweConsumer; - private JweHeaders headers; - public JweJwtCompactConsumer(String content) { - jweConsumer = new JweCompactConsumer(content); - headers = jweConsumer.getJweHeaders(); - } - public JwtToken decryptWith(JsonWebKey key) { - return decryptWith(JweUtils.createJweDecryptionProvider(key, - headers.getContentEncryptionAlgorithm())); - } - public JwtToken decryptWith(RSAPrivateKey key) { - return decryptWith(JweUtils.createJweDecryptionProvider(key, - headers.getKeyEncryptionAlgorithm(), - headers.getContentEncryptionAlgorithm())); - } - public JwtToken decryptWith(SecretKey key) { - return decryptWith(JweUtils.createJweDecryptionProvider(key, - headers.getKeyEncryptionAlgorithm(), - headers.getContentEncryptionAlgorithm())); - } - public JwtToken decryptWith(JweDecryptionProvider jwe) { - byte[] bytes = jwe.decrypt(jweConsumer.getJweDecryptionInput()); - JwtClaims claims = new JwtTokenReaderWriter().fromJsonClaims(toString(bytes)); - return new JwtToken(headers, claims); - } - private static String toString(byte[] bytes) { - try { - return new String(bytes, "UTF-8"); - } catch (Exception ex) { - throw new RuntimeException(ex); - } - } -} http://git-wip-us.apache.org/repos/asf/cxf/blob/66a81773/rt/rs/security/jose/src/main/java/org/apache/cxf/rs/security/jose/jwe/JweJwtCompactProducer.java ---------------------------------------------------------------------- diff --git a/rt/rs/security/jose/src/main/java/org/apache/cxf/rs/security/jose/jwe/JweJwtCompactProducer.java b/rt/rs/security/jose/src/main/java/org/apache/cxf/rs/security/jose/jwe/JweJwtCompactProducer.java deleted file mode 100644 index 98702b4..0000000 --- a/rt/rs/security/jose/src/main/java/org/apache/cxf/rs/security/jose/jwe/JweJwtCompactProducer.java +++ /dev/null @@ -1,60 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you 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 org.apache.cxf.rs.security.jose.jwe; -import java.security.interfaces.RSAPublicKey; - -import javax.crypto.SecretKey; - -import org.apache.cxf.common.util.StringUtils; -import org.apache.cxf.rs.security.jose.jwk.JsonWebKey; -import org.apache.cxf.rs.security.jose.jwt.JwtClaims; -import org.apache.cxf.rs.security.jose.jwt.JwtToken; -import org.apache.cxf.rs.security.jose.jwt.JwtUtils; - - -public class JweJwtCompactProducer { - private JweHeaders headers; - private String claimsJson; - public JweJwtCompactProducer(JwtToken token) { - this(new JweHeaders(token.getHeaders()), token.getClaims()); - } - public JweJwtCompactProducer(JwtClaims claims) { - this(new JweHeaders(), claims); - } - public JweJwtCompactProducer(JweHeaders joseHeaders, JwtClaims claims) { - headers = new JweHeaders(joseHeaders); - claimsJson = JwtUtils.claimsToJson(claims); - } - - public String encryptWith(JsonWebKey key) { - JweEncryptionProvider jwe = JweUtils.createJweEncryptionProvider(key, headers); - return encryptWith(jwe); - } - public String encryptWith(RSAPublicKey key) { - JweEncryptionProvider jwe = JweUtils.createJweEncryptionProvider(key, headers); - return encryptWith(jwe); - } - public String encryptWith(SecretKey key) { - JweEncryptionProvider jwe = JweUtils.createJweEncryptionProvider(key, headers); - return encryptWith(jwe); - } - public String encryptWith(JweEncryptionProvider jwe) { - return jwe.encrypt(StringUtils.toBytesUTF8(claimsJson), headers); - } -} http://git-wip-us.apache.org/repos/asf/cxf/blob/66a81773/rt/rs/security/jose/src/main/java/org/apache/cxf/rs/security/jose/jwe/JweKeyProperties.java ---------------------------------------------------------------------- diff --git a/rt/rs/security/jose/src/main/java/org/apache/cxf/rs/security/jose/jwe/JweKeyProperties.java b/rt/rs/security/jose/src/main/java/org/apache/cxf/rs/security/jose/jwe/JweKeyProperties.java deleted file mode 100644 index 49d274c..0000000 --- a/rt/rs/security/jose/src/main/java/org/apache/cxf/rs/security/jose/jwe/JweKeyProperties.java +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you 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 org.apache.cxf.rs.security.jose.jwe; - -import org.apache.cxf.rs.security.jose.jwa.ContentAlgorithm; -import org.apache.cxf.rs.security.jose.jwa.KeyAlgorithm; - - - -public interface JweKeyProperties { - KeyAlgorithm getKeyAlgorithm(); - ContentAlgorithm getContentAlgorithm(); -} http://git-wip-us.apache.org/repos/asf/cxf/blob/66a81773/rt/rs/security/jose/src/main/java/org/apache/cxf/rs/security/jose/jwe/JweOutputStream.java ---------------------------------------------------------------------- diff --git a/rt/rs/security/jose/src/main/java/org/apache/cxf/rs/security/jose/jwe/JweOutputStream.java b/rt/rs/security/jose/src/main/java/org/apache/cxf/rs/security/jose/jwe/JweOutputStream.java deleted file mode 100644 index 1a0447d..0000000 --- a/rt/rs/security/jose/src/main/java/org/apache/cxf/rs/security/jose/jwe/JweOutputStream.java +++ /dev/null @@ -1,148 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you 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 org.apache.cxf.rs.security.jose.jwe; - -import java.io.FilterOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.nio.ByteBuffer; -import java.util.logging.Logger; - -import javax.crypto.Cipher; - -import org.apache.cxf.common.logging.LogUtils; -import org.apache.cxf.common.util.Base64UrlUtility; - -public class JweOutputStream extends FilterOutputStream { - protected static final Logger LOG = LogUtils.getL7dLogger(JweOutputStream.class); - private Cipher encryptingCipher; - private int blockSize; - private AuthenticationTagProducer authTagProducer; - private byte[] lastRawDataChunk; - private byte[] lastEncryptedDataChunk; - private boolean flushed; - public JweOutputStream(OutputStream out, - Cipher encryptingCipher, - AuthenticationTagProducer authTagProducer) { - super(out); - this.encryptingCipher = encryptingCipher; - this.blockSize = encryptingCipher.getBlockSize(); - this.authTagProducer = authTagProducer; - } - - @Override - public void write(int value) throws IOException { - byte[] bytes = ByteBuffer.allocate(Integer.SIZE / 8).putInt(value).array(); - write(bytes, 0, bytes.length); - } - - @Override - public void write(byte b[], int off, int len) throws IOException { - if (lastRawDataChunk != null) { - int remaining = blockSize - lastRawDataChunk.length; - int lenToCopy = remaining < len ? remaining : len; - lastRawDataChunk = newArray(lastRawDataChunk, 0, lastRawDataChunk.length, b, off, lenToCopy); - off = off + lenToCopy; - len -= lenToCopy; - if (lastRawDataChunk.length < blockSize) { - return; - } else { - encryptAndWrite(lastRawDataChunk, 0, lastRawDataChunk.length); - lastRawDataChunk = null; - } - } - int offset = 0; - int chunkSize = blockSize > len ? blockSize : blockSize * (len / blockSize); - for (; offset + chunkSize <= len; offset += chunkSize, off += chunkSize) { - encryptAndWrite(b, off, chunkSize); - } - if (offset < len) { - lastRawDataChunk = newArray(b, off, len - offset); - } - - } - - private void encryptAndWrite(byte[] chunk, int off, int len) throws IOException { - byte[] encrypted = encryptingCipher.update(chunk, off, len); - if (authTagProducer != null) { - authTagProducer.update(encrypted, 0, encrypted.length); - } - encodeAndWrite(encrypted, 0, encrypted.length, false); - } - private void encodeAndWrite(byte[] encryptedChunk, int off, int len, boolean finalWrite) throws IOException { - byte[] theChunk = lastEncryptedDataChunk; - int lenToEncode = len; - if (theChunk != null) { - theChunk = newArray(theChunk, 0, theChunk.length, encryptedChunk, off, len); - lenToEncode = theChunk.length; - off = 0; - } else { - theChunk = encryptedChunk; - } - int rem = finalWrite ? 0 : lenToEncode % 3; - Base64UrlUtility.encodeAndStream(theChunk, off, lenToEncode - rem, out); - out.flush(); - if (rem > 0) { - lastEncryptedDataChunk = newArray(theChunk, lenToEncode - rem, rem); - } else { - lastEncryptedDataChunk = null; - } - } - - public void finalFlush() throws IOException { - if (flushed) { - return; - } - try { - byte[] finalBytes = lastRawDataChunk == null - ? encryptingCipher.doFinal() - : encryptingCipher.doFinal(lastRawDataChunk, 0, lastRawDataChunk.length); - final int authTagLengthBits = 128; - if (authTagProducer != null) { - authTagProducer.update(finalBytes, 0, finalBytes.length); - encodeAndWrite(finalBytes, 0, finalBytes.length, true); - } else { - encodeAndWrite(finalBytes, 0, finalBytes.length - authTagLengthBits / 8, true); - } - out.write(new byte[]{'.'}); - - if (authTagProducer == null) { - encodeAndWrite(finalBytes, finalBytes.length - authTagLengthBits / 8, authTagLengthBits / 8, true); - } else { - byte[] authTag = authTagProducer.getTag(); - encodeAndWrite(authTag, 0, authTagLengthBits / 8, true); - } - } catch (Exception ex) { - LOG.warning("Content encryption failure"); - throw new JweException(JweException.Error.CONTENT_ENCRYPTION_FAILURE, ex); - } - flushed = true; - } - private byte[] newArray(byte[] src, int srcPos, int srcLen) { - byte[] buf = new byte[srcLen]; - System.arraycopy(src, srcPos, buf, 0, srcLen); - return buf; - } - private byte[] newArray(byte[] src, int srcPos, int srcLen, byte[] src2, int srcPos2, int srcLen2) { - byte[] buf = new byte[srcLen + srcLen2]; - System.arraycopy(src, srcPos, buf, 0, srcLen); - System.arraycopy(src2, srcPos2, buf, srcLen, srcLen2); - return buf; - } -} http://git-wip-us.apache.org/repos/asf/cxf/blob/66a81773/rt/rs/security/jose/src/main/java/org/apache/cxf/rs/security/jose/jwe/JweUtils.java ---------------------------------------------------------------------- diff --git a/rt/rs/security/jose/src/main/java/org/apache/cxf/rs/security/jose/jwe/JweUtils.java b/rt/rs/security/jose/src/main/java/org/apache/cxf/rs/security/jose/jwe/JweUtils.java deleted file mode 100644 index 984d15b..0000000 --- a/rt/rs/security/jose/src/main/java/org/apache/cxf/rs/security/jose/jwe/JweUtils.java +++ /dev/null @@ -1,634 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you 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 org.apache.cxf.rs.security.jose.jwe; - -import java.nio.ByteBuffer; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.cert.X509Certificate; -import java.security.interfaces.ECPrivateKey; -import java.security.interfaces.ECPublicKey; -import java.security.interfaces.RSAPrivateKey; -import java.security.interfaces.RSAPublicKey; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Properties; -import java.util.logging.Logger; - -import javax.crypto.KeyAgreement; -import javax.crypto.SecretKey; - -import org.apache.cxf.common.logging.LogUtils; -import org.apache.cxf.common.util.StringUtils; -import org.apache.cxf.jaxrs.utils.JAXRSUtils; -import org.apache.cxf.message.Message; -import org.apache.cxf.message.MessageUtils; -import org.apache.cxf.rs.security.jose.JoseConstants; -import org.apache.cxf.rs.security.jose.JoseHeaders; -import org.apache.cxf.rs.security.jose.JoseUtils; -import org.apache.cxf.rs.security.jose.jaxrs.KeyManagementUtils; -import org.apache.cxf.rs.security.jose.jwa.AlgorithmUtils; -import org.apache.cxf.rs.security.jose.jwa.ContentAlgorithm; -import org.apache.cxf.rs.security.jose.jwa.KeyAlgorithm; -import org.apache.cxf.rs.security.jose.jwk.JsonWebKey; -import org.apache.cxf.rs.security.jose.jwk.JwkUtils; -import org.apache.cxf.rs.security.jose.jwk.KeyOperation; -import org.apache.cxf.rs.security.jose.jwk.KeyType; -import org.apache.cxf.rt.security.crypto.MessageDigestUtils; - -public final class JweUtils { - private static final Logger LOG = LogUtils.getL7dLogger(JweUtils.class); - private static final String JSON_WEB_ENCRYPTION_CEK_ALGO_PROP = "rs.security.jwe.content.encryption.algorithm"; - private static final String JSON_WEB_ENCRYPTION_KEY_ALGO_PROP = "rs.security.jwe.key.encryption.algorithm"; - private static final String JSON_WEB_ENCRYPTION_ZIP_ALGO_PROP = "rs.security.jwe.zip.algorithm"; - private static final String RSSEC_ENCRYPTION_OUT_PROPS = "rs.security.encryption.out.properties"; - private static final String RSSEC_ENCRYPTION_IN_PROPS = "rs.security.encryption.in.properties"; - private static final String RSSEC_ENCRYPTION_PROPS = "rs.security.encryption.properties"; - private static final String RSSEC_ENCRYPTION_REPORT_KEY_PROP = "rs.security.jwe.report.public.key"; - private static final String RSSEC_ENCRYPTION_REPORT_KEY_ID_PROP = "rs.security.jwe.report.public.key.id"; - - private JweUtils() { - - } - public static String encrypt(PublicKey key, KeyAlgorithm keyAlgo, ContentAlgorithm contentAlgo, - byte[] content) { - return encrypt(key, keyAlgo, contentAlgo, content, null); - } - public static String encrypt(PublicKey key, KeyAlgorithm keyAlgo, - ContentAlgorithm contentAlgo, byte[] content, String ct) { - KeyEncryptionProvider keyEncryptionProvider = getPublicKeyEncryptionProvider(key, keyAlgo); - return encrypt(keyEncryptionProvider, contentAlgo, content, ct); - } - public static String encrypt(SecretKey key, KeyAlgorithm keyAlgo, ContentAlgorithm contentAlgo, - byte[] content) { - return encrypt(key, keyAlgo, contentAlgo, content, null); - } - public static String encrypt(SecretKey key, KeyAlgorithm keyAlgo, ContentAlgorithm contentAlgo, - byte[] content, String ct) { - if (keyAlgo != null) { - KeyEncryptionProvider keyEncryptionProvider = getSecretKeyEncryptionAlgorithm(key, keyAlgo); - return encrypt(keyEncryptionProvider, contentAlgo, content, ct); - } else { - return encryptDirect(key, contentAlgo, content, ct); - } - } - public static String encrypt(JsonWebKey key, ContentAlgorithm contentAlgo, byte[] content, String ct) { - KeyEncryptionProvider keyEncryptionProvider = getKeyEncryptionProvider(key); - return encrypt(keyEncryptionProvider, contentAlgo, content, ct); - } - public static String encryptDirect(SecretKey key, ContentAlgorithm contentAlgo, byte[] content) { - return encryptDirect(key, contentAlgo, content, null); - } - public static String encryptDirect(SecretKey key, ContentAlgorithm contentAlgo, byte[] content, String ct) { - JweEncryptionProvider jwe = getDirectKeyJweEncryption(key, contentAlgo); - return jwe.encrypt(content, toJweHeaders(ct)); - } - public static String encryptDirect(JsonWebKey key, byte[] content, String ct) { - JweEncryptionProvider jwe = getDirectKeyJweEncryption(key); - return jwe.encrypt(content, toJweHeaders(ct)); - } - public static byte[] decrypt(PrivateKey key, KeyAlgorithm keyAlgo, ContentAlgorithm contentAlgo, String content) { - KeyDecryptionProvider keyDecryptionProvider = getPrivateKeyDecryptionProvider(key, keyAlgo); - return decrypt(keyDecryptionProvider, contentAlgo, content); - } - public static byte[] decrypt(SecretKey key, KeyAlgorithm keyAlgo, ContentAlgorithm contentAlgo, String content) { - if (keyAlgo != null) { - KeyDecryptionProvider keyDecryptionProvider = getSecretKeyDecryptionProvider(key, keyAlgo); - return decrypt(keyDecryptionProvider, contentAlgo, content); - } else { - return decryptDirect(key, contentAlgo, content); - } - } - public static byte[] decrypt(JsonWebKey key, ContentAlgorithm contentAlgo, String content) { - KeyDecryptionProvider keyDecryptionProvider = getKeyDecryptionProvider(key); - return decrypt(keyDecryptionProvider, contentAlgo, content); - } - public static byte[] decryptDirect(SecretKey key, ContentAlgorithm contentAlgo, String content) { - JweDecryptionProvider jwe = getDirectKeyJweDecryption(key, contentAlgo); - return jwe.decrypt(content).getContent(); - } - public static byte[] decryptDirect(JsonWebKey key, String content) { - JweDecryptionProvider jwe = getDirectKeyJweDecryption(key); - return jwe.decrypt(content).getContent(); - } - public static KeyEncryptionProvider getKeyEncryptionProvider(JsonWebKey jwk) { - return getKeyEncryptionProvider(jwk, null); - } - public static KeyEncryptionProvider getKeyEncryptionProvider(JsonWebKey jwk, KeyAlgorithm defaultAlgorithm) { - KeyAlgorithm keyAlgo = jwk.getAlgorithm() == null ? defaultAlgorithm - : KeyAlgorithm.getAlgorithm(jwk.getAlgorithm()); - KeyEncryptionProvider keyEncryptionProvider = null; - KeyType keyType = jwk.getKeyType(); - if (KeyType.RSA == keyType) { - keyEncryptionProvider = getPublicKeyEncryptionProvider(JwkUtils.toRSAPublicKey(jwk, true), - keyAlgo); - } else if (KeyType.OCTET == keyType) { - keyEncryptionProvider = getSecretKeyEncryptionAlgorithm(JwkUtils.toSecretKey(jwk), - keyAlgo); - } else { - keyEncryptionProvider = new EcdhAesWrapKeyEncryptionAlgorithm(JwkUtils.toECPublicKey(jwk), - jwk.getStringProperty(JsonWebKey.EC_CURVE), - keyAlgo); - } - return keyEncryptionProvider; - } - public static KeyEncryptionProvider getPublicKeyEncryptionProvider(PublicKey key, KeyAlgorithm algo) { - if (key instanceof PublicKey) { - return new RSAKeyEncryptionAlgorithm((RSAPublicKey)key, algo); - } else { - return new EcdhAesWrapKeyEncryptionAlgorithm((ECPublicKey)key, algo); - } - } - public static KeyEncryptionProvider getSecretKeyEncryptionAlgorithm(SecretKey key, KeyAlgorithm algo) { - if (AlgorithmUtils.isAesKeyWrap(algo.getJwaName())) { - return new AesWrapKeyEncryptionAlgorithm(key, algo); - } else if (AlgorithmUtils.isAesGcmKeyWrap(algo.getJwaName())) { - return new AesGcmWrapKeyEncryptionAlgorithm(key, algo); - } - return null; - } - public static KeyDecryptionProvider getKeyDecryptionProvider(JsonWebKey jwk) { - return getKeyDecryptionProvider(jwk, null); - } - - public static KeyDecryptionProvider getKeyDecryptionProvider(JsonWebKey jwk, KeyAlgorithm defaultAlgorithm) { - KeyAlgorithm keyAlgo = jwk.getAlgorithm() == null ? defaultAlgorithm - : KeyAlgorithm.getAlgorithm(jwk.getAlgorithm()); - KeyDecryptionProvider keyDecryptionProvider = null; - KeyType keyType = jwk.getKeyType(); - if (KeyType.RSA == keyType) { - keyDecryptionProvider = getPrivateKeyDecryptionProvider(JwkUtils.toRSAPrivateKey(jwk), - keyAlgo); - } else if (KeyType.OCTET == keyType) { - keyDecryptionProvider = getSecretKeyDecryptionProvider(JwkUtils.toSecretKey(jwk), - keyAlgo); - } else { - keyDecryptionProvider = getPrivateKeyDecryptionProvider(JwkUtils.toECPrivateKey(jwk), - keyAlgo); - } - return keyDecryptionProvider; - } - public static KeyDecryptionProvider getPrivateKeyDecryptionProvider(PrivateKey key, KeyAlgorithm algo) { - if (key instanceof RSAPrivateKey) { - return new RSAKeyDecryptionAlgorithm((RSAPrivateKey)key, algo); - } else { - return new EcdhAesWrapKeyDecryptionAlgorithm((ECPrivateKey)key, algo); - } - } - public static KeyDecryptionProvider getSecretKeyDecryptionProvider(SecretKey key, KeyAlgorithm algo) { - if (AlgorithmUtils.isAesKeyWrap(algo.getJwaName())) { - return new AesWrapKeyDecryptionAlgorithm(key, algo); - } else if (AlgorithmUtils.isAesGcmKeyWrap(algo.getJwaName())) { - return new AesGcmWrapKeyDecryptionAlgorithm(key, algo); - } - return null; - } - public static ContentEncryptionProvider getContentEncryptionAlgorithm(JsonWebKey jwk) { - return getContentEncryptionAlgorithm(jwk, null); - } - public static ContentEncryptionProvider getContentEncryptionAlgorithm(JsonWebKey jwk, String defaultAlgorithm) { - String ctEncryptionAlgo = jwk.getAlgorithm() == null ? defaultAlgorithm : jwk.getAlgorithm(); - ContentEncryptionProvider contentEncryptionProvider = null; - KeyType keyType = jwk.getKeyType(); - if (KeyType.OCTET == keyType) { - return getContentEncryptionAlgorithm(JwkUtils.toSecretKey(jwk), - getContentAlgo(ctEncryptionAlgo)); - } - return contentEncryptionProvider; - } - public static ContentEncryptionProvider getContentEncryptionAlgorithm(SecretKey key, - ContentAlgorithm algorithm) { - if (AlgorithmUtils.isAesGcm(algorithm.getJwaName())) { - return new AesGcmContentEncryptionAlgorithm(key, null, algorithm); - } - return null; - } - public static ContentEncryptionProvider getContentEncryptionAlgorithm(String algorithm) { - if (AlgorithmUtils.isAesGcm(algorithm)) { - return new AesGcmContentEncryptionAlgorithm(getContentAlgo(algorithm)); - } - return null; - } - public static ContentDecryptionProvider getContentDecryptionProvider(ContentAlgorithm algorithm) { - if (AlgorithmUtils.isAesGcm(algorithm.getJwaName())) { - return new AesGcmContentDecryptionAlgorithm(algorithm); - } - return null; - } - public static SecretKey getContentDecryptionSecretKey(JsonWebKey jwk) { - return getContentDecryptionSecretKey(jwk, null); - } - public static SecretKey getContentDecryptionSecretKey(JsonWebKey jwk, String defaultAlgorithm) { - String ctEncryptionAlgo = jwk.getAlgorithm() == null ? defaultAlgorithm : jwk.getAlgorithm(); - KeyType keyType = jwk.getKeyType(); - if (KeyType.OCTET == keyType && AlgorithmUtils.isAesGcm(ctEncryptionAlgo)) { - return JwkUtils.toSecretKey(jwk); - } - return null; - } - private static ContentAlgorithm getContentAlgo(String algo) { - return ContentAlgorithm.getAlgorithm(algo); - } - public static JweEncryption getDirectKeyJweEncryption(JsonWebKey key) { - return getDirectKeyJweEncryption(JwkUtils.toSecretKey(key), - getContentAlgo(key.getAlgorithm())); - } - public static JweEncryption getDirectKeyJweEncryption(SecretKey key, ContentAlgorithm algo) { - if (AlgorithmUtils.isAesCbcHmac(algo.getJwaName())) { - return new AesCbcHmacJweEncryption(algo, key.getEncoded(), - null, new DirectKeyEncryptionAlgorithm()); - } else { - return new JweEncryption(new DirectKeyEncryptionAlgorithm(), - getContentEncryptionAlgorithm(key, algo)); - } - } - public static JweDecryption getDirectKeyJweDecryption(JsonWebKey key) { - return getDirectKeyJweDecryption(JwkUtils.toSecretKey(key), getContentAlgo(key.getAlgorithm())); - } - public static JweDecryption getDirectKeyJweDecryption(SecretKey key, ContentAlgorithm algorithm) { - if (AlgorithmUtils.isAesCbcHmac(algorithm.getJwaName())) { - return new AesCbcHmacJweDecryption(new DirectKeyDecryptionAlgorithm(key), algorithm); - } else { - return new JweDecryption(new DirectKeyDecryptionAlgorithm(key), - getContentDecryptionProvider(algorithm)); - } - } - public static JweEncryptionProvider loadEncryptionProvider(boolean required) { - return loadEncryptionProvider(null, required); - } - public static JweEncryptionProvider loadEncryptionProvider(JweHeaders headers, boolean required) { - Message m = JAXRSUtils.getCurrentMessage(); - Properties props = KeyManagementUtils.loadStoreProperties(m, required, - RSSEC_ENCRYPTION_OUT_PROPS, RSSEC_ENCRYPTION_PROPS); - if (props == null) { - return null; - } - - boolean reportPublicKey = - headers != null && MessageUtils.isTrue( - MessageUtils.getContextualProperty(m, RSSEC_ENCRYPTION_REPORT_KEY_PROP, - KeyManagementUtils.RSSEC_REPORT_KEY_PROP)); - boolean reportPublicKeyId = - headers != null && MessageUtils.isTrue( - MessageUtils.getContextualProperty(m, RSSEC_ENCRYPTION_REPORT_KEY_ID_PROP, - KeyManagementUtils.RSSEC_REPORT_KEY_ID_PROP)); - - KeyEncryptionProvider keyEncryptionProvider = null; - String keyEncryptionAlgo = getKeyEncryptionAlgo(m, props, null, null); - KeyAlgorithm keyAlgo = KeyAlgorithm.getAlgorithm(keyEncryptionAlgo); - String contentEncryptionAlgo = getContentEncryptionAlgo(m, props, null); - ContentEncryptionProvider ctEncryptionProvider = null; - if (JwkUtils.JWK_KEY_STORE_TYPE.equals(props.get(KeyManagementUtils.RSSEC_KEY_STORE_TYPE))) { - JsonWebKey jwk = JwkUtils.loadJsonWebKey(m, props, KeyOperation.ENCRYPT); - if ("direct".equals(keyEncryptionAlgo)) { - contentEncryptionAlgo = getContentEncryptionAlgo(m, props, jwk.getAlgorithm()); - ctEncryptionProvider = getContentEncryptionAlgorithm(jwk, contentEncryptionAlgo); - } else { - keyEncryptionAlgo = getKeyEncryptionAlgo(m, props, jwk.getAlgorithm(), - getDefaultKeyAlgo(jwk)); - keyEncryptionProvider = getKeyEncryptionProvider(jwk, keyAlgo); - if (reportPublicKey || reportPublicKeyId) { - JwkUtils.setPublicKeyInfo(jwk, headers, keyEncryptionAlgo, - reportPublicKey, reportPublicKeyId); - } - } - } else { - keyEncryptionProvider = getPublicKeyEncryptionProvider( - KeyManagementUtils.loadPublicKey(m, props), - keyAlgo); - if (reportPublicKey) { - headers.setX509Chain(KeyManagementUtils.loadAndEncodeX509CertificateOrChain(m, props)); - } - - } - return createJweEncryptionProvider(keyEncryptionProvider, - ctEncryptionProvider, - contentEncryptionAlgo, - props.getProperty(JSON_WEB_ENCRYPTION_ZIP_ALGO_PROP)); - } - public static JweDecryptionProvider loadDecryptionProvider(boolean required) { - return loadDecryptionProvider(null, required); - } - public static JweDecryptionProvider loadDecryptionProvider(JweHeaders inHeaders, boolean required) { - Message m = JAXRSUtils.getCurrentMessage(); - Properties props = KeyManagementUtils.loadStoreProperties(m, required, - RSSEC_ENCRYPTION_IN_PROPS, RSSEC_ENCRYPTION_PROPS); - if (props == null) { - return null; - } - - KeyDecryptionProvider keyDecryptionProvider = null; - String contentEncryptionAlgo = getContentEncryptionAlgo(m, props, null); - SecretKey ctDecryptionKey = null; - String keyEncryptionAlgo = getKeyEncryptionAlgo(m, props, null, null); - if (inHeaders != null && inHeaders.getHeader(JoseConstants.HEADER_X509_CHAIN) != null) { - //TODO: validate incoming public keys or certificates - //TODO: optionally validate inHeaders.getAlgorithm against a property in props - // Supporting loading a private key via a certificate for now - List<X509Certificate> chain = KeyManagementUtils.toX509CertificateChain(inHeaders.getX509Chain()); - KeyManagementUtils.validateCertificateChain(props, chain); - PrivateKey privateKey = - KeyManagementUtils.loadPrivateKey(m, props, chain, KeyOperation.DECRYPT); - contentEncryptionAlgo = inHeaders.getContentEncryptionAlgorithm().getJwaName(); - keyDecryptionProvider = getPrivateKeyDecryptionProvider(privateKey, - inHeaders.getKeyEncryptionAlgorithm()); - } else { - if (JwkUtils.JWK_KEY_STORE_TYPE.equals(props.get(KeyManagementUtils.RSSEC_KEY_STORE_TYPE))) { - JsonWebKey jwk = JwkUtils.loadJsonWebKey(m, props, KeyOperation.DECRYPT); - if ("direct".equals(keyEncryptionAlgo)) { - contentEncryptionAlgo = getContentEncryptionAlgo(m, props, jwk.getAlgorithm()); - ctDecryptionKey = getContentDecryptionSecretKey(jwk, contentEncryptionAlgo); - } else { - keyEncryptionAlgo = getKeyEncryptionAlgo(m, props, jwk.getAlgorithm(), - getDefaultKeyAlgo(jwk)); - keyDecryptionProvider = getKeyDecryptionProvider(jwk, - KeyAlgorithm.getAlgorithm(keyEncryptionAlgo)); - } - } else { - keyDecryptionProvider = getPrivateKeyDecryptionProvider( - KeyManagementUtils.loadPrivateKey(m, props, KeyOperation.DECRYPT), - KeyAlgorithm.getAlgorithm(keyEncryptionAlgo)); - } - } - return createJweDecryptionProvider(keyDecryptionProvider, ctDecryptionKey, - getContentAlgo(contentEncryptionAlgo)); - } - public static JweEncryptionProvider createJweEncryptionProvider(PublicKey key, - KeyAlgorithm keyAlgo, - ContentAlgorithm contentEncryptionAlgo, - String compression) { - KeyEncryptionProvider keyEncryptionProvider = getPublicKeyEncryptionProvider(key, keyAlgo); - return createJweEncryptionProvider(keyEncryptionProvider, contentEncryptionAlgo, compression); - } - public static JweEncryptionProvider createJweEncryptionProvider(PublicKey key, JweHeaders headers) { - KeyEncryptionProvider keyEncryptionProvider = getPublicKeyEncryptionProvider(key, - headers.getKeyEncryptionAlgorithm()); - return createJweEncryptionProvider(keyEncryptionProvider, headers); - } - public static JweEncryptionProvider createJweEncryptionProvider(SecretKey key, - KeyAlgorithm keyAlgo, - ContentAlgorithm contentEncryptionAlgo, - String compression) { - KeyEncryptionProvider keyEncryptionProvider = getSecretKeyEncryptionAlgorithm(key, keyAlgo); - return createJweEncryptionProvider(keyEncryptionProvider, contentEncryptionAlgo, compression); - } - public static JweEncryptionProvider createJweEncryptionProvider(SecretKey key, JweHeaders headers) { - KeyEncryptionProvider keyEncryptionProvider = getSecretKeyEncryptionAlgorithm(key, - headers.getKeyEncryptionAlgorithm()); - return createJweEncryptionProvider(keyEncryptionProvider, headers); - } - public static JweEncryptionProvider createJweEncryptionProvider(JsonWebKey key, - ContentAlgorithm contentEncryptionAlgo, - String compression) { - KeyEncryptionProvider keyEncryptionProvider = getKeyEncryptionProvider(key); - return createJweEncryptionProvider(keyEncryptionProvider, contentEncryptionAlgo, compression); - } - public static JweEncryptionProvider createJweEncryptionProvider(JsonWebKey key, JweHeaders headers) { - KeyEncryptionProvider keyEncryptionProvider = getKeyEncryptionProvider(key); - return createJweEncryptionProvider(keyEncryptionProvider, headers); - } - public static JweEncryptionProvider createJweEncryptionProvider(KeyEncryptionProvider keyEncryptionProvider, - ContentAlgorithm contentEncryptionAlgo, - String compression) { - JweHeaders headers = - prepareJweHeaders(keyEncryptionProvider != null ? keyEncryptionProvider.getAlgorithm().getJwaName() : null, - contentEncryptionAlgo.getJwaName(), compression); - return createJweEncryptionProvider(keyEncryptionProvider, headers); - } - public static JweEncryptionProvider createJweEncryptionProvider(KeyEncryptionProvider keyEncryptionProvider, - JweHeaders headers) { - String contentEncryptionAlgo = headers.getContentEncryptionAlgorithm().getJwaName(); - if (AlgorithmUtils.isAesCbcHmac(contentEncryptionAlgo)) { - return new AesCbcHmacJweEncryption(getContentAlgo(contentEncryptionAlgo), keyEncryptionProvider); - } else { - return new JweEncryption(keyEncryptionProvider, - getContentEncryptionAlgorithm(contentEncryptionAlgo)); - } - } - public static JweDecryptionProvider createJweDecryptionProvider(PrivateKey key, - KeyAlgorithm keyAlgo, - ContentAlgorithm contentDecryptionAlgo) { - return createJweDecryptionProvider(getPrivateKeyDecryptionProvider(key, keyAlgo), contentDecryptionAlgo); - } - public static JweDecryptionProvider createJweDecryptionProvider(SecretKey key, - KeyAlgorithm keyAlgo, - ContentAlgorithm contentDecryptionAlgo) { - return createJweDecryptionProvider(getSecretKeyDecryptionProvider(key, keyAlgo), contentDecryptionAlgo); - } - public static JweDecryptionProvider createJweDecryptionProvider(JsonWebKey key, - ContentAlgorithm contentDecryptionAlgo) { - return createJweDecryptionProvider(getKeyDecryptionProvider(key), contentDecryptionAlgo); - } - public static JweDecryptionProvider createJweDecryptionProvider(KeyDecryptionProvider keyDecryptionProvider, - ContentAlgorithm contentDecryptionAlgo) { - if (AlgorithmUtils.isAesCbcHmac(contentDecryptionAlgo.getJwaName())) { - return new AesCbcHmacJweDecryption(keyDecryptionProvider, contentDecryptionAlgo); - } else { - return new JweDecryption(keyDecryptionProvider, - getContentDecryptionProvider(contentDecryptionAlgo)); - } - } - public static boolean validateCriticalHeaders(JoseHeaders headers) { - //TODO: Validate JWE specific constraints - return JoseUtils.validateCriticalHeaders(headers); - } - public static byte[] getECDHKey(JsonWebKey privateKey, - JsonWebKey peerPublicKey, - byte[] partyUInfo, - byte[] partyVInfo, - String algoName, - int algoKeyBitLen) { - return getECDHKey(JwkUtils.toECPrivateKey(privateKey), - JwkUtils.toECPublicKey(peerPublicKey), - partyUInfo, partyVInfo, algoName, algoKeyBitLen); - } - public static byte[] getECDHKey(ECPrivateKey privateKey, - ECPublicKey peerPublicKey, - byte[] partyUInfo, - byte[] partyVInfo, - String algoName, - int algoKeyBitLen) { - byte[] keyZ = generateKeyZ(privateKey, peerPublicKey); - return calculateDerivedKey(keyZ, algoName, partyUInfo, partyVInfo, algoKeyBitLen); - } - public static byte[] getAdditionalAuthenticationData(String headersJson, byte[] aad) { - byte[] headersAAD = JweHeaders.toCipherAdditionalAuthData(headersJson); - if (aad != null) { - // JWE JSON can provide the extra aad - byte[] newAAD = Arrays.copyOf(headersAAD, headersAAD.length + 1 + aad.length); - newAAD[headersAAD.length] = '.'; - System.arraycopy(aad, 0, newAAD, headersAAD.length + 1, aad.length); - return newAAD; - } else { - return headersAAD; - } - } - private static byte[] calculateDerivedKey(byte[] keyZ, - String algoName, - byte[] apuBytes, - byte[] apvBytes, - int algoKeyBitLen) { - final byte[] emptyPartyInfo = new byte[4]; - - if (apuBytes != null && apvBytes != null && Arrays.equals(apuBytes, apvBytes)) { - LOG.warning("Derived key calculation problem: apu equals to apv"); - throw new JweException(JweException.Error.KEY_ENCRYPTION_FAILURE); - } - byte[] algorithmId = concatenateDatalenAndData(StringUtils.toBytesASCII(algoName)); - byte[] partyUInfo = apuBytes == null ? emptyPartyInfo : concatenateDatalenAndData(apuBytes); - byte[] partyVInfo = apvBytes == null ? emptyPartyInfo : concatenateDatalenAndData(apvBytes); - byte[] suppPubInfo = datalenToBytes(algoKeyBitLen); - - byte[] otherInfo = new byte[algorithmId.length - + partyUInfo.length - + partyVInfo.length - + suppPubInfo.length]; - System.arraycopy(algorithmId, 0, otherInfo, 0, algorithmId.length); - System.arraycopy(partyUInfo, 0, otherInfo, algorithmId.length, partyUInfo.length); - System.arraycopy(partyVInfo, 0, otherInfo, algorithmId.length + partyUInfo.length, partyVInfo.length); - System.arraycopy(suppPubInfo, 0, otherInfo, algorithmId.length + partyUInfo.length + partyVInfo.length, - suppPubInfo.length); - - - byte[] concatKDF = new byte[36 + otherInfo.length]; - concatKDF[3] = 1; - System.arraycopy(keyZ, 0, concatKDF, 4, keyZ.length); - System.arraycopy(otherInfo, 0, concatKDF, 36, otherInfo.length); - try { - byte[] round1Hash = MessageDigestUtils.createDigest(concatKDF, MessageDigestUtils.ALGO_SHA_256); - return Arrays.copyOf(round1Hash, algoKeyBitLen / 8); - } catch (Exception ex) { - LOG.warning("Derived key calculation problem: round hash1 error"); - throw new JweException(JweException.Error.KEY_ENCRYPTION_FAILURE); - } - } - private static byte[] generateKeyZ(ECPrivateKey privateKey, ECPublicKey publicKey) { - try { - KeyAgreement ka = KeyAgreement.getInstance("ECDH"); - ka.init(privateKey); - ka.doPhase(publicKey, true); - return ka.generateSecret(); - } catch (Exception ex) { - LOG.warning("Derived key calculation problem"); - throw new JweException(JweException.Error.KEY_ENCRYPTION_FAILURE); - } - } - private static byte[] concatenateDatalenAndData(byte[] bytesASCII) { - final byte[] datalen = datalenToBytes(bytesASCII.length); - byte[] all = new byte[4 + bytesASCII.length]; - System.arraycopy(datalen, 0, all, 0, 4); - System.arraycopy(bytesASCII, 0, all, 4, bytesASCII.length); - return all; - } - private static byte[] datalenToBytes(int len) { - ByteBuffer buf = ByteBuffer.allocate(4); - return buf.putInt(len).array(); - } - private static JweHeaders prepareJweHeaders(String keyEncryptionAlgo, - String contentEncryptionAlgo, - String compression) { - JweHeaders headers = new JweHeaders(); - if (keyEncryptionAlgo != null) { - headers.setKeyEncryptionAlgorithm(KeyAlgorithm.getAlgorithm(keyEncryptionAlgo)); - } - headers.setContentEncryptionAlgorithm(ContentAlgorithm.getAlgorithm(contentEncryptionAlgo)); - if (compression != null) { - headers.setZipAlgorithm(compression); - } - return headers; - } - private static JweEncryptionProvider createJweEncryptionProvider(KeyEncryptionProvider keyEncryptionProvider, - ContentEncryptionProvider ctEncryptionProvider, - String contentEncryptionAlgo, - String compression) { - if (keyEncryptionProvider == null && ctEncryptionProvider == null) { - LOG.warning("Key or content encryptor is not available"); - throw new JweException(JweException.Error.NO_ENCRYPTOR); - } - JweHeaders headers = - prepareJweHeaders(keyEncryptionProvider != null ? keyEncryptionProvider.getAlgorithm().getJwaName() : null, - contentEncryptionAlgo, compression); - if (keyEncryptionProvider != null) { - return createJweEncryptionProvider(keyEncryptionProvider, headers); - } else { - return new JweEncryption(new DirectKeyEncryptionAlgorithm(), ctEncryptionProvider); - } - } - private static JweDecryptionProvider createJweDecryptionProvider(KeyDecryptionProvider keyDecryptionProvider, - SecretKey ctDecryptionKey, - ContentAlgorithm contentDecryptionAlgo) { - if (keyDecryptionProvider == null && ctDecryptionKey == null) { - LOG.warning("Key or content encryptor is not available"); - throw new JweException(JweException.Error.NO_ENCRYPTOR); - } - if (keyDecryptionProvider != null) { - return createJweDecryptionProvider(keyDecryptionProvider, contentDecryptionAlgo); - } else { - return getDirectKeyJweDecryption(ctDecryptionKey, contentDecryptionAlgo); - } - } - private static String getKeyEncryptionAlgo(Message m, Properties props, - String algo, String defaultAlgo) { - if (algo == null) { - if (defaultAlgo == null) { - defaultAlgo = AlgorithmUtils.RSA_OAEP_ALGO; - } - return KeyManagementUtils.getKeyAlgorithm(m, props, - JSON_WEB_ENCRYPTION_KEY_ALGO_PROP, defaultAlgo); - } - return algo; - } - private static String getDefaultKeyAlgo(JsonWebKey jwk) { - KeyType keyType = jwk.getKeyType(); - if (KeyType.OCTET == keyType) { - return AlgorithmUtils.A128GCMKW_ALGO; - } else { - return AlgorithmUtils.RSA_OAEP_ALGO; - } - } - private static String getContentEncryptionAlgo(Message m, Properties props, String algo) { - if (algo == null) { - return KeyManagementUtils.getKeyAlgorithm(m, props, - JSON_WEB_ENCRYPTION_CEK_ALGO_PROP, AlgorithmUtils.A128GCM_ALGO); - } - return algo; - } - private static String encrypt(KeyEncryptionProvider keyEncryptionProvider, - ContentAlgorithm contentAlgo, byte[] content, String ct) { - JweEncryptionProvider jwe = createJweEncryptionProvider(keyEncryptionProvider, contentAlgo, null); - return jwe.encrypt(content, toJweHeaders(ct)); - } - private static byte[] decrypt(KeyDecryptionProvider keyDecryptionProvider, ContentAlgorithm contentAlgo, - String content) { - JweDecryptionProvider jwe = createJweDecryptionProvider(keyDecryptionProvider, contentAlgo); - return jwe.decrypt(content).getContent(); - } - private static JweHeaders toJweHeaders(String ct) { - return new JweHeaders(Collections.<String, Object>singletonMap(JoseConstants.HEADER_CONTENT_TYPE, ct)); - } - public static void validateJweCertificateChain(List<X509Certificate> certs) { - - Message m = JAXRSUtils.getCurrentMessage(); - Properties props = KeyManagementUtils.loadStoreProperties(m, true, - RSSEC_ENCRYPTION_IN_PROPS, RSSEC_ENCRYPTION_PROPS); - KeyManagementUtils.validateCertificateChain(props, certs); - } - -} http://git-wip-us.apache.org/repos/asf/cxf/blob/66a81773/rt/rs/security/jose/src/main/java/org/apache/cxf/rs/security/jose/jwe/KeyDecryptionProvider.java ---------------------------------------------------------------------- diff --git a/rt/rs/security/jose/src/main/java/org/apache/cxf/rs/security/jose/jwe/KeyDecryptionProvider.java b/rt/rs/security/jose/src/main/java/org/apache/cxf/rs/security/jose/jwe/KeyDecryptionProvider.java deleted file mode 100644 index 1924e78..0000000 --- a/rt/rs/security/jose/src/main/java/org/apache/cxf/rs/security/jose/jwe/KeyDecryptionProvider.java +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you 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 org.apache.cxf.rs.security.jose.jwe; - -import org.apache.cxf.rs.security.jose.jwa.KeyAlgorithm; - - -public interface KeyDecryptionProvider { - KeyAlgorithm getAlgorithm(); - byte[] getDecryptedContentEncryptionKey(JweDecryptionInput jweDecryptionInput); -} http://git-wip-us.apache.org/repos/asf/cxf/blob/66a81773/rt/rs/security/jose/src/main/java/org/apache/cxf/rs/security/jose/jwe/KeyEncryptionProvider.java ---------------------------------------------------------------------- diff --git a/rt/rs/security/jose/src/main/java/org/apache/cxf/rs/security/jose/jwe/KeyEncryptionProvider.java b/rt/rs/security/jose/src/main/java/org/apache/cxf/rs/security/jose/jwe/KeyEncryptionProvider.java deleted file mode 100644 index 2f5c8db..0000000 --- a/rt/rs/security/jose/src/main/java/org/apache/cxf/rs/security/jose/jwe/KeyEncryptionProvider.java +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you 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 org.apache.cxf.rs.security.jose.jwe; - -import org.apache.cxf.rs.security.jose.jwa.KeyAlgorithm; - - -public interface KeyEncryptionProvider { - KeyAlgorithm getAlgorithm(); - byte[] getEncryptedContentEncryptionKey(JweHeaders headers, byte[] cek); -}
