v1.2.1 GA

SAML 2.0 optimization,support 阿里云、腾讯云 SSO
maxkey-mgt main report
APPS ExtraAttr
fix ui bugs
remove maxkey-jose-jwt
dep com.nimbusds nimbus-jose-jwt
dep net.jcip jcip-annotations
dep net.minidev json-smart
dep net.minidev asm
上级 008793f4
......@@ -202,6 +202,11 @@ subprojects {
compile group: 'org.opensaml', name: 'openws', version: '1.5.4'
compile group: 'org.opensaml', name: 'xmltooling', version: '1.4.4'
compile group: 'com.nimbusds', name: 'nimbus-jose-jwt', version: '8.8'
compile group: 'net.jcip', name: 'jcip-annotations', version: '1.0'
compile group: 'net.minidev', name: 'json-smart', version: '2.3'
compile group: 'net.minidev', name: 'asm', version: '1.0.2'
compile group: 'cn.hutool', name: 'hutool-core', version: '5.1.2'
compile group: 'cn.hutool', name: 'hutool-http', version: '5.1.2'
compile group: 'me.zhyd.oauth', name: 'JustAuth', version: '1.13.2'
......
group =org.maxkey
version =1.2.0.RELEASE
version =1.2.1.RELEASE
vendor =https://github.com/shimingxy/MaxKey
author =shimingxy
......
......@@ -10,7 +10,6 @@ dependencies {
compile project(":maxkey-core")
compile project(":maxkey-dao")
compile project(":maxkey-jose-jwt")
compile project(":maxkey-client-sdk")
compile project(":maxkey-protocols:maxkey-protocol-oauth-2.0")
compile project(":maxkey-protocols:maxkey-protocol-saml-2.0")
......
......@@ -4,7 +4,7 @@ import org.maxkey.client.oauth.model.Token;
public class MaxkeyApi10a extends DefaultApi10a
{
private static final String DEFAULT_WEB_URL = "http://sso.maxkey.org/maxkey";
private static final String DEFAULT_WEB_URL = "https://sso.maxkey.org/maxkey";
private static final String AUTHORIZATION_URL = DEFAULT_WEB_URL+"/oauth/v10a/authz?oauth_token=%s";
public MaxkeyApi10a() {
......
......@@ -9,7 +9,7 @@ import org.maxkey.client.utils.Preconditions;
public class MaxkeyApi20 extends DefaultApi20 {
//approval_prompt:force or auto
private static final String DEFAULT_WEB_URL = "http://sso.maxkey.org/maxkey";
private static final String DEFAULT_WEB_URL = "https://sso.maxkey.org/maxkey";
private static final String AUTHORIZATION_URL = "%s/oauth/v20/authorize?client_id=%s&response_type=code&redirect_uri=%s&approval_prompt=auto";
......
......@@ -4,5 +4,4 @@ dependencies {
//local jars
compile fileTree(dir: '../maxkey-lib/', include: '*/*.jar')
compile project(":maxkey-jose-jwt")
}
\ No newline at end of file
......@@ -164,7 +164,7 @@ public class InitApplicationContext extends HttpServlet {
public void showLicense(){
_logger.info("----------------------------------------------------------------------------------------------------");
_logger.info("+ Single Sign On ( SSO ) ");
_logger.info("+ MaxKey Version 1.2 GA");
_logger.info("+ MaxKey Version 1.2.1 GA");
_logger.info("");
_logger.info("+ Apache License 2.0");
_logger.info("+ https://github.com/shimingxy/MaxKey");
......
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" output="bin/main" path="src/main/java">
<attributes>
<attribute name="gradle_scope" value="main"/>
<attribute name="gradle_used_by_scope" value="main,test"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8/"/>
<classpathentry kind="con" path="org.eclipse.buildship.core.gradleclasspathcontainer"/>
<classpathentry kind="output" path="bin/default"/>
</classpath>
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>maxkey-jose-jwt</name>
<comment>maxkey-jose-jwt</comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.buildship.core.gradleprojectbuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.wst.common.project.facet.core.builder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.wst.validation.validationbuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.springframework.ide.eclipse.boot.validation.springbootbuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.buildship.core.gradleprojectnature</nature>
<nature>org.eclipse.wst.common.project.facet.core.nature</nature>
<nature>org.eclipse.wst.common.modulecore.ModuleCoreNature</nature>
</natures>
</projectDescription>
build.commands=org.eclipse.jdt.core.javabuilder
connection.arguments=
connection.gradle.distribution=GRADLE_DISTRIBUTION(WRAPPER)
connection.java.home=null
connection.jvm.arguments=
connection.project.dir=..
containers=org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7/
derived.resources=.gradle,build
eclipse.preferences.version=1
natures=org.eclipse.jdt.core.javanature
project.path=\:maxkey-jose-jwt
eclipse.preferences.version=1
encoding/<project>=UTF-8
\ No newline at end of file
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
org.eclipse.jdt.core.compiler.compliance=1.8
org.eclipse.jdt.core.compiler.source=1.8
<?xml version="1.0" encoding="UTF-8"?><project-modules id="moduleCoreId" project-version="1.5.0">
<wb-module deploy-name="maxkey-jose-jwt">
<wb-resource deploy-path="/" source-path="/src/main/java"/>
</wb-module>
</project-modules>
<?xml version="1.0" encoding="UTF-8"?>
<faceted-project>
<fixed facet="java"/>
<fixed facet="jst.utility"/>
<installed facet="jst.utility" version="1.0"/>
<installed facet="java" version="1.8"/>
</faceted-project>
description = "maxkey-jose-jwt"
dependencies {
compile fileTree(dir: '../maxkey-lib/', include: '*/tink-1.2.2.jar')
compile fileTree(dir: '../maxkey-lib/', include: '*/bcp*jdk15on-150.jar')
compile fileTree(dir: '../maxkey-lib/', include: '*/asm-5.0.3.jar')
}
Manifest-Version: 1.0
Archiver-Version: Plexus Archiver
Created-By: Apache Maven
Built-By: vd
Build-Jdk: 1.7.0_72
net.minidev
json-smart-2.3
asm-1.0.2
Java Concurrency in Practice
net.jcip.annotations
nimbus
nimbus-jose-jwt version 7.1
\ No newline at end of file
/*
* nimbus-jose-jwt
*
* Copyright 2012-2016, Connect2id Ltd.
*
* Licensed 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 com.nimbusds.jose;
import java.io.Serializable;
import net.jcip.annotations.Immutable;
import net.minidev.json.JSONAware;
import net.minidev.json.JSONObject;
/**
* The base class for algorithm names, with optional implementation
* requirement. This class is immutable.
*
* <p>Includes constants for the following standard algorithm names:
*
* <ul>
* <li>{@link #NONE none}
* </ul>
*
* @author Vladimir Dzhuvinov
* @version 2013-03-27
*/
@Immutable
public class Algorithm implements JSONAware, Serializable {
private static final long serialVersionUID = 1L;
/**
* No algorithm (unsecured JOSE object without signature / encryption).
*/
public static final Algorithm NONE = new Algorithm("none", Requirement.REQUIRED);
/**
* The algorithm name.
*/
private final String name;
/**
* The implementation requirement, {@code null} if not known.
*/
private final Requirement requirement;
/**
* Creates a new JOSE algorithm name.
*
* @param name The algorithm name. Must not be {@code null}.
* @param req The implementation requirement, {@code null} if not
* known.
*/
public Algorithm(final String name, final Requirement req) {
if (name == null) {
throw new IllegalArgumentException("The algorithm name must not be null");
}
this.name = name;
requirement = req;
}
/**
* Creates a new JOSE algorithm name.
*
* @param name The algorithm name. Must not be {@code null}.
*/
public Algorithm(final String name) {
this(name, null);
}
/**
* Gets the name of this algorithm.
*
* @return The algorithm name.
*/
public final String getName() {
return name;
}
/**
* Gets the implementation requirement of this algorithm.
*
* @return The implementation requirement, {@code null} if not known.
*/
public final Requirement getRequirement() {
return requirement;
}
/**
* Overrides {@code Object.hashCode()}.
*
* @return The object hash code.
*/
@Override
public final int hashCode() {
return name.hashCode();
}
/**
* Overrides {@code Object.equals()}.
*
* @param object The object to compare to.
*
* @return {@code true} if the objects have the same value, otherwise
* {@code false}.
*/
@Override
public boolean equals(final Object object) {
return object != null &&
object instanceof Algorithm &&
this.toString().equals(object.toString());
}
/**
* Returns the string representation of this algorithm.
*
* @see #getName
*
* @return The string representation.
*/
@Override
public final String toString() {
return name;
}
/**
* Returns the JSON string representation of this algorithm.
*
* @return The JSON string representation.
*/
@Override
public final String toJSONString() {
return "\"" + JSONObject.escape(name) + '"';
}
}
/*
* nimbus-jose-jwt
*
* Copyright 2012-2016, Connect2id Ltd.
*
* Licensed 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 com.nimbusds.jose;
import java.util.Collection;
import java.util.LinkedHashSet;
import net.jcip.annotations.Immutable;
/**
* Algorithm family.
*
* @author Vladimir Dzhuvinov
* @version 2016-08-24
*/
@Immutable
class AlgorithmFamily <T extends Algorithm> extends LinkedHashSet<T> {
private static final long serialVersionUID = 1L;
/**
* Creates a new algorithm family.
*
* @param algs The algorithms of the family. Must not be {@code null}.
*/
public AlgorithmFamily(final T ... algs) {
for (T alg: algs) {
super.add(alg);
}
}
@Override
public boolean add(final T alg) {
throw new UnsupportedOperationException();
}
@Override
public boolean addAll(final Collection<? extends T> algs) {
throw new UnsupportedOperationException();
}
@Override
public boolean remove(final Object o) {
throw new UnsupportedOperationException();
}
@Override
public boolean removeAll(final Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
public boolean retainAll(final Collection<?> c) {
throw new UnsupportedOperationException();
}
}
/*
* nimbus-jose-jwt
*
* Copyright 2012-2016, Connect2id Ltd.
*
* Licensed 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 com.nimbusds.jose;
import java.net.URI;
import java.util.*;
import com.nimbusds.jose.jwk.JWK;
import com.nimbusds.jose.util.Base64;
import com.nimbusds.jose.util.Base64URL;
import net.minidev.json.JSONObject;
/**
* Common class for JWS and JWE headers.
*
* <p>Supports all registered header parameters shared by the JWS and JWE
* specifications:
*
* <ul>
* <li>alg
* <li>jku
* <li>jwk
* <li>x5u
* <li>x5t
* <li>x5t#S256
* <li>x5c
* <li>kid
* <li>typ
* <li>cty
* <li>crit
* </ul>
*
* @author Vladimir Dzhuvinov
* @version 2017-04-09
*/
abstract class CommonSEHeader extends Header {
private static final long serialVersionUID = 1L;
/**
* JWK Set URL, {@code null} if not specified.
*/
private final URI jku;
/**
* JWK, {@code null} if not specified.
*/
private final JWK jwk;
/**
* X.509 certificate URL, {@code null} if not specified.
*/
private final URI x5u;
/**
* X.509 certificate SHA-1 thumbprint, {@code null} if not specified.
*/
private final Base64URL x5t;
/**
* X.509 certificate SHA-256 thumbprint, {@code null} if not specified.
*/
private final Base64URL x5t256;
/**
* The X.509 certificate chain corresponding to the key used to sign or
* encrypt the JWS / JWE object, {@code null} if not specified.
*/
private final List<Base64> x5c;
/**
* Key ID, {@code null} if not specified.
*/
private final String kid;
/**
* Creates a new common JWS and JWE header.
*
* @param alg The algorithm ({@code alg}) parameter. Must
* not be {@code null}.
* @param typ The type ({@code typ}) parameter,
* {@code null} if not specified.
* @param cty The content type ({@code cty}) parameter,
* {@code null} if not specified.
* @param crit The names of the critical header
* ({@code crit}) parameters, empty set or
* {@code null} if none.
* @param jku The JSON Web Key (JWK) Set URL ({@code jku})
* parameter, {@code null} if not specified.
* @param jwk The X.509 certificate URL ({@code jwk})
* parameter, {@code null} if not specified.
* @param x5u The X.509 certificate URL parameter
* ({@code x5u}), {@code null} if not specified.
* @param x5t The X.509 certificate SHA-1 thumbprint
* ({@code x5t}) parameter, {@code null} if not
* specified.
* @param x5t256 The X.509 certificate SHA-256 thumbprint
* ({@code x5t#S256}) parameter, {@code null} if
* not specified.
* @param x5c The X.509 certificate chain ({@code x5c})
* parameter, {@code null} if not specified.
* @param kid The key ID ({@code kid}) parameter,
* {@code null} if not specified.
* @param customParams The custom parameters, empty map or
* {@code null} if none.
* @param parsedBase64URL The parsed Base64URL, {@code null} if the
* header is created from scratch.
*/
protected CommonSEHeader(final Algorithm alg,
final JOSEObjectType typ,
final String cty,
final Set<String> crit,
final URI jku,
final JWK jwk,
final URI x5u,
final Base64URL x5t,
final Base64URL x5t256,
final List<Base64> x5c,
final String kid,
final Map<String,Object> customParams,
final Base64URL parsedBase64URL) {
super(alg, typ, cty, crit, customParams, parsedBase64URL);
this.jku = jku;
this.jwk = jwk;
this.x5u = x5u;
this.x5t = x5t;
this.x5t256 = x5t256;
if (x5c != null) {
// Copy and make unmodifiable
this.x5c = Collections.unmodifiableList(new ArrayList<>(x5c));
} else {
this.x5c = null;
}
this.kid = kid;
}
/**
* Gets the JSON Web Key (JWK) Set URL ({@code jku}) parameter.
*
* @return The JSON Web Key (JWK) Set URL parameter, {@code null} if
* not specified.
*/
public URI getJWKURL() {
return jku;
}
/**
* Gets the JSON Web Key (JWK) ({@code jwk}) parameter.
*
* @return The JSON Web Key (JWK) parameter, {@code null} if not
* specified.
*/
public JWK getJWK() {
return jwk;
}
/**
* Gets the X.509 certificate URL ({@code x5u}) parameter.
*
* @return The X.509 certificate URL parameter, {@code null} if not
* specified.
*/
public URI getX509CertURL() {
return x5u;
}
/**
* Gets the X.509 certificate SHA-1 thumbprint ({@code x5t}) parameter.
*
* @return The X.509 certificate SHA-1 thumbprint parameter,
* {@code null} if not specified.
*/
@Deprecated
public Base64URL getX509CertThumbprint() {
return x5t;
}
/**
* Gets the X.509 certificate SHA-256 thumbprint ({@code x5t#S256})
* parameter.
*
* @return The X.509 certificate SHA-256 thumbprint parameter,
* {@code null} if not specified.
*/
public Base64URL getX509CertSHA256Thumbprint() {
return x5t256;
}
/**
* Gets the X.509 certificate chain ({@code x5c}) parameter
* corresponding to the key used to sign or encrypt the JWS / JWE
* object.
*
* @return The X.509 certificate chain parameter as a unmodifiable
* list, {@code null} if not specified.
*/
public List<Base64> getX509CertChain() {
return x5c;
}
/**
* Gets the key ID ({@code kid}) parameter.
*
* @return The key ID parameter, {@code null} if not specified.
*/
public String getKeyID() {
return kid;
}
@Override
public Set<String> getIncludedParams() {
Set<String> includedParameters = super.getIncludedParams();
if (jku != null) {
includedParameters.add("jku");
}
if (jwk != null) {
includedParameters.add("jwk");
}
if (x5u != null) {
includedParameters.add("x5u");
}
if (x5t != null) {
includedParameters.add("x5t");
}
if (x5t256 != null) {
includedParameters.add("x5t#S256");
}
if (x5c != null && ! x5c.isEmpty()) {
includedParameters.add("x5c");
}
if (kid != null) {
includedParameters.add("kid");
}
return includedParameters;
}
@Override
public JSONObject toJSONObject() {
JSONObject o = super.toJSONObject();
if (jku != null) {
o.put("jku", jku.toString());
}
if (jwk != null) {
o.put("jwk", jwk.toJSONObject());
}
if (x5u != null) {
o.put("x5u", x5u.toString());
}
if (x5t != null) {
o.put("x5t", x5t.toString());
}
if (x5t256 != null) {
o.put("x5t#S256", x5t256.toString());
}
if (x5c != null && ! x5c.isEmpty()) {
o.put("x5c", x5c);
}
if (kid != null) {
o.put("kid", kid);
}
return o;
}
}
/*
* nimbus-jose-jwt
*
* Copyright 2012-2016, Connect2id Ltd.
*
* Licensed 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 com.nimbusds.jose;
import java.io.Serializable;
import net.jcip.annotations.Immutable;
import net.minidev.json.JSONAware;
import net.minidev.json.JSONObject;
/**
* Compression algorithm name, represents the {@code zip} header parameter in
* JSON Web Encryption (JWE) objects. This class is immutable.
*
* <p>Includes a constant for the standard DEFLATE compression algorithm:
*
* <ul>
* <li>{@link #DEF}
* </ul>
*
* <p>Additional compression algorithm names can be defined using the
* constructor.
*
* @author Vladimir Dzhuvinov
* @version 2013-01-15
*/
@Immutable
public final class CompressionAlgorithm implements JSONAware, Serializable {
private static final long serialVersionUID = 1L;
/**
* DEFLATE Compressed Data Format Specification version 1.3, as
* described in RFC 1951.
*/
public static final CompressionAlgorithm DEF = new CompressionAlgorithm("DEF");
/**
* The algorithm name.
*/
private final String name;
/**
* Creates a new compression algorithm with the specified name.
*
* @param name The compression algorithm name. Must not be {@code null}.
*/
public CompressionAlgorithm(final String name) {
if (name == null) {
throw new IllegalArgumentException("The compression algorithm name must not be null");
}
this.name = name;
}
/**
* Gets the name of this compression algorithm.
*
* @return The compression algorithm name.
*/
public String getName() {
return name;
}
/**
* Overrides {@code Object.hashCode()}.
*
* @return The object hash code.
*/
@Override
public int hashCode() {
return name.hashCode();
}
/**
* Overrides {@code Object.equals()}.
*
* @param object The object to compare to.
*
* @return {@code true} if the objects have the same value, otherwise
* {@code false}.
*/
@Override
public boolean equals(final Object object) {
return object != null &&
object instanceof CompressionAlgorithm &&
this.toString().equals(object.toString());
}
/**
* Returns the string representation of this compression algorithm.
*
* @see #getName
*
* @return The string representation.
*/
@Override
public String toString() {
return name;
}
/**
* Returns the JSON string representation of this compression algorithm.
*
* @return The JSON string representation.
*/
@Override
public String toJSONString() {
return "\"" + JSONObject.escape(name) + '"';
}
}
/*
* nimbus-jose-jwt
*
* Copyright 2012-2016, Connect2id Ltd.
*
* Licensed 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 com.nimbusds.jose;
import java.util.Set;
/**
* JSON Web Signature (JWS) verifier or JSON Web Encryption (JWE) decrypter
* that supports processing and / or deferral of critical ({@code crit}) header
* parameters.
*
* <p>JWS verification / JWE decryption will fail with a {@link JOSEException}
* if a critical header is encountered that is neither processed by the
* verifier / decrypter nor deferred to the application.
*
* @author Vladimir Dzhuvinov
* @version 2015-04-21
*/
public interface CriticalHeaderParamsAware {
/**
* Returns the names of the critical ({@code crit}) header parameters
* that are understood and processed by the JWS verifier / JWE
* decrypter.
*
* @return The names of the critical header parameters that are
* understood and processed, empty set if none.
*/
Set<String> getProcessedCriticalHeaderParams();
/**
* Returns the names of the critical ({@code crit}) header parameters
* that are deferred to the application for processing and will be
* ignored by the JWS verifier / JWE decrypter.
*
* @return The names of the critical header parameters that are
* deferred to the application for processing, empty set if
* none.
*/
Set<String> getDeferredCriticalHeaderParams();
}
/*
* nimbus-jose-jwt
*
* Copyright 2012-2016, Connect2id Ltd.
*
* Licensed 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 com.nimbusds.jose;
import net.jcip.annotations.Immutable;
/**
* Encryption method name, represents the {@code enc} header parameter in JSON
* Web Encryption (JWE) objects. This class is immutable.
*
* <p>Includes constants for the following standard encryption method names:
*
* <ul>
* <li>{@link #A128CBC_HS256 A128CBC-HS256}
* <li>{@link #A192CBC_HS384 A192CBC-HS384}
* <li>{@link #A256CBC_HS512 A256CBC-HS512}
* <li>{@link #A128GCM}
* <li>{@link #A192GCM}
* <li>{@link #A256GCM}
* <li>{@link #A128CBC_HS256_DEPRECATED A128CBC+HS256 (deprecated)}
* <li>{@link #A256CBC_HS512_DEPRECATED A256CBC+HS512 (deprecated)}
* </ul>
*
* <p>Additional encryption method names can be defined using the constructors.
*
* @author Vladimir Dzhuvinov
* @version 2015-10-14
*/
@Immutable
public final class EncryptionMethod extends Algorithm {
private static final long serialVersionUID = 1L;
/**
* The Content Encryption Key (CEK) bit length, zero if not specified.
*/
private final int cekBitLength;
/**
* AES_128_CBC_HMAC_SHA_256 authenticated encryption using a 256 bit
* key (required).
*/
public static final EncryptionMethod A128CBC_HS256 =
new EncryptionMethod("A128CBC-HS256", Requirement.REQUIRED, 256);
/**
* AES_192_CBC_HMAC_SHA_384 authenticated encryption using a 384 bit
* key (optional).
*/
public static final EncryptionMethod A192CBC_HS384 =
new EncryptionMethod("A192CBC-HS384", Requirement.OPTIONAL, 384);
/**
* AES_256_CBC_HMAC_SHA_512 authenticated encryption using a 512 bit
* key (required).
*/
public static final EncryptionMethod A256CBC_HS512 =
new EncryptionMethod("A256CBC-HS512", Requirement.REQUIRED, 512);
/**
* AES_128_CBC_HMAC_SHA_256 authenticated encryption using a 256 bit
* key, deprecated in JOSE draft suite version 09.
*/
public static final EncryptionMethod A128CBC_HS256_DEPRECATED =
new EncryptionMethod("A128CBC+HS256", Requirement.OPTIONAL, 256);
/**
* AES_256_CBC_HMAC_SHA_512 authenticated encryption using a 512 bit
* key, deprecated in JOSE draft suite version 09.
*/
public static final EncryptionMethod A256CBC_HS512_DEPRECATED =
new EncryptionMethod("A256CBC+HS512", Requirement.OPTIONAL, 512);
/**
* AES in Galois/Counter Mode (GCM) (NIST.800-38D) using a 128 bit key
* (recommended).
*/
public static final EncryptionMethod A128GCM =
new EncryptionMethod("A128GCM", Requirement.RECOMMENDED, 128);
/**
* AES in Galois/Counter Mode (GCM) (NIST.800-38D) using a 192 bit key
* (optional).
*/
public static final EncryptionMethod A192GCM =
new EncryptionMethod("A192GCM", Requirement.OPTIONAL, 192);
/**
* AES in Galois/Counter Mode (GCM) (NIST.800-38D) using a 256 bit key
* (recommended).
*/
public static final EncryptionMethod A256GCM =
new EncryptionMethod("A256GCM", Requirement.RECOMMENDED, 256);
/**
* Encryption method family.
*/
public static final class Family extends AlgorithmFamily<EncryptionMethod> {
private static final long serialVersionUID = 1L;
/**
* AES/CBC/HMAC with SHA-2.
*/
public static final Family AES_CBC_HMAC_SHA = new Family(A128CBC_HS256, A192CBC_HS384, A256CBC_HS512);
/**
* AES/GCM.
*/
public static final Family AES_GCM = new Family(A128GCM, A192GCM, A256GCM);
/***
* Creates a new encryption method family.
*
* @param encs The encryption methods of the family. Must not
* be {@code null}.
*/
public Family(final EncryptionMethod ... encs) {
super(encs);
}
}
/**
* Creates a new encryption method.
*
* @param name The encryption method name. Must not be
* {@code null}.
* @param req The implementation requirement, {@code null} if
* not known.
* @param cekBitLength The Content Encryption Key (CEK) bit length,
* zero if not specified.
*/
public EncryptionMethod(final String name, final Requirement req, final int cekBitLength) {
super(name, req);
this.cekBitLength = cekBitLength;
}
/**
* Creates a new encryption method. The Content Encryption Key (CEK)
* bit length is not specified.
*
* @param name The encryption method name. Must not be {@code null}.
* @param req The implementation requirement, {@code null} if not
* known.
*/
public EncryptionMethod(final String name, final Requirement req) {
this(name, req, 0);
}
/**
* Creates a new encryption method. The implementation requirement and
* the Content Encryption Key (CEK) bit length are not specified.
*
* @param name The encryption method name. Must not be {@code null}.
*/
public EncryptionMethod(final String name) {
this(name, null, 0);
}
/**
* Gets the length of the associated Content Encryption Key (CEK).
*
* @return The Content Encryption Key (CEK) bit length, zero if not
* specified.
*/
public int cekBitLength() {
return cekBitLength;
}
/**
* Parses an encryption method from the specified string.
*
* @param s The string to parse. Must not be {@code null}.
*
* @return The encryption method (matching standard algorithm
* constant, else a newly created algorithm).
*/
public static EncryptionMethod parse(final String s) {
if (s.equals(A128CBC_HS256.getName())) {
return A128CBC_HS256;
} else if (s.equals(A192CBC_HS384.getName())) {
return A192CBC_HS384;
} else if (s.equals(A256CBC_HS512.getName())) {
return A256CBC_HS512;
} else if (s.equals(A128GCM.getName())) {
return A128GCM;
} else if (s.equals(A192GCM.getName())) {
return A192GCM;
} else if (s.equals(A256GCM.getName())) {
return A256GCM;
} else if (s.equals(A128CBC_HS256_DEPRECATED.getName())) {
return A128CBC_HS256_DEPRECATED;
} else if (s.equals(A256CBC_HS512_DEPRECATED.getName())) {
return A256CBC_HS512_DEPRECATED;
} else {
return new EncryptionMethod(s);
}
}
}
/*
* nimbus-jose-jwt
*
* Copyright 2012-2016, Connect2id Ltd.
*
* Licensed 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 com.nimbusds.jose;
import java.io.Serializable;
import java.text.ParseException;
import java.util.*;
import net.minidev.json.JSONObject;
import com.nimbusds.jose.util.Base64URL;
import com.nimbusds.jose.util.JSONObjectUtils;
/**
* The base abstract class for unsecured ({@code alg=none}), JSON Web Signature
* (JWS) and JSON Web Encryption (JWE) headers.
*
* <p>The header may also include {@link #getCustomParams custom
* parameters}; these will be serialised and parsed along the registered ones.
*
* @author Vladimir Dzhuvinov
* @version 2014-08-21
*/
public abstract class Header implements Serializable {
private static final long serialVersionUID = 1L;
/**
* The algorithm ({@code alg}) parameter.
*/
private final Algorithm alg;
/**
* The JOSE object type ({@code typ}) parameter.
*/
private final JOSEObjectType typ;
/**
* The content type ({@code cty}) parameter.
*/
private final String cty;
/**
* The critical headers ({@code crit}) parameter.
*/
private final Set<String> crit;
/**
* Custom header parameters.
*/
private final Map<String,Object> customParams;
/**
* Empty custom parameters constant.
*/
private static final Map<String,Object> EMPTY_CUSTOM_PARAMS =
Collections.unmodifiableMap(new HashMap<String,Object>());
/**
* The original parsed Base64URL, {@code null} if the header was
* created from scratch.
*/
private final Base64URL parsedBase64URL;
/**
* Creates a new abstract header.
*
* @param alg The algorithm ({@code alg}) parameter. Must
* not be {@code null}.
* @param typ The type ({@code typ}) parameter,
* {@code null} if not specified.
* @param cty The content type ({@code cty}) parameter,
* {@code null} if not specified.
* @param crit The names of the critical header
* ({@code crit}) parameters, empty set or
* {@code null} if none.
* @param customParams The custom parameters, empty map or
* {@code null} if none.
* @param parsedBase64URL The parsed Base64URL, {@code null} if the
* header is created from scratch.
*/
protected Header(final Algorithm alg,
final JOSEObjectType typ,
final String cty, Set<String> crit,
final Map<String,Object> customParams,
final Base64URL parsedBase64URL) {
if (alg == null) {
throw new IllegalArgumentException("The algorithm \"alg\" header parameter must not be null");
}
this.alg = alg;
this.typ = typ;
this.cty = cty;
if (crit != null) {
// Copy and make unmodifiable
this.crit = Collections.unmodifiableSet(new HashSet<>(crit));
} else {
this.crit = null;
}
if (customParams != null) {
// Copy and make unmodifiable
this.customParams = Collections.unmodifiableMap(new HashMap<>(customParams));
} else {
this.customParams = EMPTY_CUSTOM_PARAMS;
}
this.parsedBase64URL = parsedBase64URL;
}
/**
* Deep copy constructor.
*
* @param header The header to copy. Must not be {@code null}.
*/
protected Header(final Header header) {
this(
header.getAlgorithm(),
header.getType(),
header.getContentType(),
header.getCriticalParams(),
header.getCustomParams(),
header.getParsedBase64URL());
}
/**
* Gets the algorithm ({@code alg}) parameter.
*
* @return The algorithm parameter.
*/
public Algorithm getAlgorithm() {
return alg;
}
/**
* Gets the type ({@code typ}) parameter.
*
* @return The type parameter, {@code null} if not specified.
*/
public JOSEObjectType getType() {
return typ;
}
/**
* Gets the content type ({@code cty}) parameter.
*
* @return The content type parameter, {@code null} if not specified.
*/
public String getContentType() {
return cty;
}
/**
* Gets the critical header parameters ({@code crit}) parameter.
*
* @return The names of the critical header parameters, as a
* unmodifiable set, {@code null} if not specified.
*/
public Set<String> getCriticalParams() {
return crit;
}
/**
* Gets a custom (non-registered) parameter.
*
* @param name The name of the custom parameter. Must not be
* {@code null}.
*
* @return The custom parameter, {@code null} if not specified.
*/
public Object getCustomParam(final String name) {
return customParams.get(name);
}
/**
* Gets the custom (non-registered) parameters.
*
* @return The custom parameters, as a unmodifiable map, empty map if
* none.
*/
public Map<String,Object> getCustomParams() {
return customParams;
}
/**
* Gets the original Base64URL used to create this header.
*
* @return The parsed Base64URL, {@code null} if the header was created
* from scratch.
*/
public Base64URL getParsedBase64URL() {
return parsedBase64URL;
}
/**
* Gets the names of all included parameters (registered and custom) in
* the header instance.
*
* @return The included parameters.
*/
public Set<String> getIncludedParams() {
Set<String> includedParameters =
new HashSet<>(getCustomParams().keySet());
includedParameters.add("alg");
if (getType() != null) {
includedParameters.add("typ");
}
if (getContentType() != null) {
includedParameters.add("cty");
}
if (getCriticalParams() != null && ! getCriticalParams().isEmpty()) {
includedParameters.add("crit");
}
return includedParameters;
}
/**
* Returns a JSON object representation of the header. All custom
* parameters are included if they serialise to a JSON entity and
* their names don't conflict with the registered ones.
*
* @return The JSON object representation of the header.
*/
public JSONObject toJSONObject() {
// Include custom parameters, they will be overwritten if their
// names match specified registered ones
JSONObject o = new JSONObject(customParams);
// Alg is always defined
o.put("alg", alg.toString());
if (typ != null) {
o.put("typ", typ.toString());
}
if (cty != null) {
o.put("cty", cty);
}
if (crit != null && ! crit.isEmpty()) {
o.put("crit", new ArrayList<>(crit));
}
return o;
}
/**
* Returns a JSON string representation of the header. All custom
* parameters will be included if they serialise to a JSON entity and
* their names don't conflict with the registered ones.
*
* @return The JSON string representation of the header.
*/
public String toString() {
return toJSONObject().toString();
}
/**
* Returns a Base64URL representation of the header. If the header was
* parsed always returns the original Base64URL (required for JWS
* validation and authenticated JWE decryption).
*
* @return The original parsed Base64URL representation of the header,
* or a new Base64URL representation if the header was created
* from scratch.
*/
public Base64URL toBase64URL() {
if (parsedBase64URL == null) {
// Header was created from scratch, return new Base64URL
return Base64URL.encode(toString());
} else {
// Header was parsed, return original Base64URL
return parsedBase64URL;
}
}
/**
* Parses an algorithm ({@code alg}) parameter from the specified
* header JSON object. Intended for initial parsing of unsecured
* (plain), JWS and JWE headers.
*
* <p>The algorithm type (none, JWS or JWE) is determined by inspecting
* the algorithm name for "none" and the presence of an "enc"
* parameter.
*
* @param json The JSON object to parse. Must not be {@code null}.
*
* @return The algorithm, an instance of {@link Algorithm#NONE},
* {@link JWSAlgorithm} or {@link JWEAlgorithm}.
*
* @throws ParseException If the {@code alg} parameter couldn't be
* parsed.
*/
public static Algorithm parseAlgorithm(final JSONObject json)
throws ParseException {
String algName = JSONObjectUtils.getString(json, "alg");
// Infer algorithm type
if (algName.equals(Algorithm.NONE.getName())) {
// Plain
return Algorithm.NONE;
} else if (json.containsKey("enc")) {
// JWE
return JWEAlgorithm.parse(algName);
} else {
// JWS
return JWSAlgorithm.parse(algName);
}
}
/**
* Parses a {@link PlainHeader}, {@link JWSHeader} or {@link JWEHeader}
* from the specified JSON object.
*
* @param jsonObject The JSON object to parse. Must not be
* {@code null}.
*
* @return The header.
*
* @throws ParseException If the specified JSON object doesn't
* represent a valid header.
*/
public static Header parse(final JSONObject jsonObject)
throws ParseException {
return parse(jsonObject, null);
}
/**
* Parses a {@link PlainHeader}, {@link JWSHeader} or {@link JWEHeader}
* from the specified JSON object.
*
* @param jsonObject The JSON object to parse. Must not be
* {@code null}.
* @param parsedBase64URL The original parsed Base64URL, {@code null}
* if not applicable.
*
* @return The header.
*
* @throws ParseException If the specified JSON object doesn't
* represent a valid header.
*/
public static Header parse(final JSONObject jsonObject,
final Base64URL parsedBase64URL)
throws ParseException {
Algorithm alg = parseAlgorithm(jsonObject);
if (alg.equals(Algorithm.NONE)) {
return PlainHeader.parse(jsonObject, parsedBase64URL);
} else if (alg instanceof JWSAlgorithm) {
return JWSHeader.parse(jsonObject, parsedBase64URL);
} else if (alg instanceof JWEAlgorithm) {
return JWEHeader.parse(jsonObject, parsedBase64URL);
} else {
throw new AssertionError("Unexpected algorithm type: " + alg);
}
}
/**
* Parses a {@link PlainHeader}, {@link JWSHeader} or {@link JWEHeader}
* from the specified JSON object string.
*
* @param jsonString The JSON object string to parse. Must not be
* {@code null}.
*
* @return The header.
*
* @throws ParseException If the specified JSON object string doesn't
* represent a valid header.
*/
public static Header parse(final String jsonString)
throws ParseException {
return parse(jsonString, null);
}
/**
* Parses a {@link PlainHeader}, {@link JWSHeader} or {@link JWEHeader}
* from the specified JSON object string.
*
* @param jsonString The JSON object string to parse. Must not be
* {@code null}.
* @param parsedBase64URL The original parsed Base64URL, {@code null}
* if not applicable.
*
* @return The header.
*
* @throws ParseException If the specified JSON object string doesn't
* represent a valid header.
*/
public static Header parse(final String jsonString,
final Base64URL parsedBase64URL)
throws ParseException {
JSONObject jsonObject = JSONObjectUtils.parse(jsonString);
return parse(jsonObject, parsedBase64URL);
}
/**
* Parses a {@link PlainHeader}, {@link JWSHeader} or {@link JWEHeader}
* from the specified Base64URL.
*
* @param base64URL The Base64URL to parse. Must not be {@code null}.
*
* @return The header.
*
* @throws ParseException If the specified Base64URL doesn't represent
* a valid header.
*/
public static Header parse(final Base64URL base64URL)
throws ParseException {
return parse(base64URL.decodeToString(), base64URL);
}
}
\ No newline at end of file
/*
* nimbus-jose-jwt
*
* Copyright 2012-2016, Connect2id Ltd.
*
* Licensed 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 com.nimbusds.jose;
/**
* Javascript Object Signing and Encryption (JOSE) exception.
*
* @author Vladimir Dzhuvinov
* @version 2012-09-15
*/
public class JOSEException extends Exception {
private static final long serialVersionUID = 1L;
/**
* Creates a new JOSE exception with the specified message.
*
* @param message The exception message.
*/
public JOSEException(final String message) {
super(message);
}
/**
* Creates a new JOSE exception with the specified message and cause.
*
* @param message The exception message.
* @param cause The exception cause.
*/
public JOSEException(final String message, final Throwable cause) {
super(message, cause);
}
}
/*
* nimbus-jose-jwt
*
* Copyright 2012-2016, Connect2id Ltd.
*
* Licensed 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 com.nimbusds.jose;
import java.io.Serializable;
import java.text.ParseException;
import com.nimbusds.jose.util.Base64URL;
import com.nimbusds.jose.util.JSONObjectUtils;
import net.minidev.json.JSONObject;
/**
* The base abstract class for unsecured (plain / {@code alg=none}), JSON Web
* Signature (JWS) secured and JSON Web Encryption (JWE) secured objects.
*
* @author Vladimir Dzhuvinov
* @version 2017-07-11
*/
public abstract class JOSEObject implements Serializable {
private static final long serialVersionUID = 1L;
/**
* The MIME type of JOSE objects serialised to a compact form:
* {@code application/jose; charset=UTF-8}
*/
public static final String MIME_TYPE_COMPACT = "application/jose; charset=UTF-8";
/**
* The MIME type of JOSE objects serialised to a JSON object form:
* {@code application/jose+json; charset=UTF-8}
*/
public static final String MIME_TYPE_JS = "application/jose+json; charset=UTF-8";
/**
* The payload (message), {@code null} if not specified.
*/
private Payload payload;
/**
* The original parsed Base64URL parts, {@code null} if the JOSE object
* was created from scratch. The individual parts may be empty or
* {@code null} to indicate a missing part.
*/
private Base64URL[] parsedParts;
/**
* Creates a new JOSE object. The payload and the original parsed
* Base64URL parts are not defined.
*/
protected JOSEObject() {
payload = null;
parsedParts = null;
}
/**
* Creates a new JOSE object with the specified payload.
*
* @param payload The payload, {@code null} if not available (e.g for
* an encrypted JWE object).
*/
protected JOSEObject(final Payload payload) {
this.payload = payload;
}
/**
* Returns the header of this JOSE object.
*
* @return The header.
*/
public abstract Header getHeader();
/**
* Sets the payload of this JOSE object.
*
* @param payload The payload, {@code null} if not available (e.g. for
* an encrypted JWE object).
*/
protected void setPayload(final Payload payload) {
this.payload = payload;
}
/**
* Returns the payload of this JOSE object.
*
* @return The payload, {@code null} if not available (for an encrypted
* JWE object that hasn't been decrypted).
*/
public Payload getPayload() {
return payload;
}
/**
* Sets the original parsed Base64URL parts used to create this JOSE
* object.
*
* @param parts The original Base64URL parts used to creates this JOSE
* object, {@code null} if the object was created from
* scratch. The individual parts may be empty or
* {@code null} to indicate a missing part.
*/
protected void setParsedParts(final Base64URL... parts) {
parsedParts = parts;
}
/**
* Returns the original parsed Base64URL parts used to create this JOSE
* object.
*
* @return The original Base64URL parts used to creates this JOSE
* object, {@code null} if the object was created from scratch.
* The individual parts may be empty or {@code null} to
* indicate a missing part.
*/
public Base64URL[] getParsedParts() {
return parsedParts;
}
/**
* Returns the original parsed string used to create this JOSE object.
*
* @see #getParsedParts
*
* @return The parsed string used to create this JOSE object,
* {@code null} if the object was creates from scratch.
*/
public String getParsedString() {
if (parsedParts == null) {
return null;
}
StringBuilder sb = new StringBuilder();
for (Base64URL part: parsedParts) {
if (sb.length() > 0) {
sb.append('.');
}
if (part != null) {
sb.append(part.toString());
}
}
return sb.toString();
}
/**
* Serialises this JOSE object to its compact format consisting of
* Base64URL-encoded parts delimited by period ('.') characters.
*
* @return The serialised JOSE object.
*
* @throws IllegalStateException If the JOSE object is not in a state
* that permits serialisation.
*/
public abstract String serialize();
/**
* Splits a compact serialised JOSE object into its Base64URL-encoded
* parts.
*
* @param s The compact serialised JOSE object to split. Must not be
* {@code null}.
*
* @return The JOSE Base64URL-encoded parts (three for unsecured and
* JWS objects, five for JWE objects).
*
* @throws ParseException If the specified string couldn't be split
* into three or five Base64URL-encoded parts.
*/
public static Base64URL[] split(final String s)
throws ParseException {
final String t = s.trim();
// We must have 2 (JWS) or 4 dots (JWE)
// String.split() cannot handle empty parts
final int dot1 = t.indexOf(".");
if (dot1 == -1) {
throw new ParseException("Invalid serialized unsecured/JWS/JWE object: Missing part delimiters", 0);
}
final int dot2 = t.indexOf(".", dot1 + 1);
if (dot2 == -1) {
throw new ParseException("Invalid serialized unsecured/JWS/JWE object: Missing second delimiter", 0);
}
// Third dot for JWE only
final int dot3 = t.indexOf(".", dot2 + 1);
if (dot3 == -1) {
// Two dots only? -> We have a JWS
Base64URL[] parts = new Base64URL[3];
parts[0] = new Base64URL(t.substring(0, dot1));
parts[1] = new Base64URL(t.substring(dot1 + 1, dot2));
parts[2] = new Base64URL(t.substring(dot2 + 1));
return parts;
}
// Fourth final dot for JWE
final int dot4 = t.indexOf(".", dot3 + 1);
if (dot4 == -1) {
throw new ParseException("Invalid serialized JWE object: Missing fourth delimiter", 0);
}
if (dot4 != -1 && t.indexOf(".", dot4 + 1) != -1) {
throw new ParseException("Invalid serialized unsecured/JWS/JWE object: Too many part delimiters", 0);
}
// Four dots -> five parts
Base64URL[] parts = new Base64URL[5];
parts[0] = new Base64URL(t.substring(0, dot1));
parts[1] = new Base64URL(t.substring(dot1 + 1, dot2));
parts[2] = new Base64URL(t.substring(dot2 + 1, dot3));
parts[3] = new Base64URL(t.substring(dot3 + 1, dot4));
parts[4] = new Base64URL(t.substring(dot4 + 1));
return parts;
}
/**
* Parses a JOSE object from the specified string in compact format.
*
* @param s The string to parse. Must not be {@code null}.
*
* @return The corresponding {@link PlainObject}, {@link JWSObject} or
* {@link JWEObject} instance.
*
* @throws ParseException If the string couldn't be parsed to a valid
* unsecured, JWS or JWE object.
*/
public static JOSEObject parse(final String s)
throws ParseException {
Base64URL[] parts = split(s);
JSONObject jsonObject;
try {
jsonObject = JSONObjectUtils.parse(parts[0].decodeToString());
} catch (ParseException e) {
throw new ParseException("Invalid unsecured/JWS/JWE header: " + e.getMessage(), 0);
}
Algorithm alg = Header.parseAlgorithm(jsonObject);
if (alg.equals(Algorithm.NONE)) {
return PlainObject.parse(s);
} else if (alg instanceof JWSAlgorithm) {
return JWSObject.parse(s);
} else if (alg instanceof JWEAlgorithm) {
return JWEObject.parse(s);
} else {
throw new AssertionError("Unexpected algorithm type: " + alg);
}
}
}
/*
* nimbus-jose-jwt
*
* Copyright 2012-2016, Connect2id Ltd.
*
* Licensed 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 com.nimbusds.jose;
import java.io.Serializable;
import net.jcip.annotations.Immutable;
import net.minidev.json.JSONAware;
import net.minidev.json.JSONObject;
/**
* JOSE object type, represents the {@code typ} header parameter in unsecured,
* JSON Web Signature (JWS) and JSON Web Encryption (JWE) objects. This class
* is immutable.
*
* <p>Includes constants for the following standard types:
*
* <ul>
* <li>{@link #JOSE}
* <li>{@link #JOSE_JSON JOSE+JSON}
* <li>{@link #JWT}
* </ul>
*
* <p>Additional types can be defined using the constructor.
*
* @author Vladimir Dzhuvinov
* @version 2014-02-15
*/
@Immutable
public final class JOSEObjectType implements JSONAware, Serializable {
private static final long serialVersionUID = 1L;
/**
* Compact encoded JOSE object type.
*/
public static final JOSEObjectType JOSE = new JOSEObjectType("JOSE");
/**
* JSON-encoded JOSE object type..
*/
public static final JOSEObjectType JOSE_JSON = new JOSEObjectType("JOSE+JSON");
/**
* JSON Web Token (JWT) object type.
*/
public static final JOSEObjectType JWT = new JOSEObjectType("JWT");
/**
* The object type.
*/
private final String type;
/**
* Creates a new JOSE object type.
*
* @param type The object type. Must not be {@code null}.
*/
public JOSEObjectType(final String type) {
if (type == null) {
throw new IllegalArgumentException("The object type must not be null");
}
this.type = type;
}
/**
* Gets the JOSE object type.
*
* @return The JOSE object type.
*/
public String getType() {
return type;
}
/**
* Overrides {@code Object.hashCode()}.
*
* @return The object hash code.
*/
@Override
public int hashCode() {
return type.hashCode();
}
/**
* Overrides {@code Object.equals()}.
*
* @param object The object to compare to.
*
* @return {@code true} if the objects have the same value, otherwise
* {@code false}.
*/
@Override
public boolean equals(final Object object) {
return object != null &&
object instanceof JOSEObjectType &&
this.toString().equals(object.toString());
}
/**
* Returns the string representation of this JOSE object type.
*
* @see #getType
*
* @return The string representation.
*/
@Override
public String toString() {
return type;
}
/**
* Returns the JSON string representation of this JOSE object type.
*
* @return The JSON string representation.
*/
@Override
public String toJSONString() {
return "\"" + JSONObject.escape(type) + '"';
}
}
/*
* nimbus-jose-jwt
*
* Copyright 2012-2016, Connect2id Ltd.
*
* Licensed 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 com.nimbusds.jose;
/**
* JavaScript Object Signing and Encryption (JOSE) provider.
*
* @author Vladimir Dzhuvinov
* @version 2015-05-26
*/
public interface JOSEProvider { }
/*
* nimbus-jose-jwt
*
* Copyright 2012-2016, Connect2id Ltd.
*
* Licensed 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 com.nimbusds.jose;
import com.nimbusds.jose.util.ArrayUtils;
import net.jcip.annotations.Immutable;
/**
* JSON Web Encryption (JWE) algorithm name, represents the {@code alg} header
* parameter in JWE objects. This class is immutable.
*
* <p>Includes constants for the following standard JWE algorithm names:
*
* <ul>
* <li>{@link #RSA_OAEP_256 RSA-OAEP-256}
* <li>{@link #RSA_OAEP RSA-OAEP} (deprecated)
* <li>{@link #RSA1_5} (deprecated)
* <li>{@link #A128KW}
* <li>{@link #A192KW}
* <li>{@link #A256KW}
* <li>{@link #DIR dir}
* <li>{@link #ECDH_ES ECDH-ES}
* <li>{@link #ECDH_ES_A128KW ESDH-ES+A128KW}
* <li>{@link #ECDH_ES_A128KW ESDH-ES+A192KW}
* <li>{@link #ECDH_ES_A256KW ESDH-ES+A256KW}
* <li>{@link #PBES2_HS256_A128KW PBES2-HS256+A128KW}
* <li>{@link #PBES2_HS384_A192KW PBES2-HS256+A192KW}
* <li>{@link #PBES2_HS512_A256KW PBES2-HS256+A256KW}
* </ul>
*
* <p>Additional JWE algorithm names can be defined using the constructors.
*
* @author Vladimir Dzhuvinov
* @version 2017-04-09
*/
@Immutable
public final class JWEAlgorithm extends Algorithm {
private static final long serialVersionUID = 1L;
/**
* RSAES-PKCS1-V1_5 (RFC 3447). Use of this RSA encryption algorithm is
* no longer recommended, use {@link #RSA_OAEP_256} instead.
*/
@Deprecated
public static final JWEAlgorithm RSA1_5 = new JWEAlgorithm("RSA1_5", Requirement.REQUIRED);
/**
* RSAES using Optimal Asymmetric Encryption Padding (OAEP) (RFC 3447),
* with the default parameters specified by RFC 3447 in section A.2.1.
* Use of this encryption algorithm is no longer recommended, use
* {@link #RSA_OAEP_256} instead.
*/
@Deprecated
public static final JWEAlgorithm RSA_OAEP = new JWEAlgorithm("RSA-OAEP", Requirement.OPTIONAL);
/**
* RSAES using Optimal Asymmetric Encryption Padding (OAEP) (RFC 3447),
* with the SHA-256 hash function and the MGF1 with SHA-256 mask
* generation function.
*/
public static final JWEAlgorithm RSA_OAEP_256 = new JWEAlgorithm("RSA-OAEP-256", Requirement.OPTIONAL);
/**
* Advanced Encryption Standard (AES) Key Wrap Algorithm (RFC 3394)
* using 128 bit keys.
*/
public static final JWEAlgorithm A128KW = new JWEAlgorithm("A128KW", Requirement.RECOMMENDED);
/**
* Advanced Encryption Standard (AES) Key Wrap Algorithm (RFC 3394)
* using 192 bit keys.
*/
public static final JWEAlgorithm A192KW = new JWEAlgorithm("A192KW", Requirement.OPTIONAL);
/**
* Advanced Encryption Standard (AES) Key Wrap Algorithm (RFC 3394)
* using 256 bit keys.
*/
public static final JWEAlgorithm A256KW = new JWEAlgorithm("A256KW", Requirement.RECOMMENDED);
/**
* Direct use of a shared symmetric key as the Content Encryption Key
* (CEK) for the block encryption step (rather than using the symmetric
* key to wrap the CEK).
*/
public static final JWEAlgorithm DIR = new JWEAlgorithm("dir", Requirement.RECOMMENDED);
/**
* Elliptic Curve Diffie-Hellman Ephemeral Static (RFC 6090) key
* agreement using the Concat KDF, as defined in section 5.8.1 of
* NIST.800-56A, with the agreed-upon key being used directly as the
* Content Encryption Key (CEK) (rather than being used to wrap the
* CEK).
*/
public static final JWEAlgorithm ECDH_ES = new JWEAlgorithm("ECDH-ES", Requirement.RECOMMENDED);
/**
* Elliptic Curve Diffie-Hellman Ephemeral Static key agreement per
* "ECDH-ES", but where the agreed-upon key is used to wrap the Content
* Encryption Key (CEK) with the "A128KW" function (rather than being
* used directly as the CEK).
*/
public static final JWEAlgorithm ECDH_ES_A128KW = new JWEAlgorithm("ECDH-ES+A128KW", Requirement.RECOMMENDED);
/**
* Elliptic Curve Diffie-Hellman Ephemeral Static key agreement per
* "ECDH-ES", but where the agreed-upon key is used to wrap the Content
* Encryption Key (CEK) with the "A192KW" function (rather than being
* used directly as the CEK).
*/
public static final JWEAlgorithm ECDH_ES_A192KW = new JWEAlgorithm("ECDH-ES+A192KW", Requirement.OPTIONAL);
/**
* Elliptic Curve Diffie-Hellman Ephemeral Static key agreement per
* "ECDH-ES", but where the agreed-upon key is used to wrap the Content
* Encryption Key (CEK) with the "A256KW" function (rather than being
* used directly as the CEK).
*/
public static final JWEAlgorithm ECDH_ES_A256KW = new JWEAlgorithm("ECDH-ES+A256KW", Requirement.RECOMMENDED);
/**
* AES in Galois/Counter Mode (GCM) (NIST.800-38D) 128 bit keys.
*/
public static final JWEAlgorithm A128GCMKW = new JWEAlgorithm("A128GCMKW", Requirement.OPTIONAL);
/**
* AES in Galois/Counter Mode (GCM) (NIST.800-38D) 192 bit keys.
*/
public static final JWEAlgorithm A192GCMKW = new JWEAlgorithm("A192GCMKW", Requirement.OPTIONAL);
/**
* AES in Galois/Counter Mode (GCM) (NIST.800-38D) 256 bit keys.
*/
public static final JWEAlgorithm A256GCMKW = new JWEAlgorithm("A256GCMKW", Requirement.OPTIONAL);
/**
* PBES2 (RFC 2898) with HMAC SHA-256 as the PRF and AES Key Wrap
* (RFC 3394) using 128 bit keys for the encryption scheme.
*/
public static final JWEAlgorithm PBES2_HS256_A128KW = new JWEAlgorithm("PBES2-HS256+A128KW", Requirement.OPTIONAL);
/**
* PBES2 (RFC 2898) with HMAC SHA-384 as the PRF and AES Key Wrap
* (RFC 3394) using 192 bit keys for the encryption scheme.
*/
public static final JWEAlgorithm PBES2_HS384_A192KW = new JWEAlgorithm("PBES2-HS384+A192KW", Requirement.OPTIONAL);
/**
* PBES2 (RFC 2898) with HMAC SHA-512 as the PRF and AES Key Wrap
* (RFC 3394) using 256 bit keys for the encryption scheme.
*/
public static final JWEAlgorithm PBES2_HS512_A256KW = new JWEAlgorithm("PBES2-HS512+A256KW", Requirement.OPTIONAL);
/**
* JWE algorithm family.
*/
public static final class Family extends AlgorithmFamily<JWEAlgorithm> {
private static final long serialVersionUID = 1L;
/**
* RSA key encryption.
*/
public static final Family RSA = new Family(RSA1_5, RSA_OAEP, RSA_OAEP_256);
/**
* AES key wrap.
*/
public static final Family AES_KW = new Family(A128KW, A192KW, A256KW);
/**
* Elliptic Curve Diffie-Hellman Ephemeral Static key
* agreement.
*/
public static final Family ECDH_ES = new Family(JWEAlgorithm.ECDH_ES, ECDH_ES_A128KW, ECDH_ES_A192KW, ECDH_ES_A256KW);
/**
* AES GCM key wrap.
*/
public static final Family AES_GCM_KW = new Family(A128GCMKW, A192GCMKW, A256GCMKW);
/**
* Password-Based Cryptography Specification Version 2.0
*/
public static final Family PBES2 = new Family(PBES2_HS256_A128KW, PBES2_HS384_A192KW, PBES2_HS512_A256KW);
/**
* Super family of all asymmetric (public / private key based)
* JWE algorithms.
*/
public static final Family ASYMMETRIC = new Family(ArrayUtils.concat(
RSA.toArray(new JWEAlgorithm[]{}),
ECDH_ES.toArray(new JWEAlgorithm[]{})));
/**
* Super family of all symmetric (shared key based) JWE
* algorithms.
*/
public static final Family SYMMETRIC = new Family(ArrayUtils.concat(
AES_KW.toArray(new JWEAlgorithm[]{}),
AES_GCM_KW.toArray(new JWEAlgorithm[]{}),
new JWEAlgorithm[]{JWEAlgorithm.DIR}));
/***
* Creates a new JWE algorithm family.
*
* @param algs The JWE algorithms of the family. Must not be
* {@code null}.
*/
public Family(final JWEAlgorithm ... algs) {
super(algs);
}
}
/**
* Creates a new JSON Web Encryption (JWE) algorithm.
*
* @param name The algorithm name. Must not be {@code null}.
* @param req The implementation requirement, {@code null} if not
* known.
*/
public JWEAlgorithm(final String name, final Requirement req) {
super(name, req);
}
/**
* Creates a new JSON Web Encryption (JWE) algorithm.
*
* @param name The algorithm name. Must not be {@code null}.
*/
public JWEAlgorithm(final String name) {
super(name, null);
}
/**
* Parses a JWE algorithm from the specified string.
*
* @param s The string to parse. Must not be {@code null}.
*
* @return The JWE algorithm (matching standard algorithm constant, else
* a newly created algorithm).
*/
public static JWEAlgorithm parse(final String s) {
if (s.equals(RSA1_5.getName())) {
return RSA1_5;
} else if (s.equals(RSA_OAEP.getName())) {
return RSA_OAEP;
} else if (s.equals(RSA_OAEP_256.getName())) {
return RSA_OAEP_256;
} else if (s.equals(A128KW.getName())) {
return A128KW;
} else if (s.equals(A192KW.getName())) {
return A192KW;
} else if (s.equals(A256KW.getName())) {
return A256KW;
} else if (s.equals(DIR.getName())) {
return DIR;
} else if (s.equals(ECDH_ES.getName())) {
return ECDH_ES;
} else if (s.equals(ECDH_ES_A128KW.getName())) {
return ECDH_ES_A128KW;
} else if (s.equals(ECDH_ES_A192KW.getName())) {
return ECDH_ES_A192KW;
} else if (s.equals(ECDH_ES_A256KW.getName())) {
return ECDH_ES_A256KW;
} else if (s.equals(A128GCMKW.getName())) {
return A128GCMKW;
} else if (s.equals(A192GCMKW.getName())) {
return A192GCMKW;
} else if (s.equals(A256GCMKW.getName())) {
return A256GCMKW;
} else if (s.equals(PBES2_HS256_A128KW.getName())) {
return PBES2_HS256_A128KW;
} else if (s.equals(PBES2_HS384_A192KW.getName())) {
return PBES2_HS384_A192KW;
} else if (s.equals(PBES2_HS512_A256KW.getName())) {
return PBES2_HS512_A256KW;
} else {
return new JWEAlgorithm(s);
}
}
}
/*
* nimbus-jose-jwt
*
* Copyright 2012-2016, Connect2id Ltd.
*
* Licensed 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 com.nimbusds.jose;
import net.jcip.annotations.Immutable;
import com.nimbusds.jose.util.Base64URL;
/**
* The cryptographic parts of a JSON Web Encryption (JWE) object. This class is
* an immutable wrapper for returning the cipher text, initialisation vector
* (IV), encrypted key and authentication authTag from {@link JWEEncrypter}
* implementations.
*
* @author Vladimir Dzhuvinov
* @version 2014-07-11
*/
@Immutable
public final class JWECryptoParts {
/**
* The modified JWE header (optional).
*/
private final JWEHeader header;
/**
* The encrypted key (optional).
*/
private final Base64URL encryptedKey;
/**
* The initialisation vector (optional).
*/
private final Base64URL iv;
/**
* The cipher text.
*/
private final Base64URL cipherText;
/**
* The authentication tag (optional).
*/
private final Base64URL authenticationTag;
/**
* Creates a new cryptographic JWE parts instance.
*
* @param encryptedKey The encrypted key, {@code null} if not
* required by the encryption algorithm.
* @param iv The initialisation vector (IV),
* {@code null} if not required by the
* encryption algorithm.
* @param cipherText The cipher text. Must not be {@code null}.
* @param authenticationTag The authentication tag, {@code null} if the
* JWE algorithm provides built-in integrity
* check.
*/
public JWECryptoParts(final Base64URL encryptedKey,
final Base64URL iv,
final Base64URL cipherText,
final Base64URL authenticationTag) {
this(null, encryptedKey, iv, cipherText, authenticationTag);
}
/**
* Creates a new cryptographic JWE parts instance.
*
* @param header The modified JWE header, {@code null} if
* not.
* @param encryptedKey The encrypted key, {@code null} if not
* required by the encryption algorithm.
* @param iv The initialisation vector (IV),
* {@code null} if not required by the
* encryption algorithm.
* @param cipherText The cipher text. Must not be {@code null}.
* @param authenticationTag The authentication tag, {@code null} if the
* JWE algorithm provides built-in integrity
* check.
*/
public JWECryptoParts(final JWEHeader header,
final Base64URL encryptedKey,
final Base64URL iv,
final Base64URL cipherText,
final Base64URL authenticationTag) {
this.header = header;
this.encryptedKey = encryptedKey;
this.iv = iv;
if (cipherText == null) {
throw new IllegalArgumentException("The cipher text must not be null");
}
this.cipherText = cipherText;
this.authenticationTag = authenticationTag;
}
/**
* Gets the modified JWE header.
*
* @return The modified JWE header, {@code null} of not.
*/
public JWEHeader getHeader() {
return header;
}
/**
* Gets the encrypted key.
*
* @return The encrypted key, {@code null} if not required by
* the JWE algorithm.
*/
public Base64URL getEncryptedKey() {
return encryptedKey;
}
/**
* Gets the initialisation vector (IV).
*
* @return The initialisation vector (IV), {@code null} if not required
* by the JWE algorithm.
*/
public Base64URL getInitializationVector() {
return iv;
}
/**
* Gets the cipher text.
*
* @return The cipher text.
*/
public Base64URL getCipherText() {
return cipherText;
}
/**
* Gets the authentication tag.
*
* @return The authentication tag, {@code null} if the encryption
* algorithm provides built-in integrity checking.
*/
public Base64URL getAuthenticationTag() {
return authenticationTag;
}
}
/*
* nimbus-jose-jwt
*
* Copyright 2012-2016, Connect2id Ltd.
*
* Licensed 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 com.nimbusds.jose;
import com.nimbusds.jose.util.Base64URL;
/**
* JSON Web Encryption (JWE) decrypter.
*
* @author Vladimir Dzhuvinov
* @version 2015-04-21
*/
public interface JWEDecrypter extends JWEProvider {
/**
* Decrypts the specified cipher text of a {@link JWEObject JWE Object}.
*
* @param header The JSON Web Encryption (JWE) header. Must
* specify a supported JWE algorithm and method.
* Must not be {@code null}.
* @param encryptedKey The encrypted key, {@code null} if not required
* by the JWE algorithm.
* @param iv The initialisation vector, {@code null} if not
* required by the JWE algorithm.
* @param cipherText The cipher text to decrypt. Must not be
* {@code null}.
* @param authTag The authentication tag, {@code null} if not
* required.
*
* @return The clear text.
*
* @throws JOSEException If the JWE algorithm or method is not
* supported, if a critical header parameter is
* not supported or marked for deferral to the
* application, or if decryption failed for some
* other reason.
*/
byte[] decrypt(final JWEHeader header,
final Base64URL encryptedKey,
final Base64URL iv,
final Base64URL cipherText,
final Base64URL authTag)
throws JOSEException;
}
/*
* nimbus-jose-jwt
*
* Copyright 2012-2016, Connect2id Ltd.
*
* Licensed 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 com.nimbusds.jose;
/**
* JSON Web Encryption (JWE) encrypter.
*
* @author Vladimir Dzhuvinov
* @version 2015-05-21
*/
public interface JWEEncrypter extends JWEProvider {
/**
* Encrypts the specified clear text of a {@link JWEObject JWE object}.
*
* @param header The JSON Web Encryption (JWE) header. Must specify
* a supported JWE algorithm and method. Must not be
* {@code null}.
* @param clearText The clear text to encrypt. Must not be {@code null}.
*
* @return The resulting JWE crypto parts.
*
* @throws JOSEException If the JWE algorithm or method is not
* supported or if encryption failed for some
* other internal reason.
*/
JWECryptoParts encrypt(final JWEHeader header, final byte[] clearText)
throws JOSEException;
}
/*
* nimbus-jose-jwt
*
* Copyright 2012-2016, Connect2id Ltd.
*
* Licensed 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 com.nimbusds.jose;
import java.text.ParseException;
import net.jcip.annotations.ThreadSafe;
import com.nimbusds.jose.util.Base64URL;
/**
* JSON Web Encryption (JWE) secured object. This class is thread-safe.
*
* @author Vladimir Dzhuvinov
* @version 2016-04-13
*/
@ThreadSafe
public class JWEObject extends JOSEObject {
private static final long serialVersionUID = 1L;
/**
* Enumeration of the states of a JSON Web Encryption (JWE) object.
*/
public enum State {
/**
* The JWE object is created but not encrypted yet.
*/
UNENCRYPTED,
/**
* The JWE object is encrypted.
*/
ENCRYPTED,
/**
* The JWE object is decrypted.
*/
DECRYPTED
}
/**
* The header.
*/
private JWEHeader header;
/**
* The encrypted key, {@code null} if not computed or applicable.
*/
private Base64URL encryptedKey;
/**
* The initialisation vector, {@code null} if not generated or
* applicable.
*/
private Base64URL iv;
/**
* The cipher text, {@code null} if not computed.
*/
private Base64URL cipherText;
/**
* The authentication tag, {@code null} if not computed or applicable.
*/
private Base64URL authTag;
/**
* The JWE object state.
*/
private State state;
/**
* Creates a new to-be-encrypted JSON Web Encryption (JWE) object with
* the specified header and payload. The initial state will be
* {@link State#UNENCRYPTED unencrypted}.
*
* @param header The JWE header. Must not be {@code null}.
* @param payload The payload. Must not be {@code null}.
*/
public JWEObject(final JWEHeader header, final Payload payload) {
if (header == null) {
throw new IllegalArgumentException("The JWE header must not be null");
}
this.header = header;
if (payload == null) {
throw new IllegalArgumentException("The payload must not be null");
}
setPayload(payload);
encryptedKey = null;
cipherText = null;
state = State.UNENCRYPTED;
}
/**
* Creates a new encrypted JSON Web Encryption (JWE) object with the
* specified serialised parts. The state will be {@link State#ENCRYPTED
* encrypted}.
*
* @param firstPart The first part, corresponding to the JWE header.
* Must not be {@code null}.
* @param secondPart The second part, corresponding to the encrypted
* key. Empty or {@code null} if none.
* @param thirdPart The third part, corresponding to the
* initialisation vector. Empty or {@code null} if
* none.
* @param fourthPart The fourth part, corresponding to the cipher text.
* Must not be {@code null}.
* @param fifthPart The fifth part, corresponding to the
* authentication tag. Empty of {@code null} if none.
*
* @throws ParseException If parsing of the serialised parts failed.
*/
public JWEObject(final Base64URL firstPart,
final Base64URL secondPart,
final Base64URL thirdPart,
final Base64URL fourthPart,
final Base64URL fifthPart)
throws ParseException {
if (firstPart == null) {
throw new IllegalArgumentException("The first part must not be null");
}
try {
this.header = JWEHeader.parse(firstPart);
} catch (ParseException e) {
throw new ParseException("Invalid JWE header: " + e.getMessage(), 0);
}
if (secondPart == null || secondPart.toString().isEmpty()) {
encryptedKey = null;
} else {
encryptedKey = secondPart;
}
if (thirdPart == null || thirdPart.toString().isEmpty()) {
iv = null;
} else {
iv = thirdPart;
}
if (fourthPart == null) {
throw new IllegalArgumentException("The fourth part must not be null");
}
cipherText = fourthPart;
if (fifthPart == null || fifthPart.toString().isEmpty()) {
authTag = null;
} else {
authTag = fifthPart;
}
state = State.ENCRYPTED; // but not decrypted yet!
setParsedParts(firstPart, secondPart, thirdPart, fourthPart, fifthPart);
}
@Override
public JWEHeader getHeader() {
return header;
}
/**
* Returns the encrypted key of this JWE object.
*
* @return The encrypted key, {@code null} not applicable or the JWE
* object has not been encrypted yet.
*/
public Base64URL getEncryptedKey() {
return encryptedKey;
}
/**
* Returns the initialisation vector (IV) of this JWE object.
*
* @return The initialisation vector (IV), {@code null} if not
* applicable or the JWE object has not been encrypted yet.
*/
public Base64URL getIV() {
return iv;
}
/**
* Returns the cipher text of this JWE object.
*
* @return The cipher text, {@code null} if the JWE object has not been
* encrypted yet.
*/
public Base64URL getCipherText() {
return cipherText;
}
/**
* Returns the authentication tag of this JWE object.
*
* @return The authentication tag, {@code null} if not applicable or
* the JWE object has not been encrypted yet.
*/
public Base64URL getAuthTag() {
return authTag;
}
/**
* Returns the state of this JWE object.
*
* @return The state.
*/
public State getState() {
return state;
}
/**
* Ensures the current state is {@link State#UNENCRYPTED unencrypted}.
*
* @throws IllegalStateException If the current state is not
* unencrypted.
*/
private void ensureUnencryptedState() {
if (state != State.UNENCRYPTED) {
throw new IllegalStateException("The JWE object must be in an unencrypted state");
}
}
/**
* Ensures the current state is {@link State#ENCRYPTED encrypted}.
*
* @throws IllegalStateException If the current state is not encrypted.
*/
private void ensureEncryptedState() {
if (state != State.ENCRYPTED) {
throw new IllegalStateException("The JWE object must be in an encrypted state");
}
}
/**
* Ensures the current state is {@link State#ENCRYPTED encrypted} or
* {@link State#DECRYPTED decrypted}.
*
* @throws IllegalStateException If the current state is not encrypted
* or decrypted.
*/
private void ensureEncryptedOrDecryptedState() {
if (state != State.ENCRYPTED && state != State.DECRYPTED) {
throw new IllegalStateException("The JWE object must be in an encrypted or decrypted state");
}
}
/**
* Ensures the specified JWE encrypter supports the algorithms of this
* JWE object.
*
* @throws JOSEException If the JWE algorithms are not supported.
*/
private void ensureJWEEncrypterSupport(final JWEEncrypter encrypter)
throws JOSEException {
if (! encrypter.supportedJWEAlgorithms().contains(getHeader().getAlgorithm())) {
throw new JOSEException("The \"" + getHeader().getAlgorithm() +
"\" algorithm is not supported by the JWE encrypter: Supported algorithms: " + encrypter.supportedJWEAlgorithms());
}
if (! encrypter.supportedEncryptionMethods().contains(getHeader().getEncryptionMethod())) {
throw new JOSEException("The \"" + getHeader().getEncryptionMethod() +
"\" encryption method or key size is not supported by the JWE encrypter: Supported methods: " + encrypter.supportedEncryptionMethods());
}
}
/**
* Encrypts this JWE object with the specified encrypter. The JWE
* object must be in an {@link State#UNENCRYPTED unencrypted} state.
*
* @param encrypter The JWE encrypter. Must not be {@code null}.
*
* @throws IllegalStateException If the JWE object is not in an
* {@link State#UNENCRYPTED unencrypted
* state}.
* @throws JOSEException If the JWE object couldn't be
* encrypted.
*/
public synchronized void encrypt(final JWEEncrypter encrypter)
throws JOSEException {
ensureUnencryptedState();
ensureJWEEncrypterSupport(encrypter);
JWECryptoParts parts;
try {
parts = encrypter.encrypt(getHeader(), getPayload().toBytes());
} catch (JOSEException e) {
throw e;
} catch (Exception e) {
// Prevent throwing unchecked exceptions at this point,
// see issue #20
throw new JOSEException(e.getMessage(), e);
}
// Check if the header has been modified
if (parts.getHeader() != null) {
header = parts.getHeader();
}
encryptedKey = parts.getEncryptedKey();
iv = parts.getInitializationVector();
cipherText = parts.getCipherText();
authTag = parts.getAuthenticationTag();
state = State.ENCRYPTED;
}
/**
* Decrypts this JWE object with the specified decrypter. The JWE
* object must be in a {@link State#ENCRYPTED encrypted} state.
*
* @param decrypter The JWE decrypter. Must not be {@code null}.
*
* @throws IllegalStateException If the JWE object is not in an
* {@link State#ENCRYPTED encrypted
* state}.
* @throws JOSEException If the JWE object couldn't be
* decrypted.
*/
public synchronized void decrypt(final JWEDecrypter decrypter)
throws JOSEException {
ensureEncryptedState();
try {
setPayload(new Payload(decrypter.decrypt(getHeader(),
getEncryptedKey(),
getIV(),
getCipherText(),
getAuthTag())));
} catch (JOSEException e) {
throw e;
} catch (Exception e) {
// Prevent throwing unchecked exceptions at this point,
// see issue #20
throw new JOSEException(e.getMessage(), e);
}
state = State.DECRYPTED;
}
/**
* Serialises this JWE object to its compact format consisting of
* Base64URL-encoded parts delimited by period ('.') characters. It
* must be in a {@link State#ENCRYPTED encrypted} or
* {@link State#DECRYPTED decrypted} state.
*
* <pre>
* [header-base64url].[encryptedKey-base64url].[iv-base64url].[cipherText-base64url].[authTag-base64url]
* </pre>
*
* @return The serialised JWE object.
*
* @throws IllegalStateException If the JWE object is not in a
* {@link State#ENCRYPTED encrypted} or
* {@link State#DECRYPTED decrypted
* state}.
*/
@Override
public String serialize() {
ensureEncryptedOrDecryptedState();
StringBuilder sb = new StringBuilder(header.toBase64URL().toString());
sb.append('.');
if (encryptedKey != null) {
sb.append(encryptedKey.toString());
}
sb.append('.');
if (iv != null) {
sb.append(iv.toString());
}
sb.append('.');
sb.append(cipherText.toString());
sb.append('.');
if (authTag != null) {
sb.append(authTag.toString());
}
return sb.toString();
}
/**
* Parses a JWE object from the specified string in compact form. The
* parsed JWE object will be given an {@link State#ENCRYPTED} state.
*
* @param s The string to parse. Must not be {@code null}.
*
* @return The JWE object.
*
* @throws ParseException If the string couldn't be parsed to a valid
* JWE object.
*/
public static JWEObject parse(final String s)
throws ParseException {
Base64URL[] parts = JOSEObject.split(s);
if (parts.length != 5) {
throw new ParseException("Unexpected number of Base64URL parts, must be five", 0);
}
return new JWEObject(parts[0], parts[1], parts[2], parts[3], parts[4]);
}
}
/*
* nimbus-jose-jwt
*
* Copyright 2012-2016, Connect2id Ltd.
*
* Licensed 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 com.nimbusds.jose;
import java.util.Set;
import com.nimbusds.jose.jca.JCAAware;
import com.nimbusds.jose.jca.JWEJCAContext;
/**
* JSON Web Encryption (JWE) provider.
*
* <p>The JWE provider can be queried to determine its algorithm capabilities.
*
* @author Vladimir Dzhuvinov
* @version 2015-05-26
*/
public interface JWEProvider extends JOSEProvider, JCAAware<JWEJCAContext> {
/**
* Returns the names of the supported algorithms by the JWE provider
* instance. These correspond to the {@code alg} JWE header parameter.
*
* @return The supported JWE algorithms, empty set if none.
*/
Set<JWEAlgorithm> supportedJWEAlgorithms();
/**
* Returns the names of the supported encryption methods by the JWE
* provier. These correspond to the {@code enc} JWE header parameter.
*
* @return The supported encryption methods, empty set if none.
*/
Set<EncryptionMethod> supportedEncryptionMethods();
}
/*
* nimbus-jose-jwt
*
* Copyright 2012-2016, Connect2id Ltd.
*
* Licensed 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 com.nimbusds.jose;
import com.nimbusds.jose.util.ArrayUtils;
import net.jcip.annotations.Immutable;
/**
* JSON Web Signature (JWS) algorithm name, represents the {@code alg} header
* parameter in JWS objects. Also used to represent integrity algorithm
* ({@code ia}) header parameters in JWE objects. This class is immutable.
*
* <p>Includes constants for the following standard JWS algorithm names:
*
* <ul>
* <li>{@link #HS256}
* <li>{@link #HS384}
* <li>{@link #HS512}
* <li>{@link #RS256}
* <li>{@link #RS384}
* <li>{@link #RS512}
* <li>{@link #ES256}
* <li>{@link #ES384}
* <li>{@link #ES512}
* <li>{@link #PS256}
* <li>{@link #PS384}
* <li>{@link #PS512}
* <li>{@link #EdDSA}
* <li>{@link #ES256K} (non-standard)
* </ul>
*
* <p>Additional JWS algorithm names can be defined using the constructors.
*
* @author Vladimir Dzhuvinov
* @author Aleksei Doroganov
* @version 2018-03-28
*/
@Immutable
public final class JWSAlgorithm extends Algorithm {
private static final long serialVersionUID = 1L;
/**
* HMAC using SHA-256 hash algorithm (required).
*/
public static final JWSAlgorithm HS256 = new JWSAlgorithm("HS256", Requirement.REQUIRED);
/**
* HMAC using SHA-384 hash algorithm (optional).
*/
public static final JWSAlgorithm HS384 = new JWSAlgorithm("HS384", Requirement.OPTIONAL);
/**
* HMAC using SHA-512 hash algorithm (optional).
*/
public static final JWSAlgorithm HS512 = new JWSAlgorithm("HS512", Requirement.OPTIONAL);
/**
* RSASSA-PKCS-v1_5 using SHA-256 hash algorithm (recommended).
*/
public static final JWSAlgorithm RS256 = new JWSAlgorithm("RS256", Requirement.RECOMMENDED);
/**
* RSASSA-PKCS-v1_5 using SHA-384 hash algorithm (optional).
*/
public static final JWSAlgorithm RS384 = new JWSAlgorithm("RS384", Requirement.OPTIONAL);
/**
* RSASSA-PKCS-v1_5 using SHA-512 hash algorithm (optional).
*/
public static final JWSAlgorithm RS512 = new JWSAlgorithm("RS512", Requirement.OPTIONAL);
/**
* ECDSA using P-256 (secp256r1) curve and SHA-256 hash algorithm
* (recommended).
*/
public static final JWSAlgorithm ES256 = new JWSAlgorithm("ES256", Requirement.RECOMMENDED);
/**
* ECDSA using P-256K (secp256k1) curve and SHA-256 hash algorithm
* (optional).
*/
public static final JWSAlgorithm ES256K = new JWSAlgorithm("ES256K", Requirement.OPTIONAL);
/**
* ECDSA using P-384 curve and SHA-384 hash algorithm (optional).
*/
public static final JWSAlgorithm ES384 = new JWSAlgorithm("ES384", Requirement.OPTIONAL);
/**
* ECDSA using P-521 curve and SHA-512 hash algorithm (optional).
*/
public static final JWSAlgorithm ES512 = new JWSAlgorithm("ES512", Requirement.OPTIONAL);
/**
* RSASSA-PSS using SHA-256 hash algorithm and MGF1 mask generation
* function with SHA-256 (optional).
*/
public static final JWSAlgorithm PS256 = new JWSAlgorithm("PS256", Requirement.OPTIONAL);
/**
* RSASSA-PSS using SHA-384 hash algorithm and MGF1 mask generation
* function with SHA-384 (optional).
*/
public static final JWSAlgorithm PS384 = new JWSAlgorithm("PS384", Requirement.OPTIONAL);
/**
* RSASSA-PSS using SHA-512 hash algorithm and MGF1 mask generation
* function with SHA-512 (optional).
*/
public static final JWSAlgorithm PS512 = new JWSAlgorithm("PS512", Requirement.OPTIONAL);
/**
* EdDSA signature algorithms (optional).
*/
public static final JWSAlgorithm EdDSA = new JWSAlgorithm("EdDSA", Requirement.OPTIONAL);
/**
* JWS algorithm family.
*/
public static final class Family extends AlgorithmFamily<JWSAlgorithm> {
private static final long serialVersionUID = 1L;
/**
* HMAC using a SHA-2 hash.
*/
public static final Family HMAC_SHA = new Family(HS256, HS384, HS512);
/**
* RSA signature (RSASSA-PKCS-v1_5 or RSASSA-PSS) using a SHA-2
* hash.
*/
public static final Family RSA = new Family(RS256, RS384, RS512, PS256, PS384, PS512);
/**
* Elliptic Curve signature (ECDSA) using a SHA-2 hash.
*/
public static final Family EC = new Family(ES256, ES256K, ES384, ES512);
/**
* Edwards Curve signature (EdDSA).
*/
public static final Family ED = new Family(EdDSA);
/**
* Super family of all digital signature based JWS algorithms.
*/
public static final Family SIGNATURE = new Family(ArrayUtils
.concat(
RSA.toArray(new JWSAlgorithm[]{}),
EC.toArray(new JWSAlgorithm[]{}),
ED.toArray(new JWSAlgorithm[]{})
)
);
/***
* Creates a new JWS algorithm family.
*
* @param algs The JWS algorithms of the family. Must not be
* {@code null}.
*/
public Family(final JWSAlgorithm ... algs) {
super(algs);
}
}
/**
* Creates a new JSON Web Signature (JWS) algorithm name.
*
* @param name The algorithm name. Must not be {@code null}.
* @param req The implementation requirement, {@code null} if not
* known.
*/
public JWSAlgorithm(final String name, final Requirement req) {
super(name, req);
}
/**
* Creates a new JSON Web Signature (JWS) algorithm name.
*
* @param name The algorithm name. Must not be {@code null}.
*/
public JWSAlgorithm(final String name) {
super(name, null);
}
/**
* Parses a JWS algorithm from the specified string.
*
* @param s The string to parse. Must not be {@code null}.
*
* @return The JWS algorithm (matching standard algorithm constant, else
* a newly created algorithm).
*/
public static JWSAlgorithm parse(final String s) {
if (s.equals(HS256.getName())) {
return HS256;
} else if (s.equals(HS384.getName())) {
return HS384;
} else if (s.equals(HS512.getName())) {
return HS512;
} else if (s.equals(RS256.getName())) {
return RS256;
} else if (s.equals(RS384.getName())) {
return RS384;
} else if (s.equals(RS512.getName())) {
return RS512;
} else if (s.equals(ES256.getName())) {
return ES256;
} else if (s.equals(ES256K.getName())) {
return ES256K;
} else if (s.equals(ES384.getName())) {
return ES384;
} else if (s.equals(ES512.getName())) {
return ES512;
} else if (s.equals(PS256.getName())) {
return PS256;
} else if (s.equals(PS384.getName())) {
return PS384;
} else if (s.equals(PS512.getName())) {
return PS512;
} else if (s.equals(EdDSA.getName())) {
return EdDSA;
} else {
return new JWSAlgorithm(s);
}
}
}
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册