From 36edd83c392629b24349919d0acd372882d4a824 Mon Sep 17 00:00:00 2001 From: shimingxy Date: Tue, 3 Mar 2020 12:46:55 +0800 Subject: [PATCH] v1.2.1 GA MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- build.gradle | 5 + gradle.properties | 2 +- maxkey-authentications/build.gradle | 1 - .../oauth/builder/api/MaxkeyApi10a.java | 2 +- .../client/oauth/builder/api/MaxkeyApi20.java | 2 +- maxkey-core/build.gradle | 1 - .../maxkey/web/InitApplicationContext.java | 2 +- maxkey-jose-jwt/.classpath | 12 - maxkey-jose-jwt/.gitignore | 1 - maxkey-jose-jwt/.project | 40 - .../org.eclipse.buildship.core.prefs | 11 - .../org.eclipse.core.resources.prefs | 2 - .../.settings/org.eclipse.jdt.core.prefs | 4 - .../org.eclipse.wst.common.component | 5 - ....eclipse.wst.common.project.facet.core.xml | 7 - maxkey-jose-jwt/build.gradle | 7 - .../src/main/java/META-INF/MANIFEST.MF | 5 - maxkey-jose-jwt/src/main/java/META-INF/README | 10 - .../java/com/nimbusds/jose/Algorithm.java | 173 -- .../com/nimbusds/jose/AlgorithmFamily.java | 80 - .../com/nimbusds/jose/CommonSEHeader.java | 327 --- .../nimbusds/jose/CompressionAlgorithm.java | 143 -- .../jose/CriticalHeaderParamsAware.java | 60 - .../com/nimbusds/jose/EncryptionMethod.java | 259 -- .../main/java/com/nimbusds/jose/Header.java | 493 ---- .../java/com/nimbusds/jose/JOSEException.java | 54 - .../java/com/nimbusds/jose/JOSEObject.java | 304 --- .../com/nimbusds/jose/JOSEObjectType.java | 157 -- .../java/com/nimbusds/jose/JOSEProvider.java | 27 - .../java/com/nimbusds/jose/JWEAlgorithm.java | 334 --- .../com/nimbusds/jose/JWECryptoParts.java | 185 -- .../java/com/nimbusds/jose/JWEDecrypter.java | 62 - .../java/com/nimbusds/jose/JWEEncrypter.java | 46 - .../java/com/nimbusds/jose/JWEHeader.java | 1290 ---------- .../java/com/nimbusds/jose/JWEObject.java | 511 ---- .../java/com/nimbusds/jose/JWEProvider.java | 54 - .../java/com/nimbusds/jose/JWSAlgorithm.java | 275 -- .../java/com/nimbusds/jose/JWSHeader.java | 727 ------ .../java/com/nimbusds/jose/JWSObject.java | 423 --- .../java/com/nimbusds/jose/JWSProvider.java | 45 - .../java/com/nimbusds/jose/JWSSigner.java | 51 - .../java/com/nimbusds/jose/JWSVerifier.java | 55 - .../java/com/nimbusds/jose/KeyException.java | 39 - .../com/nimbusds/jose/KeyLengthException.java | 106 - .../com/nimbusds/jose/KeySourceException.java | 50 - .../com/nimbusds/jose/KeyTypeException.java | 43 - .../main/java/com/nimbusds/jose/Payload.java | 497 ---- .../com/nimbusds/jose/PayloadTransformer.java | 35 - .../java/com/nimbusds/jose/PlainHeader.java | 477 ---- .../java/com/nimbusds/jose/PlainObject.java | 176 -- .../jose/RemoteKeySourceException.java | 39 - .../java/com/nimbusds/jose/Requirement.java | 47 - .../nimbusds/jose/crypto/AESDecrypter.java | 230 -- .../nimbusds/jose/crypto/AESEncrypter.java | 224 -- .../nimbusds/jose/crypto/DirectDecrypter.java | 273 -- .../nimbusds/jose/crypto/DirectEncrypter.java | 146 -- .../nimbusds/jose/crypto/ECDHDecrypter.java | 271 -- .../nimbusds/jose/crypto/ECDHEncrypter.java | 259 -- .../com/nimbusds/jose/crypto/ECDSASigner.java | 188 -- .../nimbusds/jose/crypto/ECDSAVerifier.java | 201 -- .../nimbusds/jose/crypto/Ed25519Signer.java | 136 - .../nimbusds/jose/crypto/Ed25519Verifier.java | 167 -- .../com/nimbusds/jose/crypto/MACSigner.java | 196 -- .../com/nimbusds/jose/crypto/MACVerifier.java | 183 -- .../jose/crypto/PasswordBasedDecrypter.java | 157 -- .../jose/crypto/PasswordBasedEncrypter.java | 188 -- .../nimbusds/jose/crypto/RSADecrypter.java | 301 --- .../nimbusds/jose/crypto/RSAEncrypter.java | 200 -- .../nimbusds/jose/crypto/RSASSASigner.java | 201 -- .../nimbusds/jose/crypto/RSASSAVerifier.java | 176 -- .../nimbusds/jose/crypto/X25519Decrypter.java | 196 -- .../nimbusds/jose/crypto/X25519Encrypter.java | 162 -- .../bc/BouncyCastleProviderSingleton.java | 63 - .../nimbusds/jose/crypto/bc/package-info.java | 21 - .../factories/DefaultJWEDecrypterFactory.java | 190 -- .../factories/DefaultJWSVerifierFactory.java | 133 - .../jose/crypto/factories/package-info.java | 22 - .../com/nimbusds/jose/crypto/impl/AAD.java | 88 - .../com/nimbusds/jose/crypto/impl/AESCBC.java | 432 ---- .../jose/crypto/impl/AESCryptoProvider.java | 166 -- .../com/nimbusds/jose/crypto/impl/AESGCM.java | 310 --- .../nimbusds/jose/crypto/impl/AESGCMKW.java | 112 - .../com/nimbusds/jose/crypto/impl/AESKW.java | 128 - .../impl/AlgorithmParametersHelper.java | 59 - .../crypto/impl/AlgorithmSupportMessage.java | 145 -- .../crypto/impl/AuthenticatedCipherText.java | 88 - .../jose/crypto/impl/BaseJWEProvider.java | 104 - .../jose/crypto/impl/BaseJWSProvider.java | 79 - .../jose/crypto/impl/CipherHelper.java | 55 - .../jose/crypto/impl/CompositeKey.java | 156 -- .../nimbusds/jose/crypto/impl/ConcatKDF.java | 312 --- .../crypto/impl/ContentCryptoProvider.java | 310 --- .../impl/CriticalHeaderParamsDeferral.java | 130 - .../jose/crypto/impl/DeflateHelper.java | 111 - .../crypto/impl/DirectCryptoProvider.java | 138 - .../com/nimbusds/jose/crypto/impl/ECDH.java | 288 --- .../jose/crypto/impl/ECDHCryptoProvider.java | 254 -- .../com/nimbusds/jose/crypto/impl/ECDSA.java | 318 --- .../jose/crypto/impl/ECDSAProvider.java | 99 - .../jose/crypto/impl/EdDSAProvider.java | 64 - .../com/nimbusds/jose/crypto/impl/HMAC.java | 122 - .../jose/crypto/impl/LegacyAESGCM.java | 219 -- .../jose/crypto/impl/LegacyConcatKDF.java | 274 -- .../jose/crypto/impl/MACProvider.java | 156 -- .../com/nimbusds/jose/crypto/impl/PBKDF2.java | 223 -- .../nimbusds/jose/crypto/impl/PRFParams.java | 144 -- .../impl/PasswordBasedCryptoProvider.java | 128 - .../com/nimbusds/jose/crypto/impl/RSA1_5.java | 123 - .../jose/crypto/impl/RSACryptoProvider.java | 89 - .../jose/crypto/impl/RSAKeyUtils.java | 82 - .../com/nimbusds/jose/crypto/impl/RSASSA.java | 114 - .../jose/crypto/impl/RSASSAProvider.java | 75 - .../nimbusds/jose/crypto/impl/RSA_OAEP.java | 121 - .../jose/crypto/impl/RSA_OAEP_256.java | 132 - .../jose/crypto/impl/package-info.java | 21 - .../nimbusds/jose/crypto/package-info.java | 89 - .../jose/crypto/utils/ConstantTimeUtils.java | 61 - .../nimbusds/jose/crypto/utils/ECChecks.java | 114 - .../jose/crypto/utils/package-info.java | 21 - .../java/com/nimbusds/jose/jca/JCAAware.java | 39 - .../com/nimbusds/jose/jca/JCAContext.java | 123 - .../com/nimbusds/jose/jca/JCASupport.java | 375 --- .../com/nimbusds/jose/jca/JWEJCAContext.java | 182 -- .../com/nimbusds/jose/jca/package-info.java | 28 - .../com/nimbusds/jose/jwk/AsymmetricJWK.java | 83 - .../java/com/nimbusds/jose/jwk/Curve.java | 371 --- .../com/nimbusds/jose/jwk/CurveBasedJWK.java | 36 - .../java/com/nimbusds/jose/jwk/ECKey.java | 1582 ------------ .../nimbusds/jose/jwk/ECParameterTable.java | 242 -- .../main/java/com/nimbusds/jose/jwk/JWK.java | 845 ------ .../com/nimbusds/jose/jwk/JWKMatcher.java | 1377 ---------- .../com/nimbusds/jose/jwk/JWKMetadata.java | 229 -- .../com/nimbusds/jose/jwk/JWKSelector.java | 94 - .../java/com/nimbusds/jose/jwk/JWKSet.java | 534 ---- .../com/nimbusds/jose/jwk/KeyConverter.java | 73 - .../com/nimbusds/jose/jwk/KeyOperation.java | 187 -- .../java/com/nimbusds/jose/jwk/KeyType.java | 254 -- .../java/com/nimbusds/jose/jwk/KeyUse.java | 201 -- .../jose/jwk/KeyUseAndOpsConsistency.java | 76 - .../com/nimbusds/jose/jwk/OctetKeyPair.java | 867 ------- .../nimbusds/jose/jwk/OctetSequenceKey.java | 668 ----- .../jose/jwk/PEMEncodedKeyParser.java | 154 -- .../com/nimbusds/jose/jwk/PasswordLookup.java | 35 - .../java/com/nimbusds/jose/jwk/RSAKey.java | 2276 ----------------- .../java/com/nimbusds/jose/jwk/SecretJWK.java | 39 - .../nimbusds/jose/jwk/ThumbprintUtils.java | 109 - .../nimbusds/jose/jwk/gen/ECKeyGenerator.java | 111 - .../nimbusds/jose/jwk/gen/JWKGenerator.java | 184 -- .../jose/jwk/gen/OctetKeyPairGenerator.java | 147 -- .../jwk/gen/OctetSequenceKeyGenerator.java | 115 - .../jose/jwk/gen/RSAKeyGenerator.java | 118 - .../nimbusds/jose/jwk/gen/package-info.java | 20 - .../com/nimbusds/jose/jwk/package-info.java | 30 - .../jose/jwk/source/DefaultJWKSetCache.java | 161 -- .../jose/jwk/source/ImmutableJWKSet.java | 77 - .../jose/jwk/source/ImmutableSecret.java | 83 - .../jwk/source/JWKSecurityContextJWKSet.java | 49 - .../nimbusds/jose/jwk/source/JWKSetCache.java | 47 - .../nimbusds/jose/jwk/source/JWKSource.java | 53 - .../jose/jwk/source/RemoteJWKSet.java | 294 --- .../jose/jwk/source/package-info.java | 23 - .../java/com/nimbusds/jose/package-info.java | 40 - .../proc/AbstractJWKSelectorWithSource.java | 62 - .../nimbusds/jose/proc/BadJOSEException.java | 51 - .../nimbusds/jose/proc/BadJWEException.java | 53 - .../nimbusds/jose/proc/BadJWSException.java | 52 - .../jose/proc/ConfigurableJOSEProcessor.java | 32 - .../jose/proc/DefaultJOSEProcessor.java | 325 --- .../com/nimbusds/jose/proc/JOSEMatcher.java | 526 ---- .../com/nimbusds/jose/proc/JOSEProcessor.java | 133 - .../jose/proc/JOSEProcessorConfiguration.java | 117 - .../jose/proc/JWEDecrypterFactory.java | 53 - .../jose/proc/JWEDecryptionKeySelector.java | 148 -- .../nimbusds/jose/proc/JWEKeySelector.java | 72 - .../jose/proc/JWKSecurityContext.java | 59 - .../nimbusds/jose/proc/JWSKeySelector.java | 72 - .../jose/proc/JWSVerificationKeySelector.java | 125 - .../jose/proc/JWSVerifierFactory.java | 53 - .../nimbusds/jose/proc/SecurityContext.java | 41 - .../jose/proc/SimpleSecurityContext.java | 34 - .../com/nimbusds/jose/proc/package-info.java | 29 - .../AbstractRestrictedResourceRetriever.java | 119 - .../com/nimbusds/jose/util/ArrayUtils.java | 59 - .../java/com/nimbusds/jose/util/Base64.java | 193 -- .../com/nimbusds/jose/util/Base64Codec.java | 393 --- .../com/nimbusds/jose/util/Base64URL.java | 110 - .../nimbusds/jose/util/BigIntegerUtils.java | 83 - .../jose/util/BoundedInputStream.java | 213 -- .../com/nimbusds/jose/util/ByteUtils.java | 166 -- .../com/nimbusds/jose/util/Container.java | 82 - .../com/nimbusds/jose/util/DateUtils.java | 132 - .../jose/util/DefaultResourceRetriever.java | 197 -- .../com/nimbusds/jose/util/DeflateUtils.java | 131 - .../java/com/nimbusds/jose/util/IOUtils.java | 84 - .../jose/util/IntegerOverflowException.java | 36 - .../com/nimbusds/jose/util/IntegerUtils.java | 54 - .../nimbusds/jose/util/JSONObjectUtils.java | 390 --- .../java/com/nimbusds/jose/util/KeyUtils.java | 56 - .../java/com/nimbusds/jose/util/Resource.java | 82 - .../nimbusds/jose/util/ResourceRetriever.java | 44 - .../util/RestrictedResourceRetriever.java | 78 - .../nimbusds/jose/util/StandardCharset.java | 41 - .../jose/util/X509CertChainUtils.java | 116 - .../com/nimbusds/jose/util/X509CertUtils.java | 178 -- .../com/nimbusds/jose/util/package-info.java | 21 - .../java/com/nimbusds/jwt/EncryptedJWT.java | 132 - .../src/main/java/com/nimbusds/jwt/JWT.java | 92 - .../java/com/nimbusds/jwt/JWTClaimsSet.java | 979 ------- .../nimbusds/jwt/JWTClaimsSetTransformer.java | 36 - .../main/java/com/nimbusds/jwt/JWTParser.java | 95 - .../main/java/com/nimbusds/jwt/PlainJWT.java | 129 - .../main/java/com/nimbusds/jwt/SignedJWT.java | 118 - .../java/com/nimbusds/jwt/package-info.java | 36 - .../nimbusds/jwt/proc/BadJWTException.java | 54 - .../com/nimbusds/jwt/proc/ClockSkewAware.java | 47 - .../jwt/proc/ConfigurableJWTProcessor.java | 35 - .../jwt/proc/DefaultJWTClaimsVerifier.java | 121 - .../jwt/proc/DefaultJWTProcessor.java | 416 --- .../jwt/proc/JWTClaimsSetVerifier.java | 56 - .../nimbusds/jwt/proc/JWTClaimsVerifier.java | 42 - .../com/nimbusds/jwt/proc/JWTProcessor.java | 136 - .../jwt/proc/JWTProcessorConfiguration.java | 99 - .../com/nimbusds/jwt/proc/package-info.java | 35 - .../java/com/nimbusds/jwt/util/DateUtils.java | 131 - .../com/nimbusds/jwt/util/package-info.java | 21 - .../java/com/nimbusds/langtag/LangTag.java | 715 ------ .../nimbusds/langtag/LangTagException.java | 36 - .../com/nimbusds/langtag/LangTagUtils.java | 367 --- .../com/nimbusds/langtag/ReadOnlyLangTag.java | 127 - .../com/nimbusds/langtag/package-info.java | 31 - .../java/net/jcip/annotations/GuardedBy.java | 59 - .../java/net/jcip/annotations/Immutable.java | 45 - .../net/jcip/annotations/NotThreadSafe.java | 36 - .../java/net/jcip/annotations/ThreadSafe.java | 36 - .../main/java/net/minidev/asm/ASMUtil.java | 253 -- .../main/java/net/minidev/asm/Accessor.java | 187 -- .../net/minidev/asm/BasicFiledFilter.java | 29 - .../java/net/minidev/asm/BeansAccess.java | 197 -- .../net/minidev/asm/BeansAccessBuilder.java | 463 ---- .../net/minidev/asm/BeansAccessConfig.java | 74 - .../java/net/minidev/asm/ConvertDate.java | 290 --- .../net/minidev/asm/DefaultConverter.java | 183 -- .../net/minidev/asm/DynamicClassLoader.java | 88 - .../java/net/minidev/asm/FieldFilter.java | 27 - .../net/minidev/asm/ex/ConvertException.java | 14 - .../minidev/asm/ex/NoSuchFieldException.java | 19 - .../main/java/net/minidev/json/JSONArray.java | 133 - .../main/java/net/minidev/json/JSONAware.java | 29 - .../java/net/minidev/json/JSONAwareEx.java | 31 - .../main/java/net/minidev/json/JSONNavi.java | 727 ------ .../java/net/minidev/json/JSONObject.java | 274 -- .../net/minidev/json/JSONStreamAware.java | 31 - .../net/minidev/json/JSONStreamAwareEx.java | 31 - .../main/java/net/minidev/json/JSONStyle.java | 212 -- .../main/java/net/minidev/json/JSONUtil.java | 261 -- .../main/java/net/minidev/json/JSONValue.java | 654 ----- .../java/net/minidev/json/JStylerObj.java | 329 --- .../net/minidev/json/annotate/JsonIgnore.java | 31 - .../json/annotate/JsonSmartAnnotation.java | 19 - .../net/minidev/json/parser/JSONParser.java | 281 -- .../minidev/json/parser/JSONParserBase.java | 763 ------ .../json/parser/JSONParserByteArray.java | 111 - .../json/parser/JSONParserInputStream.java | 64 - .../minidev/json/parser/JSONParserMemory.java | 140 - .../minidev/json/parser/JSONParserReader.java | 91 - .../minidev/json/parser/JSONParserStream.java | 142 - .../minidev/json/parser/JSONParserString.java | 109 - .../minidev/json/parser/ParseException.java | 125 - .../net/minidev/json/reader/ArrayWriter.java | 21 - .../net/minidev/json/reader/BeansWriter.java | 63 - .../minidev/json/reader/BeansWriterASM.java | 36 - .../json/reader/BeansWriterASMRemap.java | 53 - .../net/minidev/json/reader/JsonWriter.java | 395 --- .../net/minidev/json/reader/JsonWriterI.java | 9 - .../net/minidev/json/writer/ArraysMapper.java | 309 --- .../net/minidev/json/writer/BeansMapper.java | 153 -- .../minidev/json/writer/CollectionMapper.java | 252 -- .../minidev/json/writer/CompessorMapper.java | 218 -- .../minidev/json/writer/DefaultMapper.java | 63 - .../json/writer/DefaultMapperCollection.java | 74 - .../json/writer/DefaultMapperOrdered.java | 58 - .../net/minidev/json/writer/FakeMapper.java | 54 - .../net/minidev/json/writer/JsonReader.java | 155 -- .../net/minidev/json/writer/JsonReaderI.java | 110 - .../minidev/json/writer/MapperRemapped.java | 71 - .../minidev/json/writer/UpdaterMapper.java | 94 - .../maxkey-protocol-authorize/build.gradle | 1 - .../maxkey-protocol-cas/build.gradle | 1 - .../maxkey-protocol-desktop/build.gradle | 1 - .../maxkey-protocol-extendapi/build.gradle | 1 - .../maxkey-protocol-formbased/build.gradle | 1 - .../maxkey-protocol-oauth-2.0/build.gradle | 1 - .../userinfo/endpoint/UserInfoEndpoint.java | 53 +- .../maxkey-protocol-tokenbased/build.gradle | 1 - maxkey-web-manage/build.gradle | 1 - .../src/main/resources/application.properties | 2 +- .../resources/messages/message.properties | 2 +- .../resources/messages/message_en.properties | 2 +- maxkey-web-maxkey/build.gradle | 1 - .../main/java/org/maxkey/MaxKeyConfig.java | 51 +- .../src/main/resources/application.properties | 2 +- .../resources/messages/message.properties | 2 +- .../resources/messages/message_en.properties | 2 +- settings.gradle | 2 +- 304 files changed, 68 insertions(+), 49148 deletions(-) delete mode 100644 maxkey-jose-jwt/.classpath delete mode 100644 maxkey-jose-jwt/.gitignore delete mode 100644 maxkey-jose-jwt/.project delete mode 100644 maxkey-jose-jwt/.settings/org.eclipse.buildship.core.prefs delete mode 100644 maxkey-jose-jwt/.settings/org.eclipse.core.resources.prefs delete mode 100644 maxkey-jose-jwt/.settings/org.eclipse.jdt.core.prefs delete mode 100644 maxkey-jose-jwt/.settings/org.eclipse.wst.common.component delete mode 100644 maxkey-jose-jwt/.settings/org.eclipse.wst.common.project.facet.core.xml delete mode 100644 maxkey-jose-jwt/build.gradle delete mode 100644 maxkey-jose-jwt/src/main/java/META-INF/MANIFEST.MF delete mode 100644 maxkey-jose-jwt/src/main/java/META-INF/README delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/Algorithm.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/AlgorithmFamily.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/CommonSEHeader.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/CompressionAlgorithm.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/CriticalHeaderParamsAware.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/EncryptionMethod.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/Header.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JOSEException.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JOSEObject.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JOSEObjectType.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JOSEProvider.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JWEAlgorithm.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JWECryptoParts.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JWEDecrypter.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JWEEncrypter.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JWEHeader.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JWEObject.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JWEProvider.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JWSAlgorithm.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JWSHeader.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JWSObject.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JWSProvider.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JWSSigner.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JWSVerifier.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/KeyException.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/KeyLengthException.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/KeySourceException.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/KeyTypeException.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/Payload.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/PayloadTransformer.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/PlainHeader.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/PlainObject.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/RemoteKeySourceException.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/Requirement.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/AESDecrypter.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/AESEncrypter.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/DirectDecrypter.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/DirectEncrypter.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/ECDHDecrypter.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/ECDHEncrypter.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/ECDSASigner.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/ECDSAVerifier.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/Ed25519Signer.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/Ed25519Verifier.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/MACSigner.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/MACVerifier.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/PasswordBasedDecrypter.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/PasswordBasedEncrypter.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/RSADecrypter.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/RSAEncrypter.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/RSASSASigner.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/RSASSAVerifier.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/X25519Decrypter.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/X25519Encrypter.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/bc/BouncyCastleProviderSingleton.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/bc/package-info.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/factories/DefaultJWEDecrypterFactory.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/factories/DefaultJWSVerifierFactory.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/factories/package-info.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/AAD.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/AESCBC.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/AESCryptoProvider.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/AESGCM.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/AESGCMKW.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/AESKW.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/AlgorithmParametersHelper.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/AlgorithmSupportMessage.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/AuthenticatedCipherText.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/BaseJWEProvider.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/BaseJWSProvider.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/CipherHelper.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/CompositeKey.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/ConcatKDF.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/ContentCryptoProvider.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/CriticalHeaderParamsDeferral.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/DeflateHelper.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/DirectCryptoProvider.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/ECDH.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/ECDHCryptoProvider.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/ECDSA.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/ECDSAProvider.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/EdDSAProvider.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/HMAC.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/LegacyAESGCM.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/LegacyConcatKDF.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/MACProvider.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/PBKDF2.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/PRFParams.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/PasswordBasedCryptoProvider.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/RSA1_5.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/RSACryptoProvider.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/RSAKeyUtils.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/RSASSA.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/RSASSAProvider.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/RSA_OAEP.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/RSA_OAEP_256.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/package-info.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/package-info.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/utils/ConstantTimeUtils.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/utils/ECChecks.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/utils/package-info.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jca/JCAAware.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jca/JCAContext.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jca/JCASupport.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jca/JWEJCAContext.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jca/package-info.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/AsymmetricJWK.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/Curve.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/CurveBasedJWK.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/ECKey.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/ECParameterTable.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/JWK.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/JWKMatcher.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/JWKMetadata.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/JWKSelector.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/JWKSet.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/KeyConverter.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/KeyOperation.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/KeyType.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/KeyUse.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/KeyUseAndOpsConsistency.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/OctetKeyPair.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/OctetSequenceKey.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/PEMEncodedKeyParser.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/PasswordLookup.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/RSAKey.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/SecretJWK.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/ThumbprintUtils.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/gen/ECKeyGenerator.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/gen/JWKGenerator.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/gen/OctetKeyPairGenerator.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/gen/OctetSequenceKeyGenerator.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/gen/RSAKeyGenerator.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/gen/package-info.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/package-info.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/source/DefaultJWKSetCache.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/source/ImmutableJWKSet.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/source/ImmutableSecret.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/source/JWKSecurityContextJWKSet.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/source/JWKSetCache.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/source/JWKSource.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/source/RemoteJWKSet.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/source/package-info.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/package-info.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/AbstractJWKSelectorWithSource.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/BadJOSEException.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/BadJWEException.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/BadJWSException.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/ConfigurableJOSEProcessor.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/DefaultJOSEProcessor.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/JOSEMatcher.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/JOSEProcessor.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/JOSEProcessorConfiguration.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/JWEDecrypterFactory.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/JWEDecryptionKeySelector.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/JWEKeySelector.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/JWKSecurityContext.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/JWSKeySelector.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/JWSVerificationKeySelector.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/JWSVerifierFactory.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/SecurityContext.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/SimpleSecurityContext.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/package-info.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/AbstractRestrictedResourceRetriever.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/ArrayUtils.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/Base64.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/Base64Codec.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/Base64URL.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/BigIntegerUtils.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/BoundedInputStream.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/ByteUtils.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/Container.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/DateUtils.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/DefaultResourceRetriever.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/DeflateUtils.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/IOUtils.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/IntegerOverflowException.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/IntegerUtils.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/JSONObjectUtils.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/KeyUtils.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/Resource.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/ResourceRetriever.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/RestrictedResourceRetriever.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/StandardCharset.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/X509CertChainUtils.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/X509CertUtils.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/package-info.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/EncryptedJWT.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/JWT.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/JWTClaimsSet.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/JWTClaimsSetTransformer.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/JWTParser.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/PlainJWT.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/SignedJWT.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/package-info.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/proc/BadJWTException.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/proc/ClockSkewAware.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/proc/ConfigurableJWTProcessor.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/proc/DefaultJWTClaimsVerifier.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/proc/DefaultJWTProcessor.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/proc/JWTClaimsSetVerifier.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/proc/JWTClaimsVerifier.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/proc/JWTProcessor.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/proc/JWTProcessorConfiguration.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/proc/package-info.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/util/DateUtils.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/util/package-info.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/langtag/LangTag.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/langtag/LangTagException.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/langtag/LangTagUtils.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/langtag/ReadOnlyLangTag.java delete mode 100644 maxkey-jose-jwt/src/main/java/com/nimbusds/langtag/package-info.java delete mode 100644 maxkey-jose-jwt/src/main/java/net/jcip/annotations/GuardedBy.java delete mode 100644 maxkey-jose-jwt/src/main/java/net/jcip/annotations/Immutable.java delete mode 100644 maxkey-jose-jwt/src/main/java/net/jcip/annotations/NotThreadSafe.java delete mode 100644 maxkey-jose-jwt/src/main/java/net/jcip/annotations/ThreadSafe.java delete mode 100644 maxkey-jose-jwt/src/main/java/net/minidev/asm/ASMUtil.java delete mode 100644 maxkey-jose-jwt/src/main/java/net/minidev/asm/Accessor.java delete mode 100644 maxkey-jose-jwt/src/main/java/net/minidev/asm/BasicFiledFilter.java delete mode 100644 maxkey-jose-jwt/src/main/java/net/minidev/asm/BeansAccess.java delete mode 100644 maxkey-jose-jwt/src/main/java/net/minidev/asm/BeansAccessBuilder.java delete mode 100644 maxkey-jose-jwt/src/main/java/net/minidev/asm/BeansAccessConfig.java delete mode 100644 maxkey-jose-jwt/src/main/java/net/minidev/asm/ConvertDate.java delete mode 100644 maxkey-jose-jwt/src/main/java/net/minidev/asm/DefaultConverter.java delete mode 100644 maxkey-jose-jwt/src/main/java/net/minidev/asm/DynamicClassLoader.java delete mode 100644 maxkey-jose-jwt/src/main/java/net/minidev/asm/FieldFilter.java delete mode 100644 maxkey-jose-jwt/src/main/java/net/minidev/asm/ex/ConvertException.java delete mode 100644 maxkey-jose-jwt/src/main/java/net/minidev/asm/ex/NoSuchFieldException.java delete mode 100644 maxkey-jose-jwt/src/main/java/net/minidev/json/JSONArray.java delete mode 100644 maxkey-jose-jwt/src/main/java/net/minidev/json/JSONAware.java delete mode 100644 maxkey-jose-jwt/src/main/java/net/minidev/json/JSONAwareEx.java delete mode 100644 maxkey-jose-jwt/src/main/java/net/minidev/json/JSONNavi.java delete mode 100644 maxkey-jose-jwt/src/main/java/net/minidev/json/JSONObject.java delete mode 100644 maxkey-jose-jwt/src/main/java/net/minidev/json/JSONStreamAware.java delete mode 100644 maxkey-jose-jwt/src/main/java/net/minidev/json/JSONStreamAwareEx.java delete mode 100644 maxkey-jose-jwt/src/main/java/net/minidev/json/JSONStyle.java delete mode 100644 maxkey-jose-jwt/src/main/java/net/minidev/json/JSONUtil.java delete mode 100644 maxkey-jose-jwt/src/main/java/net/minidev/json/JSONValue.java delete mode 100644 maxkey-jose-jwt/src/main/java/net/minidev/json/JStylerObj.java delete mode 100644 maxkey-jose-jwt/src/main/java/net/minidev/json/annotate/JsonIgnore.java delete mode 100644 maxkey-jose-jwt/src/main/java/net/minidev/json/annotate/JsonSmartAnnotation.java delete mode 100644 maxkey-jose-jwt/src/main/java/net/minidev/json/parser/JSONParser.java delete mode 100644 maxkey-jose-jwt/src/main/java/net/minidev/json/parser/JSONParserBase.java delete mode 100644 maxkey-jose-jwt/src/main/java/net/minidev/json/parser/JSONParserByteArray.java delete mode 100644 maxkey-jose-jwt/src/main/java/net/minidev/json/parser/JSONParserInputStream.java delete mode 100644 maxkey-jose-jwt/src/main/java/net/minidev/json/parser/JSONParserMemory.java delete mode 100644 maxkey-jose-jwt/src/main/java/net/minidev/json/parser/JSONParserReader.java delete mode 100644 maxkey-jose-jwt/src/main/java/net/minidev/json/parser/JSONParserStream.java delete mode 100644 maxkey-jose-jwt/src/main/java/net/minidev/json/parser/JSONParserString.java delete mode 100644 maxkey-jose-jwt/src/main/java/net/minidev/json/parser/ParseException.java delete mode 100644 maxkey-jose-jwt/src/main/java/net/minidev/json/reader/ArrayWriter.java delete mode 100644 maxkey-jose-jwt/src/main/java/net/minidev/json/reader/BeansWriter.java delete mode 100644 maxkey-jose-jwt/src/main/java/net/minidev/json/reader/BeansWriterASM.java delete mode 100644 maxkey-jose-jwt/src/main/java/net/minidev/json/reader/BeansWriterASMRemap.java delete mode 100644 maxkey-jose-jwt/src/main/java/net/minidev/json/reader/JsonWriter.java delete mode 100644 maxkey-jose-jwt/src/main/java/net/minidev/json/reader/JsonWriterI.java delete mode 100644 maxkey-jose-jwt/src/main/java/net/minidev/json/writer/ArraysMapper.java delete mode 100644 maxkey-jose-jwt/src/main/java/net/minidev/json/writer/BeansMapper.java delete mode 100644 maxkey-jose-jwt/src/main/java/net/minidev/json/writer/CollectionMapper.java delete mode 100644 maxkey-jose-jwt/src/main/java/net/minidev/json/writer/CompessorMapper.java delete mode 100644 maxkey-jose-jwt/src/main/java/net/minidev/json/writer/DefaultMapper.java delete mode 100644 maxkey-jose-jwt/src/main/java/net/minidev/json/writer/DefaultMapperCollection.java delete mode 100644 maxkey-jose-jwt/src/main/java/net/minidev/json/writer/DefaultMapperOrdered.java delete mode 100644 maxkey-jose-jwt/src/main/java/net/minidev/json/writer/FakeMapper.java delete mode 100644 maxkey-jose-jwt/src/main/java/net/minidev/json/writer/JsonReader.java delete mode 100644 maxkey-jose-jwt/src/main/java/net/minidev/json/writer/JsonReaderI.java delete mode 100644 maxkey-jose-jwt/src/main/java/net/minidev/json/writer/MapperRemapped.java delete mode 100644 maxkey-jose-jwt/src/main/java/net/minidev/json/writer/UpdaterMapper.java diff --git a/build.gradle b/build.gradle index 81c2df39c..bef44d836 100644 --- a/build.gradle +++ b/build.gradle @@ -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' diff --git a/gradle.properties b/gradle.properties index 232114402..5e4768a04 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,5 +1,5 @@ group =org.maxkey -version =1.2.0.RELEASE +version =1.2.1.RELEASE vendor =https://github.com/shimingxy/MaxKey author =shimingxy diff --git a/maxkey-authentications/build.gradle b/maxkey-authentications/build.gradle index df63b067e..bc1f804f8 100644 --- a/maxkey-authentications/build.gradle +++ b/maxkey-authentications/build.gradle @@ -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") diff --git a/maxkey-client-sdk/src/main/java/org/maxkey/client/oauth/builder/api/MaxkeyApi10a.java b/maxkey-client-sdk/src/main/java/org/maxkey/client/oauth/builder/api/MaxkeyApi10a.java index 2bc4b82e1..d3e58c10b 100644 --- a/maxkey-client-sdk/src/main/java/org/maxkey/client/oauth/builder/api/MaxkeyApi10a.java +++ b/maxkey-client-sdk/src/main/java/org/maxkey/client/oauth/builder/api/MaxkeyApi10a.java @@ -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() { diff --git a/maxkey-client-sdk/src/main/java/org/maxkey/client/oauth/builder/api/MaxkeyApi20.java b/maxkey-client-sdk/src/main/java/org/maxkey/client/oauth/builder/api/MaxkeyApi20.java index 54e218053..a53e5e0d2 100644 --- a/maxkey-client-sdk/src/main/java/org/maxkey/client/oauth/builder/api/MaxkeyApi20.java +++ b/maxkey-client-sdk/src/main/java/org/maxkey/client/oauth/builder/api/MaxkeyApi20.java @@ -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"; diff --git a/maxkey-core/build.gradle b/maxkey-core/build.gradle index c0022ca6d..56eba0616 100644 --- a/maxkey-core/build.gradle +++ b/maxkey-core/build.gradle @@ -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 diff --git a/maxkey-core/src/main/java/org/maxkey/web/InitApplicationContext.java b/maxkey-core/src/main/java/org/maxkey/web/InitApplicationContext.java index d8eebc6d9..73c77c3d8 100644 --- a/maxkey-core/src/main/java/org/maxkey/web/InitApplicationContext.java +++ b/maxkey-core/src/main/java/org/maxkey/web/InitApplicationContext.java @@ -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"); diff --git a/maxkey-jose-jwt/.classpath b/maxkey-jose-jwt/.classpath deleted file mode 100644 index 4857be400..000000000 --- a/maxkey-jose-jwt/.classpath +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - diff --git a/maxkey-jose-jwt/.gitignore b/maxkey-jose-jwt/.gitignore deleted file mode 100644 index 84c048a73..000000000 --- a/maxkey-jose-jwt/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/build/ diff --git a/maxkey-jose-jwt/.project b/maxkey-jose-jwt/.project deleted file mode 100644 index 151088dbe..000000000 --- a/maxkey-jose-jwt/.project +++ /dev/null @@ -1,40 +0,0 @@ - - - maxkey-jose-jwt - maxkey-jose-jwt - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.buildship.core.gradleprojectbuilder - - - - - org.eclipse.wst.common.project.facet.core.builder - - - - - org.eclipse.wst.validation.validationbuilder - - - - - org.springframework.ide.eclipse.boot.validation.springbootbuilder - - - - - - org.eclipse.jdt.core.javanature - org.eclipse.buildship.core.gradleprojectnature - org.eclipse.wst.common.project.facet.core.nature - org.eclipse.wst.common.modulecore.ModuleCoreNature - - diff --git a/maxkey-jose-jwt/.settings/org.eclipse.buildship.core.prefs b/maxkey-jose-jwt/.settings/org.eclipse.buildship.core.prefs deleted file mode 100644 index 18fe303dd..000000000 --- a/maxkey-jose-jwt/.settings/org.eclipse.buildship.core.prefs +++ /dev/null @@ -1,11 +0,0 @@ -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 diff --git a/maxkey-jose-jwt/.settings/org.eclipse.core.resources.prefs b/maxkey-jose-jwt/.settings/org.eclipse.core.resources.prefs deleted file mode 100644 index 896a9a53a..000000000 --- a/maxkey-jose-jwt/.settings/org.eclipse.core.resources.prefs +++ /dev/null @@ -1,2 +0,0 @@ -eclipse.preferences.version=1 -encoding/=UTF-8 \ No newline at end of file diff --git a/maxkey-jose-jwt/.settings/org.eclipse.jdt.core.prefs b/maxkey-jose-jwt/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 35068d95f..000000000 --- a/maxkey-jose-jwt/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,4 +0,0 @@ -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 diff --git a/maxkey-jose-jwt/.settings/org.eclipse.wst.common.component b/maxkey-jose-jwt/.settings/org.eclipse.wst.common.component deleted file mode 100644 index dd5bcb93c..000000000 --- a/maxkey-jose-jwt/.settings/org.eclipse.wst.common.component +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/maxkey-jose-jwt/.settings/org.eclipse.wst.common.project.facet.core.xml b/maxkey-jose-jwt/.settings/org.eclipse.wst.common.project.facet.core.xml deleted file mode 100644 index fd0227a68..000000000 --- a/maxkey-jose-jwt/.settings/org.eclipse.wst.common.project.facet.core.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/maxkey-jose-jwt/build.gradle b/maxkey-jose-jwt/build.gradle deleted file mode 100644 index 68907debb..000000000 --- a/maxkey-jose-jwt/build.gradle +++ /dev/null @@ -1,7 +0,0 @@ -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') -} diff --git a/maxkey-jose-jwt/src/main/java/META-INF/MANIFEST.MF b/maxkey-jose-jwt/src/main/java/META-INF/MANIFEST.MF deleted file mode 100644 index d1156468e..000000000 --- a/maxkey-jose-jwt/src/main/java/META-INF/MANIFEST.MF +++ /dev/null @@ -1,5 +0,0 @@ -Manifest-Version: 1.0 -Archiver-Version: Plexus Archiver -Created-By: Apache Maven -Built-By: vd -Build-Jdk: 1.7.0_72 diff --git a/maxkey-jose-jwt/src/main/java/META-INF/README b/maxkey-jose-jwt/src/main/java/META-INF/README deleted file mode 100644 index e601056bb..000000000 --- a/maxkey-jose-jwt/src/main/java/META-INF/README +++ /dev/null @@ -1,10 +0,0 @@ - -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 diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/Algorithm.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/Algorithm.java deleted file mode 100644 index c322dae36..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/Algorithm.java +++ /dev/null @@ -1,173 +0,0 @@ -/* - * 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. - * - *

Includes constants for the following standard algorithm names: - * - *

- * - * @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) + '"'; - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/AlgorithmFamily.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/AlgorithmFamily.java deleted file mode 100644 index 9ea23b5a7..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/AlgorithmFamily.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * 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 extends LinkedHashSet { - - - 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 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(); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/CommonSEHeader.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/CommonSEHeader.java deleted file mode 100644 index 08c43b1f4..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/CommonSEHeader.java +++ /dev/null @@ -1,327 +0,0 @@ -/* - * 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. - * - *

Supports all registered header parameters shared by the JWS and JWE - * specifications: - * - *

    - *
  • alg - *
  • jku - *
  • jwk - *
  • x5u - *
  • x5t - *
  • x5t#S256 - *
  • x5c - *
  • kid - *
  • typ - *
  • cty - *
  • crit - *
- * - * @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 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 crit, - final URI jku, - final JWK jwk, - final URI x5u, - final Base64URL x5t, - final Base64URL x5t256, - final List x5c, - final String kid, - final Map 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 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 getIncludedParams() { - - Set 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; - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/CompressionAlgorithm.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/CompressionAlgorithm.java deleted file mode 100644 index 2260be1e5..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/CompressionAlgorithm.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * 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. - * - *

Includes a constant for the standard DEFLATE compression algorithm: - * - *

    - *
  • {@link #DEF} - *
- * - *

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) + '"'; - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/CriticalHeaderParamsAware.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/CriticalHeaderParamsAware.java deleted file mode 100644 index b3b2ee697..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/CriticalHeaderParamsAware.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * 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. - * - *

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 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 getDeferredCriticalHeaderParams(); -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/EncryptionMethod.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/EncryptionMethod.java deleted file mode 100644 index 59d0c364e..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/EncryptionMethod.java +++ /dev/null @@ -1,259 +0,0 @@ -/* - * 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. - * - *

Includes constants for the following standard encryption method names: - * - *

    - *
  • {@link #A128CBC_HS256 A128CBC-HS256} - *
  • {@link #A192CBC_HS384 A192CBC-HS384} - *
  • {@link #A256CBC_HS512 A256CBC-HS512} - *
  • {@link #A128GCM} - *
  • {@link #A192GCM} - *
  • {@link #A256GCM} - *
  • {@link #A128CBC_HS256_DEPRECATED A128CBC+HS256 (deprecated)} - *
  • {@link #A256CBC_HS512_DEPRECATED A256CBC+HS512 (deprecated)} - *
- * - *

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 { - - - 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); - } - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/Header.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/Header.java deleted file mode 100644 index 812ac8d56..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/Header.java +++ /dev/null @@ -1,493 +0,0 @@ -/* - * 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. - * - *

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 crit; - - - /** - * Custom header parameters. - */ - private final Map customParams; - - - /** - * Empty custom parameters constant. - */ - private static final Map EMPTY_CUSTOM_PARAMS = - Collections.unmodifiableMap(new HashMap()); - - - /** - * 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 crit, - final Map 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 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 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 getIncludedParams() { - - Set 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. - * - *

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 diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JOSEException.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JOSEException.java deleted file mode 100644 index 3b491f1e7..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JOSEException.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * 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); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JOSEObject.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JOSEObject.java deleted file mode 100644 index 8619bcebe..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JOSEObject.java +++ /dev/null @@ -1,304 +0,0 @@ -/* - * 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); - } - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JOSEObjectType.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JOSEObjectType.java deleted file mode 100644 index 611c5fea0..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JOSEObjectType.java +++ /dev/null @@ -1,157 +0,0 @@ -/* - * 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. - * - *

Includes constants for the following standard types: - * - *

    - *
  • {@link #JOSE} - *
  • {@link #JOSE_JSON JOSE+JSON} - *
  • {@link #JWT} - *
- * - *

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) + '"'; - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JOSEProvider.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JOSEProvider.java deleted file mode 100644 index 9859059eb..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JOSEProvider.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * 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 { } diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JWEAlgorithm.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JWEAlgorithm.java deleted file mode 100644 index 29017e200..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JWEAlgorithm.java +++ /dev/null @@ -1,334 +0,0 @@ -/* - * 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. - * - *

Includes constants for the following standard JWE algorithm names: - * - *

    - *
  • {@link #RSA_OAEP_256 RSA-OAEP-256} - *
  • {@link #RSA_OAEP RSA-OAEP} (deprecated) - *
  • {@link #RSA1_5} (deprecated) - *
  • {@link #A128KW} - *
  • {@link #A192KW} - *
  • {@link #A256KW} - *
  • {@link #DIR dir} - *
  • {@link #ECDH_ES ECDH-ES} - *
  • {@link #ECDH_ES_A128KW ESDH-ES+A128KW} - *
  • {@link #ECDH_ES_A128KW ESDH-ES+A192KW} - *
  • {@link #ECDH_ES_A256KW ESDH-ES+A256KW} - *
  • {@link #PBES2_HS256_A128KW PBES2-HS256+A128KW} - *
  • {@link #PBES2_HS384_A192KW PBES2-HS256+A192KW} - *
  • {@link #PBES2_HS512_A256KW PBES2-HS256+A256KW} - *
- * - *

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 { - - - 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); - } - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JWECryptoParts.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JWECryptoParts.java deleted file mode 100644 index 672d6c0e9..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JWECryptoParts.java +++ /dev/null @@ -1,185 +0,0 @@ -/* - * 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; - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JWEDecrypter.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JWEDecrypter.java deleted file mode 100644 index f8633d9fe..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JWEDecrypter.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * 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; -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JWEEncrypter.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JWEEncrypter.java deleted file mode 100644 index 9cbdc0182..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JWEEncrypter.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * 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; -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JWEHeader.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JWEHeader.java deleted file mode 100644 index 83533a49c..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JWEHeader.java +++ /dev/null @@ -1,1290 +0,0 @@ -/* - * 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.text.ParseException; -import java.util.*; - -import net.jcip.annotations.Immutable; - -import net.minidev.json.JSONObject; - -import com.nimbusds.jose.jwk.JWK; -import com.nimbusds.jose.util.Base64; -import com.nimbusds.jose.util.Base64URL; -import com.nimbusds.jose.util.JSONObjectUtils; -import com.nimbusds.jose.util.X509CertChainUtils; - - -/** - * JSON Web Encryption (JWE) header. This class is immutable. - * - *

Supports all {@link #getRegisteredParameterNames registered header - * parameters} of the JWE specification: - * - *

    - *
  • alg - *
  • enc - *
  • epk - *
  • zip - *
  • jku - *
  • jwk - *
  • x5u - *
  • x5t - *
  • x5t#S256 - *
  • x5c - *
  • kid - *
  • typ - *
  • cty - *
  • crit - *
  • apu - *
  • apv - *
  • p2s - *
  • p2c - *
  • iv - *
  • authTag - *
- * - *

The header may also include {@link #getCustomParams custom - * parameters}; these will be serialised and parsed along the registered ones. - * - *

Example header: - * - *

- * { 
- *   "alg" : "RSA1_5",
- *   "enc" : "A128CBC-HS256"
- * }
- * 
- * - * @author Vladimir Dzhuvinov - * @version 2017-04-09 - */ -@Immutable -public final class JWEHeader extends CommonSEHeader { - - - private static final long serialVersionUID = 1L; - - - /** - * The registered parameter names. - */ - private static final Set REGISTERED_PARAMETER_NAMES; - - - /** - * Initialises the registered parameter name set. - */ - static { - Set p = new HashSet<>(); - - p.add("alg"); - p.add("enc"); - p.add("epk"); - p.add("zip"); - p.add("jku"); - p.add("jwk"); - p.add("x5u"); - p.add("x5t"); - p.add("x5t#S256"); - p.add("x5c"); - p.add("kid"); - p.add("typ"); - p.add("cty"); - p.add("crit"); - p.add("apu"); - p.add("apv"); - p.add("p2s"); - p.add("p2c"); - p.add("iv"); - p.add("authTag"); - - REGISTERED_PARAMETER_NAMES = Collections.unmodifiableSet(p); - } - - - /** - * Builder for constructing JSON Web Encryption (JWE) headers. - * - *

Example usage: - * - *

-	 * JWEHeader header = new JWEHeader.Builder(JWEAlgorithm.RSA1_5, EncryptionMethod.A128GCM).
-	 *                    contentType("text/plain").
-	 *                    customParam("exp", new Date().getTime()).
-	 *                    build();
-	 * 
- */ - public static class Builder { - - - /** - * The JWE algorithm. - */ - private final JWEAlgorithm alg; - - - /** - * The encryption method. - */ - private final EncryptionMethod enc; - - - /** - * The JOSE object type. - */ - private JOSEObjectType typ; - - - /** - * The content type. - */ - private String cty; - - - /** - * The critical headers. - */ - private Set crit; - - - /** - * JWK Set URL. - */ - private URI jku; - - - /** - * JWK. - */ - private JWK jwk; - - - /** - * X.509 certificate URL. - */ - private URI x5u; - - - /** - * X.509 certificate SHA-1 thumbprint. - */ - @Deprecated - private Base64URL x5t; - - - /** - * X.509 certificate SHA-256 thumbprint. - */ - private Base64URL x5t256; - - - /** - * The X.509 certificate chain corresponding to the key used to - * sign the JWS object. - */ - private List x5c; - - - /** - * Key ID. - */ - private String kid; - - - /** - * The ephemeral public key. - */ - private JWK epk; - - - /** - * The compression algorithm. - */ - private CompressionAlgorithm zip; - - - /** - * The agreement PartyUInfo. - */ - private Base64URL apu; - - - /** - * The agreement PartyVInfo. - */ - private Base64URL apv; - - - /** - * The PBES2 salt. - */ - private Base64URL p2s; - - - /** - * The PBES2 count. - */ - private int p2c; - - - /** - * The initialisation vector. - */ - private Base64URL iv; - - - /** - * The authentication authTag. - */ - private Base64URL tag; - - - /** - * Custom header parameters. - */ - private Map customParams; - - - /** - * The parsed Base64URL. - */ - private Base64URL parsedBase64URL; - - - /** - * Creates a new JWE header builder. - * - * @param alg The JWE algorithm ({@code alg}) parameter. Must - * not be "none" or {@code null}. - * @param enc The encryption method. Must not be {@code null}. - */ - public Builder(final JWEAlgorithm alg, final EncryptionMethod enc) { - - if (alg.getName().equals(Algorithm.NONE.getName())) { - throw new IllegalArgumentException("The JWE algorithm \"alg\" cannot be \"none\""); - } - - this.alg = alg; - - if (enc == null) { - throw new IllegalArgumentException("The encryption method \"enc\" parameter must not be null"); - } - - this.enc = enc; - } - - - /** - * Creates a new JWE header builder with the parameters from - * the specified header. - * - * @param jweHeader The JWE header to use. Must not not be - * {@code null}. - */ - public Builder(final JWEHeader jweHeader) { - - this(jweHeader.getAlgorithm(), jweHeader.getEncryptionMethod()); - - typ = jweHeader.getType(); - cty = jweHeader.getContentType(); - crit = jweHeader.getCriticalParams(); - customParams = jweHeader.getCustomParams(); - - jku = jweHeader.getJWKURL(); - jwk = jweHeader.getJWK(); - x5u = jweHeader.getX509CertURL(); - x5t = jweHeader.getX509CertThumbprint(); - x5t256 = jweHeader.getX509CertSHA256Thumbprint(); - x5c = jweHeader.getX509CertChain(); - kid = jweHeader.getKeyID(); - - epk = jweHeader.getEphemeralPublicKey(); - zip = jweHeader.getCompressionAlgorithm(); - apu = jweHeader.getAgreementPartyUInfo(); - apv = jweHeader.getAgreementPartyVInfo(); - p2s = jweHeader.getPBES2Salt(); - p2c = jweHeader.getPBES2Count(); - iv = jweHeader.getIV(); - tag = jweHeader.getAuthTag(); - - customParams = jweHeader.getCustomParams(); - } - - - /** - * Sets the type ({@code typ}) parameter. - * - * @param typ The type parameter, {@code null} if not - * specified. - * - * @return This builder. - */ - public Builder type(final JOSEObjectType typ) { - - this.typ = typ; - return this; - } - - - /** - * Sets the content type ({@code cty}) parameter. - * - * @param cty The content type parameter, {@code null} if not - * specified. - * - * @return This builder. - */ - public Builder contentType(final String cty) { - - this.cty = cty; - return this; - } - - - /** - * Sets the critical header parameters ({@code crit}) - * parameter. - * - * @param crit The names of the critical header parameters, - * empty set or {@code null} if none. - * - * @return This builder. - */ - public Builder criticalParams(final Set crit) { - - this.crit = crit; - return this; - } - - - /** - * Sets the JSON Web Key (JWK) Set URL ({@code jku}) parameter. - * - * @param jku The JSON Web Key (JWK) Set URL parameter, - * {@code null} if not specified. - * - * @return This builder. - */ - public Builder jwkURL(final URI jku) { - - this.jku = jku; - return this; - } - - - /** - * Sets the JSON Web Key (JWK) ({@code jwk}) parameter. - * - * @param jwk The JSON Web Key (JWK) ({@code jwk}) parameter, - * {@code null} if not specified. - * - * @return This builder. - */ - public Builder jwk(final JWK jwk) { - - this.jwk = jwk; - return this; - } - - - /** - * Sets the X.509 certificate URL ({@code x5u}) parameter. - * - * @param x5u The X.509 certificate URL parameter, {@code null} - * if not specified. - * - * @return This builder. - */ - public Builder x509CertURL(final URI x5u) { - - this.x5u = x5u; - return this; - } - - - /** - * Sets the X.509 certificate SHA-1 thumbprint ({@code x5t}) - * parameter. - * - * @param x5t The X.509 certificate SHA-1 thumbprint parameter, - * {@code null} if not specified. - * - * @return This builder. - */ - @Deprecated - public Builder x509CertThumbprint(final Base64URL x5t) { - - this.x5t = x5t; - return this; - } - - - /** - * Sets the X.509 certificate SHA-256 thumbprint - * ({@code x5t#s256}) parameter. - * - * @param x5t256 The X.509 certificate SHA-256 thumbprint - * parameter, {@code null} if not specified. - * - * @return This builder. - */ - public Builder x509CertSHA256Thumbprint(final Base64URL x5t256) { - - this.x5t256 = x5t256; - return this; - } - - - /** - * Sets the X.509 certificate chain parameter ({@code x5c}) - * corresponding to the key used to sign the JWS object. - * - * @param x5c The X.509 certificate chain parameter, - * {@code null} if not specified. - * - * @return This builder. - */ - public Builder x509CertChain(final List x5c) { - - this.x5c = x5c; - return this; - } - - - /** - * Sets the key ID ({@code kid}) parameter. - * - * @param kid The key ID parameter, {@code null} if not - * specified. - * - * @return This builder. - */ - public Builder keyID(final String kid) { - - this.kid = kid; - return this; - } - - - /** - * Sets the Ephemeral Public Key ({@code epk}) parameter. - * - * @param epk The Ephemeral Public Key parameter, {@code null} - * if not specified. - * - * @return This builder. - */ - public Builder ephemeralPublicKey(final JWK epk) { - - this.epk = epk; - return this; - } - - - /** - * Sets the compression algorithm ({@code zip}) parameter. - * - * @param zip The compression algorithm parameter, {@code null} - * if not specified. - * - * @return This builder. - */ - public Builder compressionAlgorithm(final CompressionAlgorithm zip) { - - this.zip = zip; - return this; - } - - - /** - * Sets the agreement PartyUInfo ({@code apu}) parameter. - * - * @param apu The agreement PartyUInfo parameter, {@code null} - * if not specified. - * - * @return This builder. - */ - public Builder agreementPartyUInfo(final Base64URL apu) { - - this.apu = apu; - return this; - } - - - /** - * Sets the agreement PartyVInfo ({@code apv}) parameter. - * - * @param apv The agreement PartyVInfo parameter, {@code null} - * if not specified. - * - * @return This builder. - */ - public Builder agreementPartyVInfo(final Base64URL apv) { - - this.apv = apv; - return this; - } - - - /** - * Sets the PBES2 salt ({@code p2s}) parameter. - * - * @param p2s The PBES2 salt parameter, {@code null} if not - * specified. - * - * @return This builder. - */ - public Builder pbes2Salt(final Base64URL p2s) { - - this.p2s = p2s; - return this; - } - - - /** - * Sets the PBES2 count ({@code p2c}) parameter. - * - * @param p2c The PBES2 count parameter, zero if not specified. - * Must not be negative. - * - * @return This builder. - */ - public Builder pbes2Count(final int p2c) { - - if (p2c < 0) - throw new IllegalArgumentException("The PBES2 count parameter must not be negative"); - - this.p2c = p2c; - return this; - } - - - /** - * Sets the initialisation vector ({@code iv}) parameter. - * - * @param iv The initialisation vector, {@code null} if not - * specified. - * - * @return This builder. - */ - public Builder iv(final Base64URL iv) { - - this.iv = iv; - return this; - } - - - /** - * Sets the authentication tag ({@code tag}) parameter. - * - * @param tag The authentication tag, {@code null} if not - * specified. - * - * @return This builder. - */ - public Builder authTag(final Base64URL tag) { - - this.tag = tag; - return this; - } - - - /** - * Sets a custom (non-registered) parameter. - * - * @param name The name of the custom parameter. Must not - * match a registered parameter name and must not - * be {@code null}. - * @param value The value of the custom parameter, should map - * to a valid JSON entity, {@code null} if not - * specified. - * - * @return This builder. - * - * @throws IllegalArgumentException If the specified parameter - * name matches a registered - * parameter name. - */ - public Builder customParam(final String name, final Object value) { - - if (getRegisteredParameterNames().contains(name)) { - throw new IllegalArgumentException("The parameter name \"" + name + "\" matches a registered name"); - } - - if (customParams == null) { - customParams = new HashMap<>(); - } - - customParams.put(name, value); - - return this; - } - - - /** - * Sets the custom (non-registered) parameters. The values must - * be serialisable to a JSON entity, otherwise will be ignored. - * - * @param customParameters The custom parameters, empty map or - * {@code null} if none. - * - * @return This builder. - */ - public Builder customParams(final Map customParameters) { - - this.customParams = customParameters; - return this; - } - - - /** - * Sets the parsed Base64URL. - * - * @param base64URL The parsed Base64URL, {@code null} if the - * header is created from scratch. - * - * @return This builder. - */ - public Builder parsedBase64URL(final Base64URL base64URL) { - - this.parsedBase64URL = base64URL; - return this; - } - - - /** - * Builds a new JWE header. - * - * @return The JWE header. - */ - public JWEHeader build() { - - return new JWEHeader( - alg, enc, typ, cty, crit, - jku, jwk, x5u, x5t, x5t256, x5c, kid, - epk, zip, apu, apv, p2s, p2c, - iv, tag, - customParams, parsedBase64URL); - } - } - - - /** - * The encryption method ({@code enc}) parameter. - */ - private final EncryptionMethod enc; - - - /** - * The ephemeral public key ({@code epk}) parameter. - */ - private final JWK epk; - - - /** - * The compression algorithm ({@code zip}) parameter. - */ - private final CompressionAlgorithm zip; - - - /** - * The agreement PartyUInfo ({@code apu}) parameter. - */ - private final Base64URL apu; - - - /** - * The agreement PartyVInfo ({@code apv}) parameter. - */ - private final Base64URL apv; - - - /** - * The PBES2 salt ({@code p2s}) parameter. - */ - private final Base64URL p2s; - - - /** - * The PBES2 count ({@code p2c}) parameter. - */ - private final int p2c; - - - /** - * The initialisation vector ({@code iv}) parameter. - */ - private final Base64URL iv; - - - /** - * The authentication tag ({@code tag}) parameter. - */ - private final Base64URL tag; - - - /** - * Creates a new minimal JSON Web Encryption (JWE) header. - * - *

Note: Use {@link PlainHeader} to create a header with algorithm - * {@link Algorithm#NONE none}. - * - * @param alg The JWE algorithm parameter. Must not be "none" or - * {@code null}. - * @param enc The encryption method parameter. Must not be - * {@code null}. - */ - public JWEHeader(final JWEAlgorithm alg, final EncryptionMethod enc) { - - this( - alg, enc, - null, null, null, null, null, null, null, null, null, null, - null, null, null, null, null, 0, - null, null, - null, null); - } - - - /** - * Creates a new JSON Web Encryption (JWE) header. - * - *

Note: Use {@link PlainHeader} to create a header with algorithm - * {@link Algorithm#NONE none}. - * - * @param alg The JWE algorithm ({@code alg}) parameter. - * Must not be "none" or {@code null}. - * @param enc The encryption method 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 epk The Ephemeral Public Key ({@code epk}) - * parameter, {@code null} if not specified. - * @param zip The compression algorithm ({@code zip}) - * parameter, {@code null} if not specified. - * @param apu The agreement PartyUInfo ({@code apu}) - * parameter, {@code null} if not specified. - * @param apv The agreement PartyVInfo ({@code apv}) - * parameter, {@code null} if not specified. - * @param p2s The PBES2 salt ({@code p2s}) parameter, - * {@code null} if not specified. - * @param p2c The PBES2 count ({@code p2c}) parameter, zero - * if not specified. Must not be negative. - * @param iv The initialisation vector ({@code iv}) - * parameter, {@code null} if not specified. - * @param tag The authentication tag ({@code tag}) - * 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. - */ - public JWEHeader(final Algorithm alg, - final EncryptionMethod enc, - final JOSEObjectType typ, - final String cty, - final Set crit, - final URI jku, - final JWK jwk, - final URI x5u, - final Base64URL x5t, - final Base64URL x5t256, - final List x5c, - final String kid, - final JWK epk, - final CompressionAlgorithm zip, - final Base64URL apu, - final Base64URL apv, - final Base64URL p2s, - final int p2c, - final Base64URL iv, - final Base64URL tag, - final Map customParams, - final Base64URL parsedBase64URL) { - - super(alg, typ, cty, crit, jku, jwk, x5u, x5t, x5t256, x5c, kid, customParams, parsedBase64URL); - - if (alg.getName().equals(Algorithm.NONE.getName())) { - throw new IllegalArgumentException("The JWE algorithm cannot be \"none\""); - } - - if (enc == null) { - throw new IllegalArgumentException("The encryption method \"enc\" parameter must not be null"); - } - - if (epk != null && epk.isPrivate()) { - throw new IllegalArgumentException("Ephemeral public key should not be a private key"); - } - - this.enc = enc; - - this.epk = epk; - this.zip = zip; - this.apu = apu; - this.apv = apv; - this.p2s = p2s; - this.p2c = p2c; - this.iv = iv; - this.tag = tag; - } - - - /** - * Deep copy constructor. - * - * @param jweHeader The JWE header to copy. Must not be {@code null}. - */ - public JWEHeader(final JWEHeader jweHeader) { - - this( - jweHeader.getAlgorithm(), - jweHeader.getEncryptionMethod(), - jweHeader.getType(), - jweHeader.getContentType(), - jweHeader.getCriticalParams(), - jweHeader.getJWKURL(), - jweHeader.getJWK(), - jweHeader.getX509CertURL(), - jweHeader.getX509CertThumbprint(), - jweHeader.getX509CertSHA256Thumbprint(), - jweHeader.getX509CertChain(), - jweHeader.getKeyID(), - jweHeader.getEphemeralPublicKey(), - jweHeader.getCompressionAlgorithm(), - jweHeader.getAgreementPartyUInfo(), - jweHeader.getAgreementPartyVInfo(), - jweHeader.getPBES2Salt(), - jweHeader.getPBES2Count(), - jweHeader.getIV(), - jweHeader.getAuthTag(), - jweHeader.getCustomParams(), - jweHeader.getParsedBase64URL() - ); - } - - - /** - * Gets the registered parameter names for JWE headers. - * - * @return The registered parameter names, as an unmodifiable set. - */ - public static Set getRegisteredParameterNames() { - - return REGISTERED_PARAMETER_NAMES; - } - - - /** - * Gets the algorithm ({@code alg}) parameter. - * - * @return The algorithm parameter. - */ - public JWEAlgorithm getAlgorithm() { - - return (JWEAlgorithm)super.getAlgorithm(); - } - - - /** - * Gets the encryption method ({@code enc}) parameter. - * - * @return The encryption method parameter. - */ - public EncryptionMethod getEncryptionMethod() { - - return enc; - } - - - /** - * Gets the Ephemeral Public Key ({@code epk}) parameter. - * - * @return The Ephemeral Public Key parameter, {@code null} if not - * specified. - */ - public JWK getEphemeralPublicKey() { - - return epk; - } - - - /** - * Gets the compression algorithm ({@code zip}) parameter. - * - * @return The compression algorithm parameter, {@code null} if not - * specified. - */ - public CompressionAlgorithm getCompressionAlgorithm() { - - return zip; - } - - - /** - * Gets the agreement PartyUInfo ({@code apu}) parameter. - * - * @return The agreement PartyUInfo parameter, {@code null} if not - * specified. - */ - public Base64URL getAgreementPartyUInfo() { - - return apu; - } - - - /** - * Gets the agreement PartyVInfo ({@code apv}) parameter. - * - * @return The agreement PartyVInfo parameter, {@code null} if not - * specified. - */ - public Base64URL getAgreementPartyVInfo() { - - return apv; - } - - - /** - * Gets the PBES2 salt ({@code p2s}) parameter. - * - * @return The PBES2 salt parameter, {@code null} if not specified. - */ - public Base64URL getPBES2Salt() { - - return p2s; - } - - - /** - * Gets the PBES2 count ({@code p2c}) parameter. - * - * @return The PBES2 count parameter, zero if not specified. - */ - public int getPBES2Count() { - - return p2c; - } - - - /** - * Gets the initialisation vector ({@code iv}) parameter. - * - * @return The initialisation vector, {@code null} if not specified. - */ - public Base64URL getIV() { - - return iv; - } - - - /** - * Gets the authentication tag ({@code tag}) parameter. - * - * @return The authentication tag, {@code null} if not specified. - */ - public Base64URL getAuthTag() { - - return tag; - } - - - @Override - public Set getIncludedParams() { - - Set includedParameters = super.getIncludedParams(); - - if (enc != null) { - includedParameters.add("enc"); - } - - if (epk != null) { - includedParameters.add("epk"); - } - - if (zip != null) { - includedParameters.add("zip"); - } - - if (apu != null) { - includedParameters.add("apu"); - } - - if (apv != null) { - includedParameters.add("apv"); - } - - if (p2s != null) { - includedParameters.add("p2s"); - } - - if (p2c > 0) { - includedParameters.add("p2c"); - } - - if (iv != null) { - includedParameters.add("iv"); - } - - if (tag != null) { - includedParameters.add("tag"); - } - - return includedParameters; - } - - - @Override - public JSONObject toJSONObject() { - - JSONObject o = super.toJSONObject(); - - if (enc != null) { - o.put("enc", enc.toString()); - } - - if (epk != null) { - o.put("epk", epk.toJSONObject()); - } - - if (zip != null) { - o.put("zip", zip.toString()); - } - - if (apu != null) { - o.put("apu", apu.toString()); - } - - if (apv != null) { - o.put("apv", apv.toString()); - } - - if (p2s != null) { - o.put("p2s", p2s.toString()); - } - - if (p2c > 0) { - o.put("p2c", p2c); - } - - if (iv != null) { - o.put("iv", iv.toString()); - } - - if (tag != null) { - o.put("tag", tag.toString()); - } - - return o; - } - - - /** - * Parses an encryption method ({@code enc}) parameter from the - * specified JWE header JSON object. - * - * @param json The JSON object to parse. Must not be {@code null}. - * - * @return The encryption method. - * - * @throws ParseException If the {@code enc} parameter couldn't be - * parsed. - */ - private static EncryptionMethod parseEncryptionMethod(final JSONObject json) - throws ParseException { - - return EncryptionMethod.parse(JSONObjectUtils.getString(json, "enc")); - } - - - /** - * Parses a JWE header from the specified JSON object. - * - * @param jsonObject The JSON object to parse. Must not be - * {@code null}. - * - * @return The JWE header. - * - * @throws ParseException If the specified JSON object doesn't - * represent a valid JWE header. - */ - public static JWEHeader parse(final JSONObject jsonObject) - throws ParseException { - - return parse(jsonObject, null); - } - - - /** - * Parses a JWE header 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 JWE header. - * - * @throws ParseException If the specified JSON object doesn't - * represent a valid JWE header. - */ - public static JWEHeader parse(final JSONObject jsonObject, - final Base64URL parsedBase64URL) - throws ParseException { - - // Get the "alg" parameter - Algorithm alg = Header.parseAlgorithm(jsonObject); - - if (! (alg instanceof JWEAlgorithm)) { - throw new ParseException("The algorithm \"alg\" header parameter must be for encryption", 0); - } - - // Get the "enc" parameter - EncryptionMethod enc = parseEncryptionMethod(jsonObject); - - JWEHeader.Builder header = new Builder((JWEAlgorithm)alg, enc).parsedBase64URL(parsedBase64URL); - - // Parse optional + custom parameters - for(final String name: jsonObject.keySet()) { - - if("alg".equals(name)) { - // skip - } else if("enc".equals(name)) { - // skip - } else if("typ".equals(name)) { - header = header.type(new JOSEObjectType(JSONObjectUtils.getString(jsonObject, name))); - } else if("cty".equals(name)) { - header = header.contentType(JSONObjectUtils.getString(jsonObject, name)); - } else if("crit".equals(name)) { - header = header.criticalParams(new HashSet<>(JSONObjectUtils.getStringList(jsonObject, name))); - } else if("jku".equals(name)) { - header = header.jwkURL(JSONObjectUtils.getURI(jsonObject, name)); - } else if("jwk".equals(name)) { - header = header.jwk(JWK.parse(JSONObjectUtils.getJSONObject(jsonObject, name))); - } else if("x5u".equals(name)) { - header = header.x509CertURL(JSONObjectUtils.getURI(jsonObject, name)); - } else if("x5t".equals(name)) { - header = header.x509CertThumbprint(new Base64URL(JSONObjectUtils.getString(jsonObject, name))); - } else if("x5t#S256".equals(name)) { - header = header.x509CertSHA256Thumbprint(new Base64URL(JSONObjectUtils.getString(jsonObject, name))); - } else if("x5c".equals(name)) { - header = header.x509CertChain(X509CertChainUtils.toBase64List(JSONObjectUtils.getJSONArray(jsonObject, name))); - } else if("kid".equals(name)) { - header = header.keyID(JSONObjectUtils.getString(jsonObject, name)); - } else if("epk".equals(name)) { - header = header.ephemeralPublicKey(JWK.parse(JSONObjectUtils.getJSONObject(jsonObject, name))); - } else if("zip".equals(name)) { - header = header.compressionAlgorithm(new CompressionAlgorithm(JSONObjectUtils.getString(jsonObject, name))); - } else if("apu".equals(name)) { - header = header.agreementPartyUInfo(new Base64URL(JSONObjectUtils.getString(jsonObject, name))); - } else if("apv".equals(name)) { - header = header.agreementPartyVInfo(new Base64URL(JSONObjectUtils.getString(jsonObject, name))); - } else if("p2s".equals(name)) { - header = header.pbes2Salt(new Base64URL(JSONObjectUtils.getString(jsonObject, name))); - } else if("p2c".equals(name)) { - header = header.pbes2Count(JSONObjectUtils.getInt(jsonObject, name)); - } else if("iv".equals(name)) { - header = header.iv(new Base64URL(JSONObjectUtils.getString(jsonObject, name))); - } else if("tag".equals(name)) { - header = header.authTag(new Base64URL(JSONObjectUtils.getString(jsonObject, name))); - } else { - header = header.customParam(name, jsonObject.get(name)); - } - } - - return header.build(); - } - - - /** - * Parses a JWE header from the specified JSON object string. - * - * @param jsonString The JSON object string to parse. Must not be {@code null}. - * - * @return The JWE header. - * - * @throws ParseException If the specified JSON object string doesn't - * represent a valid JWE header. - */ - public static JWEHeader parse(final String jsonString) - throws ParseException { - - return parse(JSONObjectUtils.parse(jsonString), null); - } - - - /** - * Parses a JWE header from the specified JSON object string. - * - * @param jsonString The JSON string to parse. Must not be - * {@code null}. - * @param parsedBase64URL The original parsed Base64URL, {@code null} - * if not applicable. - * - * @return The JWE header. - * - * @throws ParseException If the specified JSON object string doesn't - * represent a valid JWE header. - */ - public static JWEHeader parse(final String jsonString, - final Base64URL parsedBase64URL) - throws ParseException { - - return parse(JSONObjectUtils.parse(jsonString), parsedBase64URL); - } - - - /** - * Parses a JWE header from the specified Base64URL. - * - * @param base64URL The Base64URL to parse. Must not be {@code null}. - * - * @return The JWE header. - * - * @throws ParseException If the specified Base64URL doesn't represent - * a valid JWE header. - */ - public static JWEHeader parse(final Base64URL base64URL) - throws ParseException { - - return parse(base64URL.decodeToString(), base64URL); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JWEObject.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JWEObject.java deleted file mode 100644 index 899d05b2e..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JWEObject.java +++ /dev/null @@ -1,511 +0,0 @@ -/* - * 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. - * - *

-	 * [header-base64url].[encryptedKey-base64url].[iv-base64url].[cipherText-base64url].[authTag-base64url]
-	 * 
- * - * @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]); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JWEProvider.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JWEProvider.java deleted file mode 100644 index f74ff7fbd..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JWEProvider.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * 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. - * - *

The JWE provider can be queried to determine its algorithm capabilities. - * - * @author Vladimir Dzhuvinov - * @version 2015-05-26 - */ -public interface JWEProvider extends JOSEProvider, JCAAware { - - - /** - * 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 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 supportedEncryptionMethods(); -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JWSAlgorithm.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JWSAlgorithm.java deleted file mode 100644 index c8abdb1d3..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JWSAlgorithm.java +++ /dev/null @@ -1,275 +0,0 @@ -/* - * 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. - * - *

Includes constants for the following standard JWS algorithm names: - * - *

    - *
  • {@link #HS256} - *
  • {@link #HS384} - *
  • {@link #HS512} - *
  • {@link #RS256} - *
  • {@link #RS384} - *
  • {@link #RS512} - *
  • {@link #ES256} - *
  • {@link #ES384} - *
  • {@link #ES512} - *
  • {@link #PS256} - *
  • {@link #PS384} - *
  • {@link #PS512} - *
  • {@link #EdDSA} - *
  • {@link #ES256K} (non-standard) - *
- * - *

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 { - - - 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); - } - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JWSHeader.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JWSHeader.java deleted file mode 100644 index 13abc3fd7..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JWSHeader.java +++ /dev/null @@ -1,727 +0,0 @@ -/* - * 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.text.ParseException; -import java.util.*; - -import com.nimbusds.jose.jwk.JWK; -import com.nimbusds.jose.util.Base64; -import com.nimbusds.jose.util.Base64URL; -import com.nimbusds.jose.util.JSONObjectUtils; -import com.nimbusds.jose.util.X509CertChainUtils; -import net.jcip.annotations.Immutable; -import net.minidev.json.JSONObject; - - -/** - * JSON Web Signature (JWS) header. This class is immutable. - * - *

Supports all {@link #getRegisteredParameterNames registered header - * parameters} of the JWS specification: - * - *

    - *
  • alg - *
  • jku - *
  • jwk - *
  • x5u - *
  • x5t - *
  • x5t#S256 - *
  • x5c - *
  • kid - *
  • typ - *
  • cty - *
  • crit - *
- * - *

The header may also include {@link #getCustomParams custom - * parameters}; these will be serialised and parsed along the registered ones. - * - *

Example header of a JSON Web Signature (JWS) object using the - * {@link JWSAlgorithm#HS256 HMAC SHA-256 algorithm}: - * - *

- * {
- *   "alg" : "HS256"
- * }
- * 
- * - * @author Vladimir Dzhuvinov - * @version 2017-04-09 - */ -@Immutable -public final class JWSHeader extends CommonSEHeader { - - - private static final long serialVersionUID = 1L; - - - /** - * The registered parameter names. - */ - private static final Set REGISTERED_PARAMETER_NAMES; - - - /** - * Initialises the registered parameter name set. - */ - static { - Set p = new HashSet<>(); - - p.add("alg"); - p.add("jku"); - p.add("jwk"); - p.add("x5u"); - p.add("x5t"); - p.add("x5t#S256"); - p.add("x5c"); - p.add("kid"); - p.add("typ"); - p.add("cty"); - p.add("crit"); - - REGISTERED_PARAMETER_NAMES = Collections.unmodifiableSet(p); - } - - - /** - * Builder for constructing JSON Web Signature (JWS) headers. - * - *

Example usage: - * - *

-	 * JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.HS256).
-	 *                    contentType("text/plain").
-	 *                    customParam("exp", new Date().getTime()).
-	 *                    build();
-	 * 
- */ - public static class Builder { - - - /** - * The JWS algorithm. - */ - private final JWSAlgorithm alg; - - - /** - * The JOSE object type. - */ - private JOSEObjectType typ; - - - /** - * The content type. - */ - private String cty; - - - /** - * The critical headers. - */ - private Set crit; - - - /** - * JWK Set URL. - */ - private URI jku; - - - /** - * JWK. - */ - private JWK jwk; - - - /** - * X.509 certificate URL. - */ - private URI x5u; - - - /** - * X.509 certificate SHA-1 thumbprint. - */ - @Deprecated - private Base64URL x5t; - - - /** - * X.509 certificate SHA-256 thumbprint. - */ - private Base64URL x5t256; - - - /** - * The X.509 certificate chain corresponding to the key used to - * sign the JWS object. - */ - private List x5c; - - - /** - * Key ID. - */ - private String kid; - - - /** - * Custom header parameters. - */ - private Map customParams; - - - /** - * The parsed Base64URL. - */ - private Base64URL parsedBase64URL; - - - /** - * Creates a new JWS header builder. - * - * @param alg The JWS algorithm ({@code alg}) parameter. Must - * not be "none" or {@code null}. - */ - public Builder(final JWSAlgorithm alg) { - - if (alg.getName().equals(Algorithm.NONE.getName())) { - throw new IllegalArgumentException("The JWS algorithm \"alg\" cannot be \"none\""); - } - - this.alg = alg; - } - - - /** - * Creates a new JWS header builder with the parameters from - * the specified header. - * - * @param jwsHeader The JWS header to use. Must not not be - * {@code null}. - */ - public Builder(final JWSHeader jwsHeader) { - - this(jwsHeader.getAlgorithm()); - - typ = jwsHeader.getType(); - cty = jwsHeader.getContentType(); - crit = jwsHeader.getCriticalParams(); - - jku = jwsHeader.getJWKURL(); - jwk = jwsHeader.getJWK(); - x5u = jwsHeader.getX509CertURL(); - x5t = jwsHeader.getX509CertThumbprint(); - x5t256 = jwsHeader.getX509CertSHA256Thumbprint(); - x5c = jwsHeader.getX509CertChain(); - kid = jwsHeader.getKeyID(); - customParams = jwsHeader.getCustomParams(); - } - - - /** - * Sets the type ({@code typ}) parameter. - * - * @param typ The type parameter, {@code null} if not - * specified. - * - * @return This builder. - */ - public Builder type(final JOSEObjectType typ) { - - this.typ = typ; - return this; - } - - - /** - * Sets the content type ({@code cty}) parameter. - * - * @param cty The content type parameter, {@code null} if not - * specified. - * - * @return This builder. - */ - public Builder contentType(final String cty) { - - this.cty = cty; - return this; - } - - - /** - * Sets the critical header parameters ({@code crit}) - * parameter. - * - * @param crit The names of the critical header parameters, - * empty set or {@code null} if none. - * - * @return This builder. - */ - public Builder criticalParams(final Set crit) { - - this.crit = crit; - return this; - } - - - /** - * Sets the JSON Web Key (JWK) Set URL ({@code jku}) parameter. - * - * @param jku The JSON Web Key (JWK) Set URL parameter, - * {@code null} if not specified. - * - * @return This builder. - */ - public Builder jwkURL(final URI jku) { - - this.jku = jku; - return this; - } - - - /** - * Sets the JSON Web Key (JWK) ({@code jwk}) parameter. - * - * @param jwk The JSON Web Key (JWK) ({@code jwk}) parameter, - * {@code null} if not specified. - * - * @return This builder. - */ - public Builder jwk(final JWK jwk) { - - this.jwk = jwk; - return this; - } - - - /** - * Sets the X.509 certificate URL ({@code x5u}) parameter. - * - * @param x5u The X.509 certificate URL parameter, {@code null} - * if not specified. - * - * @return This builder. - */ - public Builder x509CertURL(final URI x5u) { - - this.x5u = x5u; - return this; - } - - - /** - * Sets the X.509 certificate SHA-1 thumbprint ({@code x5t}) - * parameter. - * - * @param x5t The X.509 certificate SHA-1 thumbprint parameter, - * {@code null} if not specified. - * - * @return This builder. - */ - @Deprecated - public Builder x509CertThumbprint(final Base64URL x5t) { - - this.x5t = x5t; - return this; - } - - - /** - * Sets the X.509 certificate SHA-256 thumbprint - * ({@code x5t#S256}) parameter. - * - * @param x5t256 The X.509 certificate SHA-256 thumbprint - * parameter, {@code null} if not specified. - * - * @return This builder. - */ - public Builder x509CertSHA256Thumbprint(final Base64URL x5t256) { - - this.x5t256 = x5t256; - return this; - } - - - /** - * Sets the X.509 certificate chain parameter ({@code x5c}) - * corresponding to the key used to sign the JWS object. - * - * @param x5c The X.509 certificate chain parameter, - * {@code null} if not specified. - * - * @return This builder. - */ - public Builder x509CertChain(final List x5c) { - - this.x5c = x5c; - return this; - } - - - /** - * Sets the key ID ({@code kid}) parameter. - * - * @param kid The key ID parameter, {@code null} if not - * specified. - * - * @return This builder. - */ - public Builder keyID(final String kid) { - - this.kid = kid; - return this; - } - - - /** - * Sets a custom (non-registered) parameter. - * - * @param name The name of the custom parameter. Must not - * match a registered parameter name and must not - * be {@code null}. - * @param value The value of the custom parameter, should map - * to a valid JSON entity, {@code null} if not - * specified. - * - * @return This builder. - * - * @throws IllegalArgumentException If the specified parameter - * name matches a registered - * parameter name. - */ - public Builder customParam(final String name, final Object value) { - - if (getRegisteredParameterNames().contains(name)) { - throw new IllegalArgumentException("The parameter name \"" + name + "\" matches a registered name"); - } - - if (customParams == null) { - customParams = new HashMap<>(); - } - - customParams.put(name, value); - - return this; - } - - - /** - * Sets the custom (non-registered) parameters. The values must - * be serialisable to a JSON entity, otherwise will be ignored. - * - * @param customParameters The custom parameters, empty map or - * {@code null} if none. - * - * @return This builder. - */ - public Builder customParams(final Map customParameters) { - - this.customParams = customParameters; - return this; - } - - - /** - * Sets the parsed Base64URL. - * - * @param base64URL The parsed Base64URL, {@code null} if the - * header is created from scratch. - * - * @return This builder. - */ - public Builder parsedBase64URL(final Base64URL base64URL) { - - this.parsedBase64URL = base64URL; - return this; - } - - - /** - * Builds a new JWS header. - * - * @return The JWS header. - */ - public JWSHeader build() { - - return new JWSHeader( - alg, typ, cty, crit, - jku, jwk, x5u, x5t, x5t256, x5c, kid, - customParams, parsedBase64URL); - } - } - - - /** - * Creates a new minimal JSON Web Signature (JWS) header. - * - *

Note: Use {@link PlainHeader} to create a header with algorithm - * {@link Algorithm#NONE none}. - * - * @param alg The JWS algorithm ({@code alg}) parameter. Must not be - * "none" or {@code null}. - */ - public JWSHeader(final JWSAlgorithm alg) { - - this(alg, null, null, null, null, null, null, null, null, null, null, null, null); - } - - - /** - * Creates a new JSON Web Signature (JWS) header. - * - *

Note: Use {@link PlainHeader} to create a header with algorithm - * {@link Algorithm#NONE none}. - * - * @param alg The JWS algorithm ({@code alg}) parameter. - * Must not be "none" or {@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. - */ - public JWSHeader(final JWSAlgorithm alg, - final JOSEObjectType typ, - final String cty, - final Set crit, - final URI jku, - final JWK jwk, - final URI x5u, - final Base64URL x5t, - final Base64URL x5t256, - final List x5c, - final String kid, - final Map customParams, - final Base64URL parsedBase64URL) { - - super(alg, typ, cty, crit, jku, jwk, x5u, x5t, x5t256, x5c, kid, customParams, parsedBase64URL); - - if (alg.getName().equals(Algorithm.NONE.getName())) { - throw new IllegalArgumentException("The JWS algorithm \"alg\" cannot be \"none\""); - } - } - - - /** - * Deep copy constructor. - * - * @param jwsHeader The JWS header to copy. Must not be {@code null}. - */ - public JWSHeader(final JWSHeader jwsHeader) { - - this( - jwsHeader.getAlgorithm(), - jwsHeader.getType(), - jwsHeader.getContentType(), - jwsHeader.getCriticalParams(), - jwsHeader.getJWKURL(), - jwsHeader.getJWK(), - jwsHeader.getX509CertURL(), - jwsHeader.getX509CertThumbprint(), - jwsHeader.getX509CertSHA256Thumbprint(), - jwsHeader.getX509CertChain(), - jwsHeader.getKeyID(), - jwsHeader.getCustomParams(), - jwsHeader.getParsedBase64URL() - ); - } - - - /** - * Gets the registered parameter names for JWS headers. - * - * @return The registered parameter names, as an unmodifiable set. - */ - public static Set getRegisteredParameterNames() { - - return REGISTERED_PARAMETER_NAMES; - } - - - /** - * Gets the algorithm ({@code alg}) parameter. - * - * @return The algorithm parameter. - */ - @Override - public JWSAlgorithm getAlgorithm() { - - return (JWSAlgorithm)super.getAlgorithm(); - } - - - /** - * Parses a JWS header from the specified JSON object. - * - * @param jsonObject The JSON object to parse. Must not be - * {@code null}. - * - * @return The JWS header. - * - * @throws ParseException If the specified JSON object doesn't - * represent a valid JWS header. - */ - public static JWSHeader parse(final JSONObject jsonObject) - throws ParseException { - - return parse(jsonObject, null); - } - - - /** - * Parses a JWS header 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 JWS header. - * - * @throws ParseException If the specified JSON object doesn't - * represent a valid JWS header. - */ - public static JWSHeader parse(final JSONObject jsonObject, - final Base64URL parsedBase64URL) - throws ParseException { - - // Get the "alg" parameter - Algorithm alg = Header.parseAlgorithm(jsonObject); - - if (! (alg instanceof JWSAlgorithm)) { - throw new ParseException("The algorithm \"alg\" header parameter must be for signatures", 0); - } - - JWSHeader.Builder header = new Builder((JWSAlgorithm)alg).parsedBase64URL(parsedBase64URL); - - // Parse optional + custom parameters - for (final String name: jsonObject.keySet()) { - - if("alg".equals(name)) { - // skip - } else if("typ".equals(name)) { - header = header.type(new JOSEObjectType(JSONObjectUtils.getString(jsonObject, name))); - } else if("cty".equals(name)) { - header = header.contentType(JSONObjectUtils.getString(jsonObject, name)); - } else if("crit".equals(name)) { - header = header.criticalParams(new HashSet<>(JSONObjectUtils.getStringList(jsonObject, name))); - } else if("jku".equals(name)) { - header = header.jwkURL(JSONObjectUtils.getURI(jsonObject, name)); - } else if("jwk".equals(name)) { - header = header.jwk(JWK.parse(JSONObjectUtils.getJSONObject(jsonObject, name))); - } else if("x5u".equals(name)) { - header = header.x509CertURL(JSONObjectUtils.getURI(jsonObject, name)); - } else if("x5t".equals(name)) { - header = header.x509CertThumbprint(new Base64URL(JSONObjectUtils.getString(jsonObject, name))); - } else if("x5t#S256".equals(name)) { - header = header.x509CertSHA256Thumbprint(new Base64URL(JSONObjectUtils.getString(jsonObject, name))); - } else if("x5c".equals(name)) { - header = header.x509CertChain(X509CertChainUtils.toBase64List(JSONObjectUtils.getJSONArray(jsonObject, name))); - } else if("kid".equals(name)) { - header = header.keyID(JSONObjectUtils.getString(jsonObject, name)); - } else { - header = header.customParam(name, jsonObject.get(name)); - } - } - - return header.build(); - } - - - /** - * Parses a JWS header from the specified JSON object string. - * - * @param jsonString The JSON string to parse. Must not be - * {@code null}. - * - * @return The JWS header. - * - * @throws ParseException If the specified JSON object string doesn't - * represent a valid JWS header. - */ - public static JWSHeader parse(final String jsonString) - throws ParseException { - - return parse(jsonString, null); - } - - - /** - * Parses a JWS header from the specified JSON object string. - * - * @param jsonString The JSON string to parse. Must not be - * {@code null}. - * @param parsedBase64URL The original parsed Base64URL, {@code null} - * if not applicable. - * - * @return The JWS header. - * - * @throws ParseException If the specified JSON object string doesn't - * represent a valid JWS header. - */ - public static JWSHeader parse(final String jsonString, - final Base64URL parsedBase64URL) - throws ParseException { - - return parse(JSONObjectUtils.parse(jsonString), parsedBase64URL); - } - - - /** - * Parses a JWS header from the specified Base64URL. - * - * @param base64URL The Base64URL to parse. Must not be {@code null}. - * - * @return The JWS header. - * - * @throws ParseException If the specified Base64URL doesn't represent - * a valid JWS header. - */ - public static JWSHeader parse(final Base64URL base64URL) - throws ParseException { - - return parse(base64URL.decodeToString(), base64URL); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JWSObject.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JWSObject.java deleted file mode 100644 index 004837ffa..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JWSObject.java +++ /dev/null @@ -1,423 +0,0 @@ -/* - * 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 com.nimbusds.jose.util.Base64URL; -import com.nimbusds.jose.util.StandardCharset; -import net.jcip.annotations.ThreadSafe; - - -/** - * JSON Web Signature (JWS) secured object. This class is thread-safe. - * - * @author Vladimir Dzhuvinov - * @version 2016-07-26 - */ -@ThreadSafe -public class JWSObject extends JOSEObject { - - - private static final long serialVersionUID = 1L; - - - /** - * Enumeration of the states of a JSON Web Signature (JWS) object. - */ - public enum State { - - - /** - * The JWS object is created but not signed yet. - */ - UNSIGNED, - - - /** - * The JWS object is signed but its signature is not verified. - */ - SIGNED, - - - /** - * The JWS object is signed and its signature was successfully verified. - */ - VERIFIED - } - - - /** - * The header. - */ - private final JWSHeader header; - - - /** - * The signing input for this JWS object. - * - *

Format: - * - *

-	 * [header-base64url].[payload-base64url]
-	 * 
- */ - private final String signingInputString; - - - /** - * The signature, {@code null} if not signed. - */ - private Base64URL signature; - - - /** - * The JWS object state. - */ - private State state; - - - /** - * Creates a new to-be-signed JSON Web Signature (JWS) object with the - * specified header and payload. The initial state will be - * {@link State#UNSIGNED unsigned}. - * - * @param header The JWS header. Must not be {@code null}. - * @param payload The payload. Must not be {@code null}. - */ - public JWSObject(final JWSHeader header, final Payload payload) { - - if (header == null) { - - throw new IllegalArgumentException("The JWS header must not be null"); - } - - this.header = header; - - if (payload == null) { - - throw new IllegalArgumentException("The payload must not be null"); - } - - setPayload(payload); - - signingInputString = composeSigningInput(header.toBase64URL(), payload.toBase64URL()); - - signature = null; - - state = State.UNSIGNED; - } - - - /** - * Creates a new signed JSON Web Signature (JWS) object with the - * specified serialised parts. The state will be - * {@link State#SIGNED signed}. - * - * @param firstPart The first part, corresponding to the JWS header. - * Must not be {@code null}. - * @param secondPart The second part, corresponding to the payload. Must - * not be {@code null}. - * @param thirdPart The third part, corresponding to the signature. - * Must not be {@code null}. - * - * @throws ParseException If parsing of the serialised parts failed. - */ - public JWSObject(final Base64URL firstPart, final Base64URL secondPart, final Base64URL thirdPart) - throws ParseException { - - if (firstPart == null) { - - throw new IllegalArgumentException("The first part must not be null"); - } - - try { - this.header = JWSHeader.parse(firstPart); - - } catch (ParseException e) { - - throw new ParseException("Invalid JWS header: " + e.getMessage(), 0); - } - - if (secondPart == null) { - - throw new IllegalArgumentException("The second part must not be null"); - } - - setPayload(new Payload(secondPart)); - - signingInputString = composeSigningInput(firstPart, secondPart); - - if (thirdPart == null) { - throw new IllegalArgumentException("The third part must not be null"); - } - - signature = thirdPart; - - state = State.SIGNED; // but signature not verified yet! - - setParsedParts(firstPart, secondPart, thirdPart); - } - - - @Override - public JWSHeader getHeader() { - - return header; - } - - - /** - * Composes the signing input for the specified JWS object parts. - * - *

Format: - * - *

-	 * [header-base64url].[payload-base64url]
-	 * 
- * - * @param firstPart The first part, corresponding to the JWS header. - * Must not be {@code null}. - * @param secondPart The second part, corresponding to the payload. - * Must not be {@code null}. - * - * @return The signing input string. - */ - private static String composeSigningInput(final Base64URL firstPart, final Base64URL secondPart) { - - return firstPart.toString() + '.' + secondPart.toString(); - } - - - /** - * Returns the signing input for this JWS object. - * - *

Format: - * - *

-	 * [header-base64url].[payload-base64url]
-	 * 
- * - * @return The signing input, to be passed to a JWS signer or verifier. - */ - public byte[] getSigningInput() { - - return signingInputString.getBytes(StandardCharset.UTF_8); - } - - - /** - * Returns the signature of this JWS object. - * - * @return The signature, {@code null} if the JWS object is not signed - * yet. - */ - public Base64URL getSignature() { - - return signature; - } - - - /** - * Returns the state of this JWS object. - * - * @return The state. - */ - public State getState() { - - return state; - } - - - /** - * Ensures the current state is {@link State#UNSIGNED unsigned}. - * - * @throws IllegalStateException If the current state is not unsigned. - */ - private void ensureUnsignedState() { - - if (state != State.UNSIGNED) { - - throw new IllegalStateException("The JWS object must be in an unsigned state"); - } - } - - - /** - * Ensures the current state is {@link State#SIGNED signed} or - * {@link State#VERIFIED verified}. - * - * @throws IllegalStateException If the current state is not signed or - * verified. - */ - private void ensureSignedOrVerifiedState() { - - if (state != State.SIGNED && state != State.VERIFIED) { - - throw new IllegalStateException("The JWS object must be in a signed or verified state"); - } - } - - - /** - * Ensures the specified JWS signer supports the algorithm of this JWS - * object. - * - * @throws JOSEException If the JWS algorithm is not supported. - */ - private void ensureJWSSignerSupport(final JWSSigner signer) - throws JOSEException { - - if (! signer.supportedJWSAlgorithms().contains(getHeader().getAlgorithm())) { - - throw new JOSEException("The \"" + getHeader().getAlgorithm() + - "\" algorithm is not allowed or supported by the JWS signer: Supported algorithms: " + signer.supportedJWSAlgorithms()); - } - } - - - /** - * Signs this JWS object with the specified signer. The JWS object must - * be in a {@link State#UNSIGNED unsigned} state. - * - * @param signer The JWS signer. Must not be {@code null}. - * - * @throws IllegalStateException If the JWS object is not in an - * {@link State#UNSIGNED unsigned state}. - * @throws JOSEException If the JWS object couldn't be signed. - */ - public synchronized void sign(final JWSSigner signer) - throws JOSEException { - - ensureUnsignedState(); - - ensureJWSSignerSupport(signer); - - try { - signature = signer.sign(getHeader(), getSigningInput()); - - } 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.SIGNED; - } - - - /** - * Checks the signature of this JWS object with the specified verifier. - * The JWS object must be in a {@link State#SIGNED signed} state. - * - * @param verifier The JWS verifier. Must not be {@code null}. - * - * @return {@code true} if the signature was successfully verified, - * else {@code false}. - * - * @throws IllegalStateException If the JWS object is not in a - * {@link State#SIGNED signed} or - * {@link State#VERIFIED verified state}. - * @throws JOSEException If the JWS object couldn't be - * verified. - */ - public synchronized boolean verify(final JWSVerifier verifier) - throws JOSEException { - - ensureSignedOrVerifiedState(); - - boolean verified; - - try { - verified = verifier.verify(getHeader(), getSigningInput(), getSignature()); - - } catch (JOSEException e) { - - throw e; - - } catch (Exception e) { - - // Prevent throwing unchecked exceptions at this point, - // see issue #20 - throw new JOSEException(e.getMessage(), e); - } - - if (verified) { - - state = State.VERIFIED; - } - - return verified; - } - - - /** - * Serialises this JWS object to its compact format consisting of - * Base64URL-encoded parts delimited by period ('.') characters. It - * must be in a {@link State#SIGNED signed} or - * {@link State#VERIFIED verified} state. - * - *
-	 * [header-base64url].[payload-base64url].[signature-base64url]
-	 * 
- * - * @return The serialised JWS object. - * - * @throws IllegalStateException If the JWS object is not in a - * {@link State#SIGNED signed} or - * {@link State#VERIFIED verified} state. - */ - @Override - public String serialize() { - - ensureSignedOrVerifiedState(); - - return signingInputString + '.' + signature.toString(); - } - - - /** - * Parses a JWS object from the specified string in compact format. The - * parsed JWS object will be given a {@link State#SIGNED} state. - * - * @param s The string to parse. Must not be {@code null}. - * - * @return The JWS object. - * - * @throws ParseException If the string couldn't be parsed to a valid - * JWS object. - */ - public static JWSObject parse(final String s) - throws ParseException { - - Base64URL[] parts = JOSEObject.split(s); - - if (parts.length != 3) { - - throw new ParseException("Unexpected number of Base64URL parts, must be three", 0); - } - - return new JWSObject(parts[0], parts[1], parts[2]); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JWSProvider.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JWSProvider.java deleted file mode 100644 index 268e9745d..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JWSProvider.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * 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.JCAContext; - - -/** - * JSON Web Signature (JWS) provider - * - *

The JWS provider can be queried to determine its algorithm capabilities. - * - * @author Vladimir Dzhuvinov - * @version 2015-11-16 - */ -public interface JWSProvider extends JOSEProvider, JCAAware { - - - /** - * Returns the names of the supported algorithms by the JWS provider - * instance. These correspond to the {@code alg} JWS header parameter. - * - * @return The supported JWS algorithms, empty set if none. - */ - Set supportedJWSAlgorithms(); -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JWSSigner.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JWSSigner.java deleted file mode 100644 index fcf4cad32..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JWSSigner.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * 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 Signature (JWS) signer. - * - * @author Vladimir Dzhuvinov - * @version 2015-04-21 - */ -public interface JWSSigner extends JWSProvider { - - - /** - * Signs the specified {@link JWSObject#getSigningInput input} of a - * {@link JWSObject JWS object}. - * - * @param header The JSON Web Signature (JWS) header. Must - * specify a supported JWS algorithm and must not - * be {@code null}. - * @param signingInput The input to sign. Must not be {@code null}. - * - * @return The resulting signature part (third part) of the JWS object. - * - * @throws JOSEException If the JWS algorithm is not supported, if a - * critical header parameter is not supported or - * marked for deferral to the application, or if - * signing failed for some other internal reason. - */ - Base64URL sign(final JWSHeader header, final byte[] signingInput) - throws JOSEException; -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JWSVerifier.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JWSVerifier.java deleted file mode 100644 index 34e023030..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/JWSVerifier.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * 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 Signature (JWS) verifier. - * - * @author Vladimir Dzhuvinov - * @version 2015-04-21 - */ -public interface JWSVerifier extends JWSProvider { - - - /** - * Verifies the specified {@link JWSObject#getSignature signature} of a - * {@link JWSObject JWS object}. - * - * @param header The JSON Web Signature (JWS) header. Must - * specify a supported JWS algorithm and must not - * be {@code null}. - * @param signingInput The signing input. Must not be {@code null}. - * @param signature The signature part of the JWS object. Must not - * be {@code null}. - * - * @return {@code true} if the signature was successfully verified, - * {@code false} if the signature is invalid or if a critical - * header is neither supported nor marked for deferral to the - * application. - * - * @throws JOSEException If the JWS algorithm is not supported, or if - * signature verification failed for some other - * internal reason. - */ - boolean verify(final JWSHeader header, final byte[] signingInput, final Base64URL signature) - throws JOSEException; -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/KeyException.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/KeyException.java deleted file mode 100644 index 901fa023c..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/KeyException.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * 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; - - -/** - * Key exception. - * - * @author Vladimir Dzhuvinov - * @version 2015-06-29 - */ -public class KeyException extends JOSEException { - - - /** - * Creates a new key exception with the specified message. - * - * @param message The exception message. - */ - public KeyException(final String message) { - - super(message); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/KeyLengthException.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/KeyLengthException.java deleted file mode 100644 index 20ea6077e..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/KeyLengthException.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * 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; - - -/** - * Key length exception. - * - * @author Vladimir Dzhuvinov - * @version 205-06-29 - */ -public class KeyLengthException extends KeyException { - - - /** - * The expected key length. - */ - private final int expectedLength; - - - /** - * The algorithm. - */ - private final Algorithm alg; - - - /** - * Creates a new key length exception. - * - * @param message The exception message. - */ - public KeyLengthException(final String message) { - - super(message); - expectedLength = 0; - alg = null; - } - - - /** - * Creates a new key length exception. - * - * @param alg The JOSE algorithm, {@code null} if not specified. - */ - public KeyLengthException(final Algorithm alg) { - - this(0, alg); - } - - - /** - * Creates a new key length exception. - * - * @param expectedLength The expected key length in bits, zero if not - * specified. - * @param alg The JOSE algorithm, {@code null} if not - * specified. - */ - public KeyLengthException(final int expectedLength, final Algorithm alg) { - - super(( - (expectedLength > 0) ? "The expected key length is " + expectedLength + " bits" : "Unexpected key length") + - ((alg != null) ? " (for " + alg + " algorithm)" : "") - ); - - this.expectedLength = expectedLength; - this.alg = alg; - } - - - /** - * Returns the expected key length. - * - * @return The expected key length in bits, zero if not specified. - */ - public int getExpectedKeyLength() { - - return expectedLength; - } - - - /** - * Returns the algorithm. - * - * @return The JOSE algorithm, {@code null} if not specified. - */ - public Algorithm getAlgorithm() { - - return alg; - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/KeySourceException.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/KeySourceException.java deleted file mode 100644 index 868e4269a..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/KeySourceException.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * 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; - - -/** - * Key source exception. - * - * @author Vladimir Dzhuvinov - * @version 2016-06-21 - */ -public class KeySourceException extends JOSEException { - - - /** - * Creates a new key source exception. - * - * @param message The message. - */ - public KeySourceException(final String message) { - super(message); - } - - - /** - * Creates a new key source exception. - * - * @param message The message. - * @param cause The cause. - */ - public KeySourceException(final String message, final Throwable cause) { - super(message, cause); - } -} - diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/KeyTypeException.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/KeyTypeException.java deleted file mode 100644 index bbb4b7486..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/KeyTypeException.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * 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.security.Key; - - -/** - * Key type exception. - * - * @author Vladimir Dzhuvinov - * @version 2015-06-29 - */ -public class KeyTypeException extends KeyException { - - - /** - * Creates a new key type exception. - * - * @param expectedKeyClass The expected key class. Should not be - * {@code null}. - */ - public KeyTypeException(final Class expectedKeyClass) { - - super("Invalid key: Must be an instance of " + expectedKeyClass); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/Payload.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/Payload.java deleted file mode 100644 index 482dd56cd..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/Payload.java +++ /dev/null @@ -1,497 +0,0 @@ -/* - * 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 com.nimbusds.jose.util.StandardCharset; -import com.nimbusds.jwt.SignedJWT; -import net.jcip.annotations.Immutable; -import net.minidev.json.JSONObject; - - -/** - * Payload of an unsecured (plain), JSON Web Signature (JWS) or JSON Web - * Encryption (JWE) object. Supports JSON object, string, byte array, - * Base64URL, JWS object and signed JWT payload representations. This class is - * immutable. - * - *

UTF-8 is the character set for all conversions between strings and byte - * arrays. - * - *

Conversion relations: - * - *

- * JSONObject <=> String <=> Base64URL
- *                       <=> byte[]
- *                       <=> JWSObject
- *                       <=> SignedJWT
- * 
- * - * @author Vladimir Dzhuvinov - * @version 2016-07-26 - */ -@Immutable -public final class Payload implements Serializable { - - - /** - * Enumeration of the original data types used to create a - * {@link Payload}. - */ - public enum Origin { - - - /** - * The payload was created from a JSON object. - */ - JSON, - - - /** - * The payload was created from a string. - */ - STRING, - - - /** - * The payload was created from a byte array. - */ - BYTE_ARRAY, - - - /** - * The payload was created from a Base64URL-encoded object. - */ - BASE64URL, - - - /** - * The payload was created from a JWS object. - */ - JWS_OBJECT, - - - /** - * The payload was created from a signed JSON Web Token (JWT). - */ - SIGNED_JWT - } - - - private static final long serialVersionUID = 1L; - - - /** - * The original payload data type. - */ - private final Origin origin; - - - /** - * The JSON object representation. - */ - private final JSONObject jsonObject; - - - /** - * The string representation. - */ - private final String string; - - - /** - * The byte array representation. - */ - private final byte[] bytes; - - - /** - * The Base64URL representation. - */ - private final Base64URL base64URL; - - - /** - * The JWS object representation. - */ - private final JWSObject jwsObject; - - - /** - * The signed JWT representation. - */ - private final SignedJWT signedJWT; - - - /** - * Converts a byte array to a string using {@code UTF-8}. - * - * @param bytes The byte array to convert. May be {@code null}. - * - * @return The resulting string, {@code null} if conversion failed. - */ - private static String byteArrayToString(final byte[] bytes) { - - return bytes != null ? new String(bytes, StandardCharset.UTF_8) : null; - } - - - /** - * Converts a string to a byte array using {@code UTF-8}. - * - * @param string The string to convert. May be {@code null}. - * - * @return The resulting byte array, {@code null} if conversion failed. - */ - private static byte[] stringToByteArray(final String string) { - - return string != null ? string.getBytes(StandardCharset.UTF_8) : null; - } - - - /** - * Creates a new payload from the specified JSON object. - * - * @param jsonObject The JSON object representing the payload. Must not - * be {@code null}. - */ - public Payload(final JSONObject jsonObject) { - - if (jsonObject == null) { - throw new IllegalArgumentException("The JSON object must not be null"); - } - - this.jsonObject = jsonObject; - string = null; - bytes = null; - base64URL = null; - jwsObject = null; - signedJWT = null; - - origin = Origin.JSON; - } - - - /** - * Creates a new payload from the specified string. - * - * @param string The string representing the payload. Must not be - * {@code null}. - */ - public Payload(final String string) { - - if (string == null) { - throw new IllegalArgumentException("The string must not be null"); - } - - jsonObject = null; - this.string = string; - bytes = null; - base64URL = null; - jwsObject = null; - signedJWT = null; - - origin = Origin.STRING; - } - - - /** - * Creates a new payload from the specified byte array. - * - * @param bytes The byte array representing the payload. Must not be - * {@code null}. - */ - public Payload(final byte[] bytes) { - - if (bytes == null) { - throw new IllegalArgumentException("The byte array must not be null"); - } - - jsonObject = null; - string = null; - this.bytes = bytes; - base64URL = null; - jwsObject = null; - signedJWT = null; - - origin = Origin.BYTE_ARRAY; - } - - - /** - * Creates a new payload from the specified Base64URL-encoded object. - * - * @param base64URL The Base64URL-encoded object representing the - * payload. Must not be {@code null}. - */ - public Payload(final Base64URL base64URL) { - - if (base64URL == null) { - throw new IllegalArgumentException("The Base64URL-encoded object must not be null"); - } - - jsonObject = null; - string = null; - bytes = null; - this.base64URL = base64URL; - jwsObject = null; - signedJWT = null; - - origin = Origin.BASE64URL; - } - - - /** - * Creates a new payload from the specified JWS object. Intended for - * signed then encrypted JOSE objects. - * - * @param jwsObject The JWS object representing the payload. Must be in - * a signed state and not {@code null}. - */ - public Payload(final JWSObject jwsObject) { - - if (jwsObject == null) { - throw new IllegalArgumentException("The JWS object must not be null"); - } - - if (jwsObject.getState() == JWSObject.State.UNSIGNED) { - throw new IllegalArgumentException("The JWS object must be signed"); - } - - jsonObject = null; - string = null; - bytes = null; - base64URL = null; - this.jwsObject = jwsObject; - signedJWT = null; - - origin = Origin.JWS_OBJECT; - } - - - /** - * Creates a new payload from the specified signed JSON Web Token - * (JWT). Intended for signed then encrypted JWTs. - * - * @param signedJWT The signed JWT representing the payload. Must be in - * a signed state and not {@code null}. - */ - public Payload(final SignedJWT signedJWT) { - - if (signedJWT == null) { - throw new IllegalArgumentException("The signed JWT must not be null"); - } - - if (signedJWT.getState() == JWSObject.State.UNSIGNED) { - throw new IllegalArgumentException("The JWT must be signed"); - } - - jsonObject = null; - string = null; - bytes = null; - base64URL = null; - this.signedJWT = signedJWT; - jwsObject = signedJWT; // The signed JWT is also a JWS - - origin = Origin.SIGNED_JWT; - } - - - /** - * Gets the original data type used to create this payload. - * - * @return The payload origin. - */ - public Origin getOrigin() { - - return origin; - } - - - /** - * Returns a JSON object representation of this payload. - * - * @return The JSON object representation, {@code null} if the payload - * couldn't be converted to a JSON object. - */ - public JSONObject toJSONObject() { - - if (jsonObject != null) { - return jsonObject; - } - - // Convert - - String s = toString(); - - if (s == null) { - // to string conversion failed - return null; - } - - try { - return JSONObjectUtils.parse(s); - - } catch (ParseException e) { - // Payload not a JSON object - return null; - } - } - - - /** - * Returns a string representation of this payload. - * - * @return The string representation. - */ - @Override - public String toString() { - - if (string != null) { - - return string; - } - - // Convert - if (jwsObject != null) { - - if (jwsObject.getParsedString() != null) { - return jwsObject.getParsedString(); - } else { - return jwsObject.serialize(); - } - - } else if (jsonObject != null) { - - return jsonObject.toString(); - - } else if (bytes != null) { - - return byteArrayToString(bytes); - - } else if (base64URL != null) { - - return base64URL.decodeToString(); - } else { - return null; // should never happen - } - } - - - /** - * Returns a byte array representation of this payload. - * - * @return The byte array representation. - */ - public byte[] toBytes() { - - if (bytes != null) { - return bytes; - } - - // Convert - if (base64URL != null) { - return base64URL.decode(); - - } - - return stringToByteArray(toString()); - } - - - /** - * Returns a Base64URL representation of this payload. - * - * @return The Base64URL representation. - */ - public Base64URL toBase64URL() { - - if (base64URL != null) { - return base64URL; - } - - // Convert - return Base64URL.encode(toBytes()); - } - - - /** - * Returns a JWS object representation of this payload. Intended for - * signed then encrypted JOSE objects. - * - * @return The JWS object representation, {@code null} if the payload - * couldn't be converted to a JWS object. - */ - public JWSObject toJWSObject() { - - if (jwsObject != null) { - return jwsObject; - } - - try { - return JWSObject.parse(toString()); - - } catch (ParseException e) { - - return null; - } - } - - - /** - * Returns a signed JSON Web Token (JWT) representation of this - * payload. Intended for signed then encrypted JWTs. - * - * @return The signed JWT representation, {@code null} if the payload - * couldn't be converted to a signed JWT. - */ - public SignedJWT toSignedJWT() { - - if (signedJWT != null) { - return signedJWT; - } - - try { - return SignedJWT.parse(toString()); - - } catch (ParseException e) { - - return null; - } - } - - - /** - * Returns a transformation of this payload. - * - * @param Type of the result. - * @param transformer The payload transformer. Must not be - * {@code null}. - * - * @return The transformed payload. - */ - public T toType(final PayloadTransformer transformer) { - - return transformer.transform(this); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/PayloadTransformer.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/PayloadTransformer.java deleted file mode 100644 index 864c811da..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/PayloadTransformer.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * 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; - - -/** - * Generic payload type transformer. Implementations should be tread-safe. - */ -public interface PayloadTransformer { - - - /** - * Transforms the specified payload into the desired type. - * - * @param payload The payload. Not {@code null}. - * - * @return The desired type. - */ - T transform(final Payload payload); -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/PlainHeader.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/PlainHeader.java deleted file mode 100644 index 302537a40..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/PlainHeader.java +++ /dev/null @@ -1,477 +0,0 @@ -/* - * 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 java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import net.jcip.annotations.Immutable; - -import net.minidev.json.JSONObject; - -import com.nimbusds.jose.util.Base64URL; -import com.nimbusds.jose.util.JSONObjectUtils; - - -/** - * Unsecured ({@code alg=none}) JOSE header. This class is immutable. - * - *

Supports all {@link #getRegisteredParameterNames registered header - * parameters} of the unsecured JOSE object specification: - * - *

    - *
  • alg (set to {@link Algorithm#NONE "none"}). - *
  • typ - *
  • cty - *
  • crit - *
- * - *

The header may also carry {@link #getCustomParams custom parameters}; - * these will be serialised and parsed along the registered ones. - * - *

Example: - * - *

- * {
- *   "alg" : "none"
- * }
- * 
- * - * @author Vladimir Dzhuvinov - * @version 2014-08-20 - */ -@Immutable -public final class PlainHeader extends Header { - - - private static final long serialVersionUID = 1L; - - - /** - * The registered parameter names. - */ - private static final Set REGISTERED_PARAMETER_NAMES; - - - /** - * Initialises the registered parameter name set. - */ - static { - Set p = new HashSet<>(); - - p.add("alg"); - p.add("typ"); - p.add("cty"); - p.add("crit"); - - REGISTERED_PARAMETER_NAMES = Collections.unmodifiableSet(p); - } - - - /** - * Builder for constructing unsecured (plain) headers. - * - *

Example usage: - * - *

-	 * PlainHeader header = new PlainHeader.Builder().
-	 *                      contentType("text/plain").
-	 *                      customParam("exp", new Date().getTime()).
-	 *                      build();
-	 * 
- */ - public static class Builder { - - - /** - * The JOSE object type. - */ - private JOSEObjectType typ; - - - /** - * The content type. - */ - private String cty; - - - /** - * The critical headers. - */ - private Set crit; - - - /** - * Custom header parameters. - */ - private Map customParams; - - - /** - * The parsed Base64URL. - */ - private Base64URL parsedBase64URL; - - - /** - * Creates a new unsecured (plain) header builder. - */ - public Builder() { - - } - - - /** - * Creates a new unsecured (plain) header builder with the - * parameters from the specified header. - * - * @param plainHeader The unsecured header to use. Must not be - * {@code null}. - */ - public Builder(final PlainHeader plainHeader) { - - typ = plainHeader.getType(); - cty = plainHeader.getContentType(); - crit = plainHeader.getCriticalParams(); - customParams = plainHeader.getCustomParams(); - } - - - /** - * Sets the type ({@code typ}) parameter. - * - * @param typ The type parameter, {@code null} if not - * specified. - * - * @return This builder. - */ - public Builder type(final JOSEObjectType typ) { - - this.typ = typ; - return this; - } - - - /** - * Sets the content type ({@code cty}) parameter. - * - * @param cty The content type parameter, {@code null} if not - * specified. - * - * @return This builder. - */ - public Builder contentType(final String cty) { - - this.cty = cty; - return this; - } - - - /** - * Sets the critical header parameters ({@code crit}) - * parameter. - * - * @param crit The names of the critical header parameters, - * empty set or {@code null} if none. - * - * @return This builder. - */ - public Builder criticalParams(final Set crit) { - - this.crit = crit; - return this; - } - - - /** - * Sets a custom (non-registered) parameter. - * - * @param name The name of the custom parameter. Must not - * match a registered parameter name and must not - * be {@code null}. - * @param value The value of the custom parameter, should map - * to a valid JSON entity, {@code null} if not - * specified. - * - * @return This builder. - * - * @throws IllegalArgumentException If the specified parameter - * name matches a registered - * parameter name. - */ - public Builder customParam(final String name, final Object value) { - - if (getRegisteredParameterNames().contains(name)) { - throw new IllegalArgumentException("The parameter name \"" + name + "\" matches a registered name"); - } - - if (customParams == null) { - customParams = new HashMap<>(); - } - - customParams.put(name, value); - - return this; - } - - - /** - * Sets the custom (non-registered) parameters. The values must - * be serialisable to a JSON entity, otherwise will be ignored. - * - * @param customParameters The custom parameters, empty map or - * {@code null} if none. - * - * @return This builder. - */ - public Builder customParams(final Map customParameters) { - - this.customParams = customParameters; - return this; - } - - - /** - * Sets the parsed Base64URL. - * - * @param base64URL The parsed Base64URL, {@code null} if the - * header is created from scratch. - * - * @return This builder. - */ - public Builder parsedBase64URL(final Base64URL base64URL) { - - this.parsedBase64URL = base64URL; - return this; - } - - - /** - * Builds a new unsecured (plain) header. - * - * @return The unsecured header. - */ - public PlainHeader build() { - - return new PlainHeader(typ, cty, crit, customParams, parsedBase64URL); - } - } - - - /** - * Creates a new minimal unsecured (plain) header with algorithm - * {@link Algorithm#NONE none}. - */ - public PlainHeader() { - - this(null, null, null, null, null); - } - - - /** - * Creates a new unsecured (plain) header with algorithm - * {@link Algorithm#NONE none}. - * - * @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. - */ - public PlainHeader(final JOSEObjectType typ, - final String cty, - final Set crit, - final Map customParams, - final Base64URL parsedBase64URL) { - - super(Algorithm.NONE, typ, cty, crit, customParams, parsedBase64URL); - } - - - /** - * Deep copy constructor. - * - * @param plainHeader The unsecured header to copy. Must not be - * {@code null}. - */ - public PlainHeader(final PlainHeader plainHeader) { - - this( - plainHeader.getType(), - plainHeader.getContentType(), - plainHeader.getCriticalParams(), - plainHeader.getCustomParams(), - plainHeader.getParsedBase64URL() - ); - } - - - /** - * Gets the registered parameter names for unsecured headers. - * - * @return The registered parameter names, as an unmodifiable set. - */ - public static Set getRegisteredParameterNames() { - - return REGISTERED_PARAMETER_NAMES; - } - - - /** - * Gets the algorithm ({@code alg}) parameter. - * - * @return {@link Algorithm#NONE}. - */ - @Override - public Algorithm getAlgorithm() { - - return Algorithm.NONE; - } - - - /** - * Parses an unsecured header from the specified JSON object. - * - * @param jsonObject The JSON object to parse. Must not be {@code null}. - * - * @return The unsecured header. - * - * @throws ParseException If the specified JSON object doesn't - * represent a valid unsecured header. - */ - public static PlainHeader parse(final JSONObject jsonObject) - throws ParseException { - - return parse(jsonObject, null); - } - - - /** - * Parses an unsecured header 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 unsecured header. - * - * @throws ParseException If the specified JSON object doesn't - * represent a valid unsecured header. - */ - public static PlainHeader parse(final JSONObject jsonObject, - final Base64URL parsedBase64URL) - throws ParseException { - - // Get the "alg" parameter - Algorithm alg = Header.parseAlgorithm(jsonObject); - - if (alg != Algorithm.NONE) { - throw new ParseException("The algorithm \"alg\" header parameter must be \"none\"", 0); - } - - PlainHeader.Builder header = new Builder().parsedBase64URL(parsedBase64URL); - - // Parse optional + custom parameters - for(final String name: jsonObject.keySet()) { - - - - if("alg".equals(name)) { - // skip - } else if("typ".equals(name)) { - header = header.type(new JOSEObjectType(JSONObjectUtils.getString(jsonObject, name))); - } else if("cty".equals(name)) { - header = header.contentType(JSONObjectUtils.getString(jsonObject, name)); - } else if("crit".equals(name)) { - header = header.criticalParams(new HashSet<>(JSONObjectUtils.getStringList(jsonObject, name))); - } else { - header = header.customParam(name, jsonObject.get(name)); - } - } - - return header.build(); - } - - - /** - * Parses an unsecured header from the specified JSON string. - * - * @param jsonString The JSON string to parse. Must not be - * {@code null}. - * - * @return The unsecured header. - * - * @throws ParseException If the specified JSON string doesn't - * represent a valid unsecured header. - */ - public static PlainHeader parse(final String jsonString) - throws ParseException { - - return parse(jsonString, null); - } - - - /** - * Parses an unsecured header from the specified JSON string. - * - * @param jsonString The JSON string to parse. Must not be - * {@code null}. - * @param parsedBase64URL The original parsed Base64URL, {@code null} - * if not applicable. - * - * @return The unsecured header. - * - * @throws ParseException If the specified JSON string doesn't - * represent a valid unsecured header. - */ - public static PlainHeader parse(final String jsonString, - final Base64URL parsedBase64URL) - throws ParseException { - - return parse(JSONObjectUtils.parse(jsonString), parsedBase64URL); - } - - - /** - * Parses an unsecured header from the specified Base64URL. - * - * @param base64URL The Base64URL to parse. Must not be {@code null}. - * - * @return The unsecured header. - * - * @throws ParseException If the specified Base64URL doesn't represent - * a valid unsecured header. - */ - public static PlainHeader parse(final Base64URL base64URL) - throws ParseException { - - return parse(base64URL.decodeToString(), base64URL); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/PlainObject.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/PlainObject.java deleted file mode 100644 index 2e5952917..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/PlainObject.java +++ /dev/null @@ -1,176 +0,0 @@ -/* - * 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; - - -/** - * Unsecured (plain / {@code alg=none}) JOSE object. This class is thread-safe. - * - * @author Vladimir Dzhuvinov - * @version 2014-04-08 - */ -@ThreadSafe -public class PlainObject extends JOSEObject { - - - private static final long serialVersionUID = 1L; - - - /** - * The header. - */ - private final PlainHeader header; - - - /** - * Creates a new unsecured JOSE object with a default {@link - * PlainHeader} and the specified payload. - * - * @param payload The payload. Must not be {@code null}. - */ - public PlainObject(final Payload payload) { - - if (payload == null) { - throw new IllegalArgumentException("The payload must not be null"); - } - - setPayload(payload); - - header = new PlainHeader(); - } - - - /** - * Creates a new unsecured JOSE object with the specified header and - * payload. - * - * @param header The unsecured header. Must not be {@code null}. - * @param payload The payload. Must not be {@code null}. - */ - public PlainObject(final PlainHeader header, final Payload payload) { - - if (header == null) { - - throw new IllegalArgumentException("The unsecured header must not be null"); - } - - this.header = header; - - if (payload == null) { - - throw new IllegalArgumentException("The payload must not be null"); - } - - setPayload(payload); - } - - - /** - * Creates a new unsecured JOSE object with the specified - * Base64URL-encoded parts. - * - * @param firstPart The first part, corresponding to the unsecured - * header. Must not be {@code null}. - * @param secondPart The second part, corresponding to the payload. - * Must not be {@code null}. - * - * @throws ParseException If parsing of the serialised parts failed. - */ - public PlainObject(final Base64URL firstPart, final Base64URL secondPart) - throws ParseException { - - if (firstPart == null) { - - throw new IllegalArgumentException("The first part must not be null"); - } - - try { - header = PlainHeader.parse(firstPart); - - } catch (ParseException e) { - - throw new ParseException("Invalid unsecured header: " + e.getMessage(), 0); - } - - if (secondPart == null) { - - throw new IllegalArgumentException("The second part must not be null"); - } - - setPayload(new Payload(secondPart)); - - setParsedParts(firstPart, secondPart, null); - } - - - @Override - public PlainHeader getHeader() { - - return header; - } - - - /** - * Serialises this unsecured JOSE object to its compact format - * consisting of Base64URL-encoded parts delimited by period ('.') - * characters. - * - *
-	 * [header-base64url].[payload-base64url].[]
-	 * 
- * - * @return The serialised unsecured JOSE object. - */ - @Override - public String serialize() { - - return header.toBase64URL().toString() + '.' + getPayload().toBase64URL().toString() + '.'; - } - - - /** - * Parses an unsecured JOSE object from the specified string in compact - * format. - * - * @param s The string to parse. Must not be {@code null}. - * - * @return The unsecured JOSE object. - * - * @throws ParseException If the string couldn't be parsed to a valid - * unsecured JOSE object. - */ - public static PlainObject parse(final String s) - throws ParseException { - - Base64URL[] parts = JOSEObject.split(s); - - if (! parts[2].toString().isEmpty()) { - - throw new ParseException("Unexpected third Base64URL part", 0); - } - - return new PlainObject(parts[0], parts[1]); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/RemoteKeySourceException.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/RemoteKeySourceException.java deleted file mode 100644 index 5fac88fb2..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/RemoteKeySourceException.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * 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; - - -/** - * Remote key source exception. - * - * @author Vladimir Dzhuvinov - * @version 2016-06-21 - */ -public class RemoteKeySourceException extends KeySourceException { - - - /** - * Creates a new remote key source exception. - * - * @param message The message. - * @param cause The cause. - */ - public RemoteKeySourceException(final String message, final Throwable cause) { - super(message, cause); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/Requirement.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/Requirement.java deleted file mode 100644 index 20ff384b2..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/Requirement.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * 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; - - -/** - * Enumeration of JOSE algorithm implementation requirements. Refers to the - * requirement levels defined in RFC 2119. - * - * @author Vladimir Dzhuvinov - * @version 2012-09-17 - */ -public enum Requirement { - - - /** - * The implementation of the algorithm is required. - */ - REQUIRED, - - - /** - * The implementation of the algorithm is recommended. - */ - RECOMMENDED, - - - /** - * The implementation of the algorithm is optional. - */ - OPTIONAL -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/AESDecrypter.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/AESDecrypter.java deleted file mode 100644 index dc853d3cc..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/AESDecrypter.java +++ /dev/null @@ -1,230 +0,0 @@ -/* - * 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.crypto; - - -import java.util.Set; - -import javax.crypto.SecretKey; -import javax.crypto.spec.SecretKeySpec; - -import com.nimbusds.jose.crypto.impl.*; -import net.jcip.annotations.ThreadSafe; - -import com.nimbusds.jose.*; -import com.nimbusds.jose.jwk.OctetSequenceKey; -import com.nimbusds.jose.util.Base64URL; - - -/** - * AES and AES GCM key wrap decrypter of {@link com.nimbusds.jose.JWEObject JWE - * objects}. Expects an AES key. - * - *

Unwraps the encrypted Content Encryption Key (CEK) with the specified AES - * key, and then uses the CEK along with the IV and authentication tag to - * decrypt the cipher text. See RFC 7518, sections - * 4.4 and - * 4.7 for more - * information. - * - *

This class is thread-safe. - * - *

Supports the following key management algorithms: - * - *

    - *
  • {@link com.nimbusds.jose.JWEAlgorithm#A128KW} - *
  • {@link com.nimbusds.jose.JWEAlgorithm#A192KW} - *
  • {@link com.nimbusds.jose.JWEAlgorithm#A256KW} - *
  • {@link com.nimbusds.jose.JWEAlgorithm#A128GCMKW} - *
  • {@link com.nimbusds.jose.JWEAlgorithm#A192GCMKW} - *
  • {@link com.nimbusds.jose.JWEAlgorithm#A256GCMKW} - *
- * - *

Supports the following content encryption algorithms: - * - *

    - *
  • {@link com.nimbusds.jose.EncryptionMethod#A128CBC_HS256} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A192CBC_HS384} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A256CBC_HS512} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A128GCM} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A192GCM} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A256GCM} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A128CBC_HS256_DEPRECATED} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A256CBC_HS512_DEPRECATED} - *
- * - * @author Melisa Halsband - * @author Vladimir Dzhuvinov - * @version 2015-06-29 - */ -@ThreadSafe -public class AESDecrypter extends AESCryptoProvider implements JWEDecrypter, CriticalHeaderParamsAware { - - - /** - * The critical header policy. - */ - private final CriticalHeaderParamsDeferral critPolicy = new CriticalHeaderParamsDeferral(); - - - /** - * Creates a new AES decrypter. - * - * @param kek The Key Encrypting Key. Must be 128 bits (16 bytes), 192 - * bits (24 bytes) or 256 bits (32 bytes). Must not be - * {@code null}. - * - * @throws KeyLengthException If the KEK length is invalid. - */ - public AESDecrypter(final SecretKey kek) - throws KeyLengthException { - - this(kek, null); - } - - - /** - * Creates a new AES decrypter. - * - * @param keyBytes The Key Encrypting Key, as a byte array. Must be 128 - * bits (16 bytes), 192 bits (24 bytes) or 256 bits (32 - * bytes). Must not be {@code null}. - * - * @throws KeyLengthException If the KEK length is invalid. - */ - public AESDecrypter(final byte[] keyBytes) - throws KeyLengthException { - - this(new SecretKeySpec(keyBytes, "AES")); - } - - - /** - * Creates a new AES decrypter. - * - * @param octJWK The Key Encryption Key, as a JWK. Must be 128 bits (16 - * bytes), 192 bits (24 bytes), 256 bits (32 bytes), 384 - * bits (48 bytes) or 512 bits (64 bytes) long. Must not - * be {@code null}. - * - * @throws KeyLengthException If the KEK length is invalid. - */ - public AESDecrypter(final OctetSequenceKey octJWK) - throws KeyLengthException { - - this(octJWK.toSecretKey("AES")); - } - - - /** - * Creates a new AES decrypter. - * - * @param kek The Key Encrypting Key. Must be 128 bits (16 - * bytes), 192 bits (24 bytes) or 256 bits (32 - * bytes). Must not be {@code null}. - * @param defCritHeaders The names of the critical header parameters - * that are deferred to the application for - * processing, empty set or {@code null} if none. - * - * @throws KeyLengthException If the KEK length is invalid. - */ - public AESDecrypter(final SecretKey kek, final Set defCritHeaders) - throws KeyLengthException { - - super(kek); - - critPolicy.setDeferredCriticalHeaderParams(defCritHeaders); - } - - - @Override - public Set getProcessedCriticalHeaderParams() { - - return critPolicy.getProcessedCriticalHeaderParams(); - } - - - @Override - public Set getDeferredCriticalHeaderParams() { - - return critPolicy.getProcessedCriticalHeaderParams(); - } - - - @Override - public byte[] decrypt(final JWEHeader header, - final Base64URL encryptedKey, - final Base64URL iv, - final Base64URL cipherText, - final Base64URL authTag) - throws JOSEException { - - // Validate required JWE parts - if (encryptedKey == null) { - throw new JOSEException("Missing JWE encrypted key"); - } - - if (iv == null) { - throw new JOSEException("Missing JWE initialization vector (IV)"); - } - - if (authTag == null) { - throw new JOSEException("Missing JWE authentication tag"); - } - - critPolicy.ensureHeaderPasses(header); - - // Derive the content encryption key - JWEAlgorithm alg = header.getAlgorithm(); - int keyLength = header.getEncryptionMethod().cekBitLength(); - - final SecretKey cek; - - if (alg.equals(JWEAlgorithm.A128KW) || - alg.equals(JWEAlgorithm.A192KW) || - alg.equals(JWEAlgorithm.A256KW)) { - - cek = AESKW.unwrapCEK(getKey(), encryptedKey.decode(), getJCAContext().getKeyEncryptionProvider()); - - } else if (alg.equals(JWEAlgorithm.A128GCMKW) || - alg.equals(JWEAlgorithm.A192GCMKW) || - alg.equals(JWEAlgorithm.A256GCMKW)) { - - if (header.getIV() == null) { - throw new JOSEException("Missing JWE \"iv\" header parameter"); - } - - byte[] keyIV = header.getIV().decode(); - - if (header.getAuthTag() == null) { - throw new JOSEException("Missing JWE \"tag\" header parameter"); - } - - byte[] keyTag = header.getAuthTag().decode(); - - AuthenticatedCipherText authEncrCEK = new AuthenticatedCipherText(encryptedKey.decode(), keyTag); - cek = AESGCMKW.decryptCEK(getKey(), keyIV, authEncrCEK, keyLength, getJCAContext().getKeyEncryptionProvider()); - - } else { - - throw new JOSEException(AlgorithmSupportMessage.unsupportedJWEAlgorithm(alg, SUPPORTED_ALGORITHMS)); - } - - return ContentCryptoProvider.decrypt(header, encryptedKey, iv, cipherText, authTag, cek, getJCAContext()); - } -} \ No newline at end of file diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/AESEncrypter.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/AESEncrypter.java deleted file mode 100644 index ded923a8d..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/AESEncrypter.java +++ /dev/null @@ -1,224 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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.crypto; - - -import javax.crypto.SecretKey; -import javax.crypto.spec.SecretKeySpec; - -import com.nimbusds.jose.*; -import com.nimbusds.jose.crypto.impl.*; -import com.nimbusds.jose.jwk.OctetSequenceKey; -import com.nimbusds.jose.util.Base64URL; -import com.nimbusds.jose.util.ByteUtils; -import com.nimbusds.jose.util.Container; -import net.jcip.annotations.ThreadSafe; - - -/** - * AES and AES GCM key wrap encrypter of {@link com.nimbusds.jose.JWEObject JWE - * objects}. Expects an AES key. - * - *

Encrypts the plain text with a generated AES key (the Content Encryption - * Key) according to the specified JOSE encryption method, then wraps the CEK - * with the specified AES key and returns it alongside the IV, cipher text and - * authentication tag. See RFC 7518, sections - * 4.4 and - * 4.7 for more - * information. - * - *

This class is thread-safe. - * - *

Supports the following key management algorithms: - * - *

    - *
  • {@link com.nimbusds.jose.JWEAlgorithm#A128KW} - *
  • {@link com.nimbusds.jose.JWEAlgorithm#A192KW} - *
  • {@link com.nimbusds.jose.JWEAlgorithm#A256KW} - *
  • {@link com.nimbusds.jose.JWEAlgorithm#A128GCMKW} - *
  • {@link com.nimbusds.jose.JWEAlgorithm#A192GCMKW} - *
  • {@link com.nimbusds.jose.JWEAlgorithm#A256GCMKW} - *
- * - *

Supports the following content encryption algorithms: - * - *

    - *
  • {@link com.nimbusds.jose.EncryptionMethod#A128CBC_HS256} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A192CBC_HS384} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A256CBC_HS512} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A128GCM} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A192GCM} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A256GCM} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A128CBC_HS256_DEPRECATED} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A256CBC_HS512_DEPRECATED} - *
- * - * @author Melisa Halsband - * @author Vladimir Dzhuvinov - * @author Dimitar A. Stoikov - * @version 2017-06-01 - */ -@ThreadSafe -public class AESEncrypter extends AESCryptoProvider implements JWEEncrypter { - - - /** - * Algorithm family constants. - */ - private enum AlgFamily { - - AESKW, AESGCMKW - } - - - /** - * Creates a new AES encrypter. - * - * @param kek The Key Encryption Key. Must be 128 bits (16 bytes), 192 - * bits (24 bytes) or 256 bits (32 bytes). Must not be - * {@code null}. - * - * @throws KeyLengthException If the KEK length is invalid. - */ - public AESEncrypter(final SecretKey kek) - throws KeyLengthException { - - super(kek); - } - - /** - * Creates a new AES encrypter. - * - * @param keyBytes The Key Encryption Key, as a byte array. Must be 128 - * bits (16 bytes), 192 bits (24 bytes) or 256 bits (32 - * bytes). Must not be {@code null}. - * - * @throws KeyLengthException If the KEK length is invalid. - */ - public AESEncrypter(final byte[] keyBytes) - throws KeyLengthException { - - this(new SecretKeySpec(keyBytes, "AES")); - } - - - /** - * Creates a new AES encrypter. - * - * @param octJWK The Key Encryption Key, as a JWK. Must be 128 bits (16 - * bytes), 192 bits (24 bytes), 256 bits (32 bytes), 384 - * bits (48 bytes) or 512 bits (64 bytes) long. Must not - * be {@code null}. - * - * @throws KeyLengthException If the KEK length is invalid. - */ - public AESEncrypter(final OctetSequenceKey octJWK) - throws KeyLengthException { - - this(octJWK.toSecretKey("AES")); - } - - - @Override - public JWECryptoParts encrypt(final JWEHeader header, final byte[] clearText) - throws JOSEException { - - final JWEAlgorithm alg = header.getAlgorithm(); - - // Check the AES key size and determine the algorithm family - final AlgFamily algFamily; - - if (alg.equals(JWEAlgorithm.A128KW)) { - - if(ByteUtils.safeBitLength(getKey().getEncoded()) != 128){ - throw new KeyLengthException("The Key Encryption Key (KEK) length must be 128 bits for A128KW encryption"); - } - algFamily = AlgFamily.AESKW; - - } else if (alg.equals(JWEAlgorithm.A192KW)) { - - if(ByteUtils.safeBitLength(getKey().getEncoded()) != 192){ - throw new KeyLengthException("The Key Encryption Key (KEK) length must be 192 bits for A192KW encryption"); - } - algFamily = AlgFamily.AESKW; - - } else if (alg.equals(JWEAlgorithm.A256KW)) { - - if (ByteUtils.safeBitLength(getKey().getEncoded()) != 256) { - throw new KeyLengthException("The Key Encryption Key (KEK) length must be 256 bits for A256KW encryption"); - } - algFamily = AlgFamily.AESKW; - - } else if (alg.equals(JWEAlgorithm.A128GCMKW)) { - - if(ByteUtils.safeBitLength(getKey().getEncoded()) != 128){ - throw new KeyLengthException("The Key Encryption Key (KEK) length must be 128 bits for A128GCMKW encryption"); - } - algFamily = AlgFamily.AESGCMKW; - - } else if (alg.equals(JWEAlgorithm.A192GCMKW)) { - - if(ByteUtils.safeBitLength(getKey().getEncoded()) != 192){ - throw new KeyLengthException("The Key Encryption Key (KEK) length must be 192 bits for A192GCMKW encryption"); - } - algFamily = AlgFamily.AESGCMKW; - - } else if (alg.equals(JWEAlgorithm.A256GCMKW)) { - - if(ByteUtils.safeBitLength(getKey().getEncoded()) != 256){ - throw new KeyLengthException("The Key Encryption Key (KEK) length must be 256 bits for A256GCMKW encryption"); - } - algFamily = AlgFamily.AESGCMKW; - - } else { - - throw new JOSEException(AlgorithmSupportMessage.unsupportedJWEAlgorithm(alg, SUPPORTED_ALGORITHMS)); - } - - - final JWEHeader updatedHeader; // We need to work on the header - final Base64URL encryptedKey; // The second JWE part - - // Generate and encrypt the CEK according to the enc method - final EncryptionMethod enc = header.getEncryptionMethod(); - final SecretKey cek = ContentCryptoProvider.generateCEK(enc, getJCAContext().getSecureRandom()); - - if(AlgFamily.AESKW.equals(algFamily)) { - - encryptedKey = Base64URL.encode(AESKW.wrapCEK(cek, getKey(), getJCAContext().getKeyEncryptionProvider())); - updatedHeader = header; // simply copy ref - - } else if(AlgFamily.AESGCMKW.equals(algFamily)) { - - final Container keyIV = new Container<>(AESGCM.generateIV(getJCAContext().getSecureRandom())); - final AuthenticatedCipherText authCiphCEK = AESGCMKW.encryptCEK(cek, keyIV, getKey(), getJCAContext().getKeyEncryptionProvider()); - encryptedKey = Base64URL.encode(authCiphCEK.getCipherText()); - - // Add iv and tag to the header - updatedHeader = new JWEHeader.Builder(header). - iv(Base64URL.encode(keyIV.get())). - authTag(Base64URL.encode(authCiphCEK.getAuthenticationTag())). - build(); - } else { - // This should never happen - throw new JOSEException("Unexpected JWE algorithm: " + alg); - } - - return ContentCryptoProvider.encrypt(updatedHeader, clearText, cek, encryptedKey, getJCAContext()); - } -} \ No newline at end of file diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/DirectDecrypter.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/DirectDecrypter.java deleted file mode 100644 index d453f4a6d..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/DirectDecrypter.java +++ /dev/null @@ -1,273 +0,0 @@ -/* - * 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.crypto; - - -import java.util.Set; -import javax.crypto.SecretKey; -import javax.crypto.spec.SecretKeySpec; - -import com.nimbusds.jose.*; -import com.nimbusds.jose.crypto.impl.AlgorithmSupportMessage; -import com.nimbusds.jose.crypto.impl.ContentCryptoProvider; -import com.nimbusds.jose.crypto.impl.CriticalHeaderParamsDeferral; -import com.nimbusds.jose.crypto.impl.DirectCryptoProvider; -import com.nimbusds.jose.jwk.OctetSequenceKey; -import com.nimbusds.jose.util.Base64URL; -import net.jcip.annotations.ThreadSafe; - - -/** - * Direct decrypter of {@link com.nimbusds.jose.JWEObject JWE objects} with a - * shared symmetric key. - * - *

See RFC 7518 - * section 4.5 - * for more information.

- * - *

This class is thread-safe. - * - *

Supports the following key management algorithms: - * - *

    - *
  • {@link com.nimbusds.jose.JWEAlgorithm#DIR} - *
- * - *

Supports the following content encryption algorithms: - * - *

    - *
  • {@link com.nimbusds.jose.EncryptionMethod#A128CBC_HS256} (requires 256 bit key) - *
  • {@link com.nimbusds.jose.EncryptionMethod#A192CBC_HS384} (requires 384 bit key) - *
  • {@link com.nimbusds.jose.EncryptionMethod#A256CBC_HS512} (requires 512 bit key) - *
  • {@link com.nimbusds.jose.EncryptionMethod#A128GCM} (requires 128 bit key) - *
  • {@link com.nimbusds.jose.EncryptionMethod#A192GCM} (requires 192 bit key) - *
  • {@link com.nimbusds.jose.EncryptionMethod#A256GCM} (requires 256 bit key) - *
  • {@link com.nimbusds.jose.EncryptionMethod#A128CBC_HS256_DEPRECATED} (requires 256 bit key) - *
  • {@link com.nimbusds.jose.EncryptionMethod#A256CBC_HS512_DEPRECATED} (requires 512 bit key) - *
- * - *

Also supports a promiscuous mode to decrypt any JWE by passing the - * content encryption key (CEK) directly. The that mode the JWE algorithm - * checks for ("alg":"dir") and encrypted key not being present will be - * skipped. - * - * @author Vladimir Dzhuvinov - * @version 2018-07-16 - */ -@ThreadSafe -public class DirectDecrypter extends DirectCryptoProvider implements JWEDecrypter, CriticalHeaderParamsAware { - - - /** - * If set skips the checks for alg "dir" and encrypted key not present. - */ - private final boolean promiscuousMode; - - - /** - * The critical header policy. - */ - private final CriticalHeaderParamsDeferral critPolicy = new CriticalHeaderParamsDeferral(); - - - /** - * Creates a new direct decrypter. - * - * @param key The symmetric key. Its algorithm should be "AES". Must be - * 128 bits (16 bytes), 192 bits (24 bytes), 256 bits (32 - * bytes), 384 bits (48 bytes) or 512 bits (64 bytes) long. - * Must not be {@code null}. - * - * @throws KeyLengthException If the symmetric key length is not - * compatible. - */ - public DirectDecrypter(final SecretKey key) - throws KeyLengthException { - - this(key, false); - } - - - /** - * Creates a new direct decrypter with the option to set it in - * promiscuous mode. - * - * @param key The symmetric key. Its algorithm should be - * "AES". Must be 128 bits (16 bytes), 192 bits - * (24 bytes), 256 bits (32 bytes), 384 bits (48 - * bytes) or 512 bits (64 bytes) long. Must not - * be {@code null}. - * @param promiscuousMode If {@code true} set the decrypter in - * promiscuous mode to permit decryption of any - * JWE with the supplied symmetric key. The that - * mode the JWE algorithm checks for - * ("alg":"dir") and encrypted key not being - * present will be skipped. - * - * @throws KeyLengthException If the symmetric key length is not - * compatible. - */ - public DirectDecrypter(final SecretKey key, final boolean promiscuousMode) - throws KeyLengthException { - - super(key); - - this.promiscuousMode = promiscuousMode; - } - - - /** - * Creates a new direct decrypter. - * - * @param keyBytes The symmetric key, as a byte array. Must be 128 bits - * (16 bytes), 192 bits (24 bytes), 256 bits (32 - * bytes), 384 bits (48 bytes) or 512 bits (64 bytes) - * long. Must not be {@code null}. - * - * @throws KeyLengthException If the symmetric key length is not - * compatible. - */ - public DirectDecrypter(final byte[] keyBytes) - throws KeyLengthException { - - this(new SecretKeySpec(keyBytes, "AES"), false); - } - - - /** - * Creates a new direct decrypter. - * - * @param octJWK The symmetric key, as a JWK. Must be 128 bits (16 - * bytes), 192 bits (24 bytes), 256 bits (32 bytes), 384 - * bits (48 bytes) or 512 bits (64 bytes) long. Must not - * be {@code null}. - * - * @throws KeyLengthException If the symmetric key length is not - * compatible. - */ - public DirectDecrypter(final OctetSequenceKey octJWK) - throws KeyLengthException { - - this(octJWK.toSecretKey("AES")); - } - - - /** - * Creates a new direct decrypter with the option to set it in - * promiscuous mode. - * - * @param key The symmetric key. Its algorithm should be - * "AES". Must be 128 bits (16 bytes), 192 bits - * (24 bytes), 256 bits (32 bytes), 384 bits (48 - * bytes) or 512 bits (64 bytes) long. Must not - * be {@code null}. - * @param defCritHeaders The names of the critical header parameters - * that are deferred to the application for - * processing, empty set or {@code null} if none. - * - * @throws KeyLengthException If the symmetric key length is not - * compatible. - */ - public DirectDecrypter(final SecretKey key, final Set defCritHeaders) - throws KeyLengthException { - - this(key, defCritHeaders, false); - } - - - /** - * Creates a new direct decrypter. - * - * @param key The symmetric key. Its algorithm should be - * "AES". Must be 128 bits (16 bytes), 192 bits - * (24 bytes), 256 bits (32 bytes), 384 bits (48 - * bytes) or 512 bits (64 bytes) long. Must not - * be {@code null}. - * @param defCritHeaders The names of the critical header parameters - * that are deferred to the application for - * processing, empty set or {@code null} if none. - *@param promiscuousMode If {@code true} set the decrypter in - * promiscuous mode to permit decryption of any - * JWE with the supplied symmetric key. The that - * mode the JWE algorithm checks for - * ("alg":"dir") and encrypted key not being - * present will be skipped. - * - * @throws KeyLengthException If the symmetric key length is not - * compatible. - */ - public DirectDecrypter(final SecretKey key, - final Set defCritHeaders, - final boolean promiscuousMode) - throws KeyLengthException { - - super(key); - critPolicy.setDeferredCriticalHeaderParams(defCritHeaders); - this.promiscuousMode = promiscuousMode; - } - - - @Override - public Set getProcessedCriticalHeaderParams() { - - return critPolicy.getProcessedCriticalHeaderParams(); - } - - - @Override - public Set getDeferredCriticalHeaderParams() { - - return critPolicy.getProcessedCriticalHeaderParams(); - } - - - @Override - public byte[] decrypt(final JWEHeader header, - final Base64URL encryptedKey, - final Base64URL iv, - final Base64URL cipherText, - final Base64URL authTag) - throws JOSEException { - - // Validate required JWE parts - if (! promiscuousMode) { - - JWEAlgorithm alg = header.getAlgorithm(); - - if (!alg.equals(JWEAlgorithm.DIR)) { - throw new JOSEException(AlgorithmSupportMessage.unsupportedJWEAlgorithm(alg, SUPPORTED_ALGORITHMS)); - } - - if (encryptedKey != null) { - throw new JOSEException("Unexpected present JWE encrypted key"); - } - } - - if (iv == null) { - throw new JOSEException("Unexpected present JWE initialization vector (IV)"); - } - - if (authTag == null) { - throw new JOSEException("Missing JWE authentication tag"); - } - - critPolicy.ensureHeaderPasses(header); - - return ContentCryptoProvider.decrypt(header, null, iv, cipherText, authTag, getKey(), getJCAContext()); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/DirectEncrypter.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/DirectEncrypter.java deleted file mode 100644 index cbaf63277..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/DirectEncrypter.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * 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.crypto; - - -import javax.crypto.SecretKey; -import javax.crypto.spec.SecretKeySpec; - -import com.nimbusds.jose.crypto.impl.AlgorithmSupportMessage; -import com.nimbusds.jose.crypto.impl.ContentCryptoProvider; -import com.nimbusds.jose.crypto.impl.DirectCryptoProvider; -import net.jcip.annotations.ThreadSafe; - -import com.nimbusds.jose.*; -import com.nimbusds.jose.jwk.OctetSequenceKey; -import com.nimbusds.jose.util.Base64URL; -import com.nimbusds.jose.util.ByteUtils; - - -/** - * Direct encrypter of {@link com.nimbusds.jose.JWEObject JWE objects} with a - * shared symmetric key. - * - *

See RFC 7518 - * section 4.5 - * for more information.

- * - *

This class is thread-safe. - * - *

Supports the following key management algorithms: - * - *

    - *
  • {@link com.nimbusds.jose.JWEAlgorithm#DIR} - *
- * - *

Supports the following content encryption algorithms: - * - *

    - *
  • {@link com.nimbusds.jose.EncryptionMethod#A128CBC_HS256} (requires 256 bit key) - *
  • {@link com.nimbusds.jose.EncryptionMethod#A192CBC_HS384} (requires 384 bit key) - *
  • {@link com.nimbusds.jose.EncryptionMethod#A256CBC_HS512} (requires 512 bit key) - *
  • {@link com.nimbusds.jose.EncryptionMethod#A128GCM} (requires 128 bit key) - *
  • {@link com.nimbusds.jose.EncryptionMethod#A192GCM} (requires 192 bit key) - *
  • {@link com.nimbusds.jose.EncryptionMethod#A256GCM} (requires 256 bit key) - *
  • {@link com.nimbusds.jose.EncryptionMethod#A128CBC_HS256_DEPRECATED} (requires 256 bit key) - *
  • {@link com.nimbusds.jose.EncryptionMethod#A256CBC_HS512_DEPRECATED} (requires 512 bit key) - *
- * - * @author Vladimir Dzhuvinov - * @version 2017-06-01 - */ -@ThreadSafe -public class DirectEncrypter extends DirectCryptoProvider implements JWEEncrypter { - - - /** - * Creates a new direct encrypter. - * - * @param key The symmetric key. Its algorithm should be "AES". Must be - * 128 bits (16 bytes), 192 bits (24 bytes), 256 bits (32 - * bytes), 384 bits (48 bytes) or 512 bits (64 bytes) long. - * Must not be {@code null}. - * - * @throws KeyLengthException If the symmetric key length is not - * compatible. - */ - public DirectEncrypter(final SecretKey key) - throws KeyLengthException { - - super(key); - } - - - /** - * Creates a new direct encrypter. - * - * @param keyBytes The symmetric key, as a byte array. Must be 128 bits - * (16 bytes), 192 bits (24 bytes), 256 bits (32 - * bytes), 384 bits (48 bytes) or 512 bits (64 bytes) - * long. Must not be {@code null}. - * - * @throws KeyLengthException If the symmetric key length is not - * compatible. - */ - public DirectEncrypter(final byte[] keyBytes) - throws KeyLengthException { - - this(new SecretKeySpec(keyBytes, "AES")); - } - - - /** - * Creates a new direct encrypter. - * - * @param octJWK The symmetric key, as a JWK. Must be 128 bits (16 - * bytes), 192 bits (24 bytes), 256 bits (32 bytes), 384 - * bits (48 bytes) or 512 bits (64 bytes) long. Must not - * be {@code null}. - * - * @throws KeyLengthException If the symmetric key length is not - * compatible. - */ - public DirectEncrypter(final OctetSequenceKey octJWK) - throws KeyLengthException { - - this(octJWK.toSecretKey("AES")); - } - - - @Override - public JWECryptoParts encrypt(final JWEHeader header, final byte[] clearText) - throws JOSEException { - - JWEAlgorithm alg = header.getAlgorithm(); - - if (! alg.equals(JWEAlgorithm.DIR)) { - throw new JOSEException(AlgorithmSupportMessage.unsupportedJWEAlgorithm(alg, SUPPORTED_ALGORITHMS)); - } - - // Check key length matches encryption method - EncryptionMethod enc = header.getEncryptionMethod(); - - if (enc.cekBitLength() != ByteUtils.safeBitLength(getKey().getEncoded())) { - throw new KeyLengthException(enc.cekBitLength(), enc); - } - - final Base64URL encryptedKey = null; // The second JWE part - - return ContentCryptoProvider.encrypt(header, clearText, getKey(), encryptedKey, getJCAContext()); - } -} \ No newline at end of file diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/ECDHDecrypter.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/ECDHDecrypter.java deleted file mode 100644 index dcc493f99..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/ECDHDecrypter.java +++ /dev/null @@ -1,271 +0,0 @@ -/* - * 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.crypto; - - -import java.security.PrivateKey; -import java.security.interfaces.ECPrivateKey; -import java.security.interfaces.ECPublicKey; -import java.util.Collections; -import java.util.LinkedHashSet; -import java.util.Set; -import javax.crypto.SecretKey; - -import com.nimbusds.jose.CriticalHeaderParamsAware; -import com.nimbusds.jose.JOSEException; -import com.nimbusds.jose.JWEDecrypter; -import com.nimbusds.jose.JWEHeader; -import com.nimbusds.jose.crypto.impl.CriticalHeaderParamsDeferral; -import com.nimbusds.jose.crypto.impl.ECDH; -import com.nimbusds.jose.crypto.impl.ECDHCryptoProvider; -import com.nimbusds.jose.crypto.utils.ECChecks; -import com.nimbusds.jose.jwk.Curve; -import com.nimbusds.jose.jwk.ECKey; -import com.nimbusds.jose.util.Base64URL; - - -/** - * Elliptic Curve Diffie-Hellman decrypter of - * {@link com.nimbusds.jose.JWEObject JWE objects} for curves using EC JWK - * keys. Expects a private EC key (with a P-256, P-384 or P-521 curve). - * - *

See RFC 7518 - * section 4.6 - * for more information. - * - *

For Curve25519/X25519, see {@link X25519Decrypter} instead. - * - *

This class is thread-safe. - * - *

Supports the following key management algorithms: - * - *

    - *
  • {@link com.nimbusds.jose.JWEAlgorithm#ECDH_ES} - *
  • {@link com.nimbusds.jose.JWEAlgorithm#ECDH_ES_A128KW} - *
  • {@link com.nimbusds.jose.JWEAlgorithm#ECDH_ES_A192KW} - *
  • {@link com.nimbusds.jose.JWEAlgorithm#ECDH_ES_A256KW} - *
- * - *

Supports the following elliptic curves: - * - *

    - *
  • {@link com.nimbusds.jose.jwk.Curve#P_256} - *
  • {@link com.nimbusds.jose.jwk.Curve#P_384} - *
  • {@link com.nimbusds.jose.jwk.Curve#P_521} - *
- * - *

Supports the following content encryption algorithms: - * - *

    - *
  • {@link com.nimbusds.jose.EncryptionMethod#A128CBC_HS256} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A192CBC_HS384} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A256CBC_HS512} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A128GCM} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A192GCM} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A256GCM} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A128CBC_HS256_DEPRECATED} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A256CBC_HS512_DEPRECATED} - *
- * - * @author Vladimir Dzhuvinov - * @version 2018-12-12 - */ -public class ECDHDecrypter extends ECDHCryptoProvider implements JWEDecrypter, CriticalHeaderParamsAware { - - - /** - * The supported EC JWK curves by the ECDH crypto provider class. - */ - public static final Set SUPPORTED_ELLIPTIC_CURVES; - - - static { - Set curves = new LinkedHashSet<>(); - curves.add(Curve.P_256); - curves.add(Curve.P_384); - curves.add(Curve.P_521); - SUPPORTED_ELLIPTIC_CURVES = Collections.unmodifiableSet(curves); - } - - - /** - * The private EC key. - */ - private final PrivateKey privateKey; - - - /** - * The critical header policy. - */ - private final CriticalHeaderParamsDeferral critPolicy = new CriticalHeaderParamsDeferral(); - - - /** - * Creates a new Elliptic Curve Diffie-Hellman decrypter. - * - * @param privateKey The private EC key. Must not be {@code null}. - * - * @throws JOSEException If the elliptic curve is not supported. - */ - public ECDHDecrypter(final ECPrivateKey privateKey) - throws JOSEException { - - this(privateKey, null); - } - - - /** - * Creates a new Elliptic Curve Diffie-Hellman decrypter. - * - * @param ecJWK The EC JSON Web Key (JWK). Must contain a private - * part. Must not be {@code null}. - * - * @throws JOSEException If the elliptic curve is not supported. - */ - public ECDHDecrypter(final ECKey ecJWK) - throws JOSEException { - - super(ecJWK.getCurve()); - - if (! ecJWK.isPrivate()) { - throw new JOSEException("The EC JWK doesn't contain a private part"); - } - - this.privateKey = ecJWK.toECPrivateKey(); - } - - - /** - * Creates a new Elliptic Curve Diffie-Hellman decrypter. - * - * @param privateKey The private EC key. Must not be {@code null}. - * @param defCritHeaders The names of the critical header parameters - * that are deferred to the application for - * processing, empty set or {@code null} if none. - * - * @throws JOSEException If the elliptic curve is not supported. - */ - public ECDHDecrypter(final ECPrivateKey privateKey, final Set defCritHeaders) - throws JOSEException { - - this(privateKey, defCritHeaders, Curve.forECParameterSpec(privateKey.getParams())); - } - - - /** - * Creates a new Elliptic Curve Diffie-Hellman decrypter. This - * constructor can also accept a private EC key located in a PKCS#11 - * store that doesn't expose the private key parameters (such as a - * smart card or HSM). - * - * @param privateKey The private EC key. Must not be {@code null}. - * @param defCritHeaders The names of the critical header parameters - * that are deferred to the application for - * processing, empty set or {@code null} if none. - * @param curve The key curve. Must not be {@code null}. - * - * @throws JOSEException If the elliptic curve is not supported. - */ - public ECDHDecrypter(final PrivateKey privateKey, - final Set defCritHeaders, - final Curve curve) - throws JOSEException { - - super(curve); - - critPolicy.setDeferredCriticalHeaderParams(defCritHeaders); - - this.privateKey = privateKey; - } - - - /** - * Returns the private EC key. - * - * @return The private EC key. Casting to - * {@link java.security.interfaces.ECPrivateKey} may not be - * possible if the key is located in a PKCS#11 store that - * doesn't expose the private key parameters. - */ - public PrivateKey getPrivateKey() { - - return privateKey; - } - - - @Override - public Set supportedEllipticCurves() { - - return SUPPORTED_ELLIPTIC_CURVES; - } - - - @Override - public Set getProcessedCriticalHeaderParams() { - - return critPolicy.getProcessedCriticalHeaderParams(); - } - - - @Override - public Set getDeferredCriticalHeaderParams() { - - return critPolicy.getProcessedCriticalHeaderParams(); - } - - - @Override - public byte[] decrypt(final JWEHeader header, - final Base64URL encryptedKey, - final Base64URL iv, - final Base64URL cipherText, - final Base64URL authTag) - throws JOSEException { - - critPolicy.ensureHeaderPasses(header); - - // Get ephemeral EC key - ECKey ephemeralKey = (ECKey) header.getEphemeralPublicKey(); - - if (ephemeralKey == null) { - throw new JOSEException("Missing ephemeral public EC key \"epk\" JWE header parameter"); - } - - ECPublicKey ephemeralPublicKey = ephemeralKey.toECPublicKey(); - - // Curve check - if (getPrivateKey() instanceof ECPrivateKey) { - ECPrivateKey ecPrivateKey = (ECPrivateKey)getPrivateKey(); - if (!ECChecks.isPointOnCurve(ephemeralPublicKey, ecPrivateKey)) { - throw new JOSEException("Invalid ephemeral public EC key: Point(s) not on the expected curve"); - } - } else { - if (!ECChecks.isPointOnCurve(ephemeralPublicKey, getCurve().toECParameterSpec())) { - throw new JOSEException("Invalid ephemeral public EC key: Point(s) not on the expected curve"); - } - } - - // Derive 'Z' - SecretKey Z = ECDH.deriveSharedSecret( - ephemeralPublicKey, - privateKey, - getJCAContext().getKeyEncryptionProvider()); - - return decryptWithZ(header, Z, encryptedKey, iv, cipherText, authTag); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/ECDHEncrypter.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/ECDHEncrypter.java deleted file mode 100644 index c3279e6f1..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/ECDHEncrypter.java +++ /dev/null @@ -1,259 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2019, 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.crypto; - - -import java.security.InvalidAlgorithmParameterException; -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.NoSuchAlgorithmException; -import java.security.Provider; -import java.security.interfaces.ECPrivateKey; -import java.security.interfaces.ECPublicKey; -import java.security.spec.ECParameterSpec; -import java.util.Collections; -import java.util.LinkedHashSet; -import java.util.Set; - -import javax.crypto.SecretKey; - -import com.nimbusds.jose.JOSEException; -import com.nimbusds.jose.JWECryptoParts; -import com.nimbusds.jose.JWEEncrypter; -import com.nimbusds.jose.JWEHeader; -import com.nimbusds.jose.crypto.impl.ECDH; -import com.nimbusds.jose.crypto.impl.ECDHCryptoProvider; -import com.nimbusds.jose.jwk.Curve; -import com.nimbusds.jose.jwk.ECKey; - -import net.jcip.annotations.ThreadSafe; - - -/** - * Elliptic Curve Diffie-Hellman encrypter of - * {@link com.nimbusds.jose.JWEObject JWE objects} for curves using EC JWK keys. - * Expects a public EC key (with a P-256, P-384 or P-521 curve). - * - *

See RFC 7518 - * section 4.6 - * for more information. - * - *

For Curve25519/X25519, see {@link X25519Encrypter} instead. - * - *

This class is thread-safe. - * - *

Supports the following key management algorithms: - * - *

    - *
  • {@link com.nimbusds.jose.JWEAlgorithm#ECDH_ES} - *
  • {@link com.nimbusds.jose.JWEAlgorithm#ECDH_ES_A128KW} - *
  • {@link com.nimbusds.jose.JWEAlgorithm#ECDH_ES_A192KW} - *
  • {@link com.nimbusds.jose.JWEAlgorithm#ECDH_ES_A256KW} - *
- * - *

Supports the following elliptic curves: - * - *

    - *
  • {@link com.nimbusds.jose.jwk.Curve#P_256} - *
  • {@link com.nimbusds.jose.jwk.Curve#P_384} - *
  • {@link com.nimbusds.jose.jwk.Curve#P_521} - *
- * - *

Supports the following content encryption algorithms: - * - *

    - *
  • {@link com.nimbusds.jose.EncryptionMethod#A128CBC_HS256} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A192CBC_HS384} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A256CBC_HS512} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A128GCM} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A192GCM} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A256GCM} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A128CBC_HS256_DEPRECATED} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A256CBC_HS512_DEPRECATED} - *
- * - * @author Tim McLean - * @author Vladimir Dzhuvinov - * @author Fernando González Callejas - * @version 2019-01-24 - */ -@ThreadSafe -public class ECDHEncrypter extends ECDHCryptoProvider implements JWEEncrypter { - - - /** - * The supported EC JWK curves by the ECDH crypto provider class. - */ - public static final Set SUPPORTED_ELLIPTIC_CURVES; - - - static { - Set curves = new LinkedHashSet<>(); - curves.add(Curve.P_256); - curves.add(Curve.P_384); - curves.add(Curve.P_521); - SUPPORTED_ELLIPTIC_CURVES = Collections.unmodifiableSet(curves); - } - - - /** - * The public EC key. - */ - private final ECPublicKey publicKey; - - /** - * The externally supplied AES content encryption key (CEK) to use, - * {@code null} to generate a CEK for each JWE. - */ - private final SecretKey contentEncryptionKey; - - /** - * Creates a new Elliptic Curve Diffie-Hellman encrypter. - * - * @param publicKey The public EC key. Must not be {@code null}. - * - * @throws JOSEException If the elliptic curve is not supported. - */ - public ECDHEncrypter(final ECPublicKey publicKey) - throws JOSEException { - - this(publicKey, null); - } - - - /** - * Creates a new Elliptic Curve Diffie-Hellman encrypter. - * - * @param ecJWK The EC JSON Web Key (JWK). Must not be {@code null}. - * - * @throws JOSEException If the elliptic curve is not supported. - */ - public ECDHEncrypter(final ECKey ecJWK) throws - JOSEException { - - super(ecJWK.getCurve()); - - publicKey = ecJWK.toECPublicKey(); - contentEncryptionKey = null; - } - - /** - * Creates a new Elliptic Curve Diffie-Hellman encrypter with an - * optionally specified content encryption key (CEK). - * - * @param publicKey The public EC key. Must not be - * {@code null}. - * @param contentEncryptionKey The content encryption key (CEK) to use. - * If specified its algorithm must be "AES" - * and its length must match the expected - * for the JWE encryption method ("enc"). - * If {@code null} a CEK will be generated - * for each JWE. - * @throws JOSEException If the elliptic curve is not supported. - */ - public ECDHEncrypter(final ECPublicKey publicKey, final SecretKey contentEncryptionKey) - throws JOSEException { - - super(Curve.forECParameterSpec(publicKey.getParams())); - - this.publicKey = publicKey; - - if (contentEncryptionKey != null) { - if (contentEncryptionKey.getAlgorithm() == null || !contentEncryptionKey.getAlgorithm().equals("AES")) { - throw new IllegalArgumentException("The algorithm of the content encryption key (CEK) must be AES"); - } else { - this.contentEncryptionKey = contentEncryptionKey; - } - } else { - this.contentEncryptionKey = null; - } - } - - - /** - * Returns the public EC key. - * - * @return The public EC key. - */ - public ECPublicKey getPublicKey() { - - return publicKey; - } - - - @Override - public Set supportedEllipticCurves() { - - return SUPPORTED_ELLIPTIC_CURVES; - } - - - @Override - public JWECryptoParts encrypt(final JWEHeader header, final byte[] clearText) - throws JOSEException { - - // Generate ephemeral EC key pair on the same curve as the consumer's public key - KeyPair ephemeralKeyPair = generateEphemeralKeyPair(publicKey.getParams()); - ECPublicKey ephemeralPublicKey = (ECPublicKey)ephemeralKeyPair.getPublic(); - ECPrivateKey ephemeralPrivateKey = (ECPrivateKey)ephemeralKeyPair.getPrivate(); - - // Add the ephemeral public EC key to the header - JWEHeader updatedHeader = new JWEHeader.Builder(header). - ephemeralPublicKey(new ECKey.Builder(getCurve(), ephemeralPublicKey).build()). - build(); - - // Derive 'Z' - SecretKey Z = ECDH.deriveSharedSecret( - publicKey, - ephemeralPrivateKey, - getJCAContext().getKeyEncryptionProvider()); - - return encryptWithZ(updatedHeader, Z, clearText, contentEncryptionKey); - } - - - /** - * Generates a new ephemeral EC key pair with the specified curve. - * - * @param ecParameterSpec The EC key spec. Must not be {@code null}. - * - * @return The EC key pair. - * - * @throws JOSEException If the EC key pair couldn't be generated. - */ - private KeyPair generateEphemeralKeyPair(final ECParameterSpec ecParameterSpec) - throws JOSEException { - - Provider keProvider = getJCAContext().getKeyEncryptionProvider(); - - try { - KeyPairGenerator generator; - - if (keProvider != null) { - generator = KeyPairGenerator.getInstance("EC", keProvider); - } else { - generator = KeyPairGenerator.getInstance("EC"); - } - - generator.initialize(ecParameterSpec); - return generator.generateKeyPair(); - } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException e) { - throw new JOSEException("Couldn't generate ephemeral EC key pair: " + e.getMessage(), e); - } - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/ECDSASigner.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/ECDSASigner.java deleted file mode 100644 index d42b2d579..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/ECDSASigner.java +++ /dev/null @@ -1,188 +0,0 @@ -/* - * 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.crypto; - - -import java.security.InvalidKeyException; -import java.security.PrivateKey; -import java.security.Signature; -import java.security.SignatureException; -import java.security.interfaces.ECPrivateKey; - -import com.nimbusds.jose.JOSEException; -import com.nimbusds.jose.JWSAlgorithm; -import com.nimbusds.jose.JWSHeader; -import com.nimbusds.jose.JWSSigner; -import com.nimbusds.jose.crypto.impl.AlgorithmSupportMessage; -import com.nimbusds.jose.crypto.impl.ECDSA; -import com.nimbusds.jose.crypto.impl.ECDSAProvider; -import com.nimbusds.jose.jwk.Curve; -import com.nimbusds.jose.jwk.ECKey; -import com.nimbusds.jose.util.Base64URL; -import net.jcip.annotations.ThreadSafe; - - -/** - * Elliptic Curve Digital Signature Algorithm (ECDSA) signer of - * {@link com.nimbusds.jose.JWSObject JWS objects}. Expects a private EC key - * (with a P-256, P-384 or P-521 curve). - * - *

See RFC 7518 - * section 3.4 - * for more information. - * - *

This class is thread-safe. - * - *

Supports the following algorithms: - * - *

    - *
  • {@link com.nimbusds.jose.JWSAlgorithm#ES256} - *
  • {@link com.nimbusds.jose.JWSAlgorithm#ES384} - *
  • {@link com.nimbusds.jose.JWSAlgorithm#ES512} - *
- * - * @author Axel Nennker - * @author Vladimir Dzhuvinov - * @version 2016-11-30 - */ -@ThreadSafe -public class ECDSASigner extends ECDSAProvider implements JWSSigner { - - - /** - * The private EC key. Represented by generic private key interface to - * support key stores that prevent exposure of the private key - * parameters via the {@link java.security.interfaces.RSAPrivateKey} - * API. - * - * See https://bitbucket.org/connect2id/nimbus-jose-jwt/issues/169 - */ - private final PrivateKey privateKey; - - - /** - * Creates a new Elliptic Curve Digital Signature Algorithm (ECDSA) - * signer. - * - * @param privateKey The private EC key. Must not be {@code null}. - * - * @throws JOSEException If the elliptic curve of key is not supported. - */ - public ECDSASigner(final ECPrivateKey privateKey) - throws JOSEException { - - super(ECDSA.resolveAlgorithm(privateKey)); - - this.privateKey = privateKey; - } - - - /** - * Creates a new Elliptic Curve Digital Signature Algorithm (ECDSA) - * signer. This constructor is intended for a private EC key located - * in a PKCS#11 store that doesn't expose the private key parameters - * (such as a smart card or HSM). - * - * @param privateKey The private EC key. Its algorithm must be "EC". - * Must not be {@code null}. - * @param curve The elliptic curve for the key. Must not be - * {@code null}. - * - * @throws JOSEException If the elliptic curve of key is not supported. - */ - public ECDSASigner(final PrivateKey privateKey, final Curve curve) - throws JOSEException { - - super(ECDSA.resolveAlgorithm(curve)); - - if (! "EC".equalsIgnoreCase(privateKey.getAlgorithm())) { - throw new IllegalArgumentException("The private key algorithm must be EC"); - } - - this.privateKey = privateKey; - } - - - /** - * Creates a new Elliptic Curve Digital Signature Algorithm (ECDSA) - * signer. - * - * @param ecJWK The EC JSON Web Key (JWK). Must contain a private part. - * Must not be {@code null}. - * - * @throws JOSEException If the EC JWK doesn't contain a private part, - * its extraction failed, or the elliptic curve - * is not supported. - */ - public ECDSASigner(final ECKey ecJWK) - throws JOSEException { - - super(ECDSA.resolveAlgorithm(ecJWK.getCurve())); - - if (! ecJWK.isPrivate()) { - throw new JOSEException("The EC JWK doesn't contain a private part"); - } - - privateKey = ecJWK.toPrivateKey(); - } - - - /** - * Gets the private EC key. - * - * @return The private EC key. Casting to - * {@link java.security.interfaces.ECPrivateKey} may not be - * possible if the key is located in a PKCS#11 store that - * doesn't expose the private key parameters. - */ - public PrivateKey getPrivateKey() { - - return privateKey; - } - - - @Override - public Base64URL sign(final JWSHeader header, final byte[] signingInput) - throws JOSEException { - - final JWSAlgorithm alg = header.getAlgorithm(); - - if (! supportedJWSAlgorithms().contains(alg)) { - throw new JOSEException(AlgorithmSupportMessage.unsupportedJWSAlgorithm(alg, supportedJWSAlgorithms())); - } - - // DER-encoded signature, according to JCA spec - // (sequence of two integers - R + S) - final byte[] jcaSignature; - - try { - Signature dsa = ECDSA.getSignerAndVerifier(alg, getJCAContext().getProvider()); - dsa.initSign(privateKey, getJCAContext().getSecureRandom()); - dsa.update(signingInput); - jcaSignature = dsa.sign(); - - } catch (InvalidKeyException | SignatureException e) { - - throw new JOSEException(e.getMessage(), e); - } - - final int rsByteArrayLength = ECDSA.getSignatureByteArrayLength(header.getAlgorithm()); - final byte[] jwsSignature = ECDSA.transcodeSignatureToConcat(jcaSignature, rsByteArrayLength); - return Base64URL.encode(jwsSignature); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/ECDSAVerifier.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/ECDSAVerifier.java deleted file mode 100644 index 549788937..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/ECDSAVerifier.java +++ /dev/null @@ -1,201 +0,0 @@ -/* - * 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.crypto; - - -import java.security.InvalidKeyException; -import java.security.Signature; -import java.security.SignatureException; -import java.security.interfaces.ECPublicKey; -import java.util.Set; - -import com.nimbusds.jose.*; -import com.nimbusds.jose.crypto.impl.AlgorithmSupportMessage; -import com.nimbusds.jose.crypto.impl.CriticalHeaderParamsDeferral; -import com.nimbusds.jose.crypto.impl.ECDSA; -import com.nimbusds.jose.crypto.impl.ECDSAProvider; -import com.nimbusds.jose.crypto.utils.ECChecks; -import com.nimbusds.jose.jwk.Curve; -import com.nimbusds.jose.jwk.ECKey; -import com.nimbusds.jose.util.Base64URL; -import net.jcip.annotations.ThreadSafe; - - -/** - * Elliptic Curve Digital Signature Algorithm (ECDSA) verifier of - * {@link com.nimbusds.jose.JWSObject JWS objects}. Expects a public EC key - * (with a P-256, P-384 or P-521 curve). - * - *

See RFC 7518 - * section 3.4 - * for more information. - * - *

This class is thread-safe. - * - *

Supports the following algorithms: - * - *

    - *
  • {@link com.nimbusds.jose.JWSAlgorithm#ES256} - *
  • {@link com.nimbusds.jose.JWSAlgorithm#ES384} - *
  • {@link com.nimbusds.jose.JWSAlgorithm#ES512} - *
- * - * @author Axel Nennker - * @author Vladimir Dzhuvinov - * @version 2017-04-13 - */ -@ThreadSafe -public class ECDSAVerifier extends ECDSAProvider implements JWSVerifier, CriticalHeaderParamsAware { - - - /** - * The critical header policy. - */ - private final CriticalHeaderParamsDeferral critPolicy = new CriticalHeaderParamsDeferral(); - - - /** - * The public EC key. - */ - private final ECPublicKey publicKey; - - - /** - * Creates a new Elliptic Curve Digital Signature Algorithm (ECDSA) - * verifier. - * - * @param publicKey The public EC key. Must not be {@code null}. - * - * @throws JOSEException If the elliptic curve of key is not supported. - */ - public ECDSAVerifier(final ECPublicKey publicKey) - throws JOSEException { - - this(publicKey, null); - } - - - /** - * Creates a new Elliptic Curve Digital Signature Algorithm (ECDSA) - * verifier. - * - * @param ecJWK The EC JSON Web Key (JWK). Must not be {@code null}. - * - * @throws JOSEException If the elliptic curve of key is not supported. - */ - public ECDSAVerifier(final ECKey ecJWK) - throws JOSEException { - - this(ecJWK.toECPublicKey()); - } - - - /** - * Creates a new Elliptic Curve Digital Signature Algorithm (ECDSA) - * verifier. - * - * @param publicKey The public EC key. Must not be {@code null}. - * @param defCritHeaders The names of the critical header parameters - * that are deferred to the application for - * processing, empty set or {@code null} if none. - * - * @throws JOSEException If the elliptic curve of key is not supported. - */ - public ECDSAVerifier(final ECPublicKey publicKey, final Set defCritHeaders) - throws JOSEException { - - super(ECDSA.resolveAlgorithm(publicKey)); - - this.publicKey = publicKey; - - if (! ECChecks.isPointOnCurve( - publicKey, - Curve.forJWSAlgorithm(supportedECDSAAlgorithm()).iterator().next().toECParameterSpec())) { - throw new JOSEException("Curve / public key parameters mismatch"); - } - - critPolicy.setDeferredCriticalHeaderParams(defCritHeaders); - } - - - /** - * Returns the public EC key. - * - * @return The public EC key. - */ - public ECPublicKey getPublicKey() { - - return publicKey; - } - - - @Override - public Set getProcessedCriticalHeaderParams() { - - return critPolicy.getProcessedCriticalHeaderParams(); - } - - - @Override - public Set getDeferredCriticalHeaderParams() { - - return critPolicy.getProcessedCriticalHeaderParams(); - } - - - @Override - public boolean verify(final JWSHeader header, - final byte[] signedContent, - final Base64URL signature) - throws JOSEException { - - final JWSAlgorithm alg = header.getAlgorithm(); - - if (! supportedJWSAlgorithms().contains(alg)) { - throw new JOSEException(AlgorithmSupportMessage.unsupportedJWSAlgorithm(alg, supportedJWSAlgorithms())); - } - - if (! critPolicy.headerPasses(header)) { - return false; - } - - final byte[] jwsSignature = signature.decode(); - - final byte[] derSignature; - - try { - derSignature = ECDSA.transcodeSignatureToDER(jwsSignature); - } catch (JOSEException e) { - // Invalid signature format - return false; - } - - Signature sig = ECDSA.getSignerAndVerifier(alg, getJCAContext().getProvider()); - - try { - sig.initVerify(publicKey); - sig.update(signedContent); - return sig.verify(derSignature); - - } catch (InvalidKeyException e) { - throw new JOSEException("Invalid EC public key: " + e.getMessage(), e); - } catch (SignatureException e) { - return false; - } - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/Ed25519Signer.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/Ed25519Signer.java deleted file mode 100644 index 165c70a10..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/Ed25519Signer.java +++ /dev/null @@ -1,136 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2018, 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.crypto; - - -import java.security.GeneralSecurityException; - -import com.google.crypto.tink.subtle.Ed25519Sign; -import com.nimbusds.jose.JOSEException; -import com.nimbusds.jose.JWSAlgorithm; -import com.nimbusds.jose.JWSHeader; -import com.nimbusds.jose.JWSSigner; -import com.nimbusds.jose.crypto.impl.EdDSAProvider; -import com.nimbusds.jose.jwk.Curve; -import com.nimbusds.jose.jwk.OctetKeyPair; -import com.nimbusds.jose.util.Base64URL; -import net.jcip.annotations.ThreadSafe; - - -/** - * Ed25519 signer of {@link com.nimbusds.jose.JWSObject JWS objects}. - * Expects an {@link OctetKeyPair} with {@code "crv"} Ed25519. - * Uses the Edwards-curve Digital Signature Algorithm (EdDSA). - * - *

See RFC 8037 - * for more information. - * - *

This class is thread-safe. - * - *

Supports the following algorithm: - * - *

    - *
  • {@link com.nimbusds.jose.JWSAlgorithm#EdDSA} - *
- * - *

with the following curve: - * - *

    - *
  • {@link com.nimbusds.jose.jwk.Curve#Ed25519} - *
- * - * @author Tim McLean - * @version 2018-07-11 - */ -@ThreadSafe -public class Ed25519Signer extends EdDSAProvider implements JWSSigner { - - - private final OctetKeyPair privateKey; - - - private final Ed25519Sign tinkSigner; - - - /** - * Creates a new Ed25519 signer. - * - * @param privateKey The private key. Must be non-{@code null}, and must - * be of type Ed25519 ({@code "crv": "Ed25519"}). - * - * @throws JOSEException If the key subtype is not supported or if the key is not a private key - */ - public Ed25519Signer(final OctetKeyPair privateKey) - throws JOSEException { - - super(); - - if (! Curve.Ed25519.equals(privateKey.getCurve())) { - throw new JOSEException("Ed25519Signer only supports OctetKeyPairs with crv=Ed25519"); - } - - if (! privateKey.isPrivate()) { - throw new JOSEException("The OctetKeyPair doesn't contain a private part"); - } - - this.privateKey = privateKey; - - try { - tinkSigner = new Ed25519Sign(privateKey.getDecodedD()); - - } catch (GeneralSecurityException e) { - // If Tink failed to initialize; generally should not happen - throw new JOSEException(e.getMessage(), e); - } - } - - - /** - * Gets the Ed25519 private key as an {@code OctetKeyPair}. - * - * @return The private key. - */ - public OctetKeyPair getPrivateKey() { - - return privateKey; - } - - - @Override - public Base64URL sign(final JWSHeader header, final byte[] signingInput) - throws JOSEException { - - // Check alg field in header - final JWSAlgorithm alg = header.getAlgorithm(); - if (! JWSAlgorithm.EdDSA.equals(alg)) { - throw new JOSEException("Ed25519Signer requires alg=EdDSA in JWSHeader"); - } - - final byte[] jwsSignature; - - try { - jwsSignature = tinkSigner.sign(signingInput); - - } catch (GeneralSecurityException e) { - - throw new JOSEException(e.getMessage(), e); - } - - return Base64URL.encode(jwsSignature); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/Ed25519Verifier.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/Ed25519Verifier.java deleted file mode 100644 index 8fabab9f7..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/Ed25519Verifier.java +++ /dev/null @@ -1,167 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2018, 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.crypto; - - -import java.security.GeneralSecurityException; -import java.util.Set; - -import com.google.crypto.tink.subtle.Ed25519Verify; -import com.nimbusds.jose.*; -import com.nimbusds.jose.crypto.impl.CriticalHeaderParamsDeferral; -import com.nimbusds.jose.crypto.impl.EdDSAProvider; -import com.nimbusds.jose.jwk.Curve; -import com.nimbusds.jose.jwk.OctetKeyPair; -import com.nimbusds.jose.util.Base64URL; -import net.jcip.annotations.ThreadSafe; - - -/** - * Ed25519 verifier of {@link com.nimbusds.jose.JWSObject JWS objects}. - * Expects a public {@link OctetKeyPair} with {@code "crv"} Ed25519. - * Uses the Edwards-curve Digital Signature Algorithm (EdDSA). - * - *

See RFC 8037 - * for more information. - * - *

This class is thread-safe. - * - *

Supports the following algorithm: - * - *

    - *
  • {@link com.nimbusds.jose.JWSAlgorithm#EdDSA} - *
- * - *

with the following curve: - * - *

    - *
  • {@link com.nimbusds.jose.jwk.Curve#Ed25519} - *
- * - * @author Tim McLean - * @version 2018-07-11 - */ -@ThreadSafe -public class Ed25519Verifier extends EdDSAProvider implements JWSVerifier, CriticalHeaderParamsAware { - - - private final CriticalHeaderParamsDeferral critPolicy = new CriticalHeaderParamsDeferral(); - - - private final OctetKeyPair publicKey; - - - private final Ed25519Verify tinkVerifier; - - - /** - * Creates a new Ed25519 verifier. - * - * @param publicKey The public Ed25519 key. Must not be {@code null}. - * - * @throws JOSEException If the key subtype is not supported - */ - public Ed25519Verifier(final OctetKeyPair publicKey) - throws JOSEException { - - this(publicKey, null); - } - - - /** - * Creates a Ed25519 verifier. - * - * @param publicKey The public Ed25519 key. Must not be {@code null}. - * @param defCritHeaders The names of the critical header parameters - * that are deferred to the application for - * processing, empty set or {@code null} if none. - * - * @throws JOSEException If the key subtype is not supported. - */ - public Ed25519Verifier(final OctetKeyPair publicKey, final Set defCritHeaders) - throws JOSEException { - - super(); - - if (! Curve.Ed25519.equals(publicKey.getCurve())) { - throw new JOSEException("Ed25519Verifier only supports OctetKeyPairs with crv=Ed25519"); - } - - if (publicKey.isPrivate()) { - throw new JOSEException("Ed25519Verifier requires a public key, use OctetKeyPair.toPublicJWK()"); - } - - this.publicKey = publicKey; - tinkVerifier = new Ed25519Verify(publicKey.getDecodedX()); - critPolicy.setDeferredCriticalHeaderParams(defCritHeaders); - } - - - /** - * Returns the public key. - * - * @return An OctetKeyPair without the private part - */ - public OctetKeyPair getPublicKey() { - - return publicKey; - } - - - @Override - public Set getProcessedCriticalHeaderParams() { - - return critPolicy.getProcessedCriticalHeaderParams(); - } - - - @Override - public Set getDeferredCriticalHeaderParams() { - - return critPolicy.getProcessedCriticalHeaderParams(); - } - - - @Override - public boolean verify(final JWSHeader header, - final byte[] signedContent, - final Base64URL signature) - throws JOSEException { - - // Check alg field in header - final JWSAlgorithm alg = header.getAlgorithm(); - if (! JWSAlgorithm.EdDSA.equals(alg)) { - throw new JOSEException("Ed25519Verifier requires alg=EdDSA in JWSHeader"); - } - - // Check for unrecognized "crit" properties - if (! critPolicy.headerPasses(header)) { - return false; - } - - final byte[] jwsSignature = signature.decode(); - - try { - tinkVerifier.verify(jwsSignature, signedContent); - return true; - - } catch (GeneralSecurityException e) { - return false; - } - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/MACSigner.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/MACSigner.java deleted file mode 100644 index 13f92e900..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/MACSigner.java +++ /dev/null @@ -1,196 +0,0 @@ -/* - * 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.crypto; - - -import java.util.Collections; -import java.util.LinkedHashSet; -import java.util.Set; -import javax.crypto.SecretKey; - -import com.nimbusds.jose.*; -import com.nimbusds.jose.crypto.impl.AlgorithmSupportMessage; -import com.nimbusds.jose.crypto.impl.HMAC; -import com.nimbusds.jose.crypto.impl.MACProvider; -import com.nimbusds.jose.jwk.OctetSequenceKey; -import com.nimbusds.jose.util.Base64URL; -import com.nimbusds.jose.util.ByteUtils; -import com.nimbusds.jose.util.StandardCharset; -import net.jcip.annotations.ThreadSafe; - - - -/** - * Message Authentication Code (MAC) signer of - * {@link com.nimbusds.jose.JWSObject JWS objects}. Expects a secret key. - * - *

See RFC 7518 - * section 3.2 - * for more information. - * - *

This class is thread-safe. - * - *

Supports the following algorithms: - * - *

    - *
  • {@link com.nimbusds.jose.JWSAlgorithm#HS256} - *
  • {@link com.nimbusds.jose.JWSAlgorithm#HS384} - *
  • {@link com.nimbusds.jose.JWSAlgorithm#HS512} - *
- * - * @author Vladimir Dzhuvinov - * @version 2016-07-27 - */ -@ThreadSafe -public class MACSigner extends MACProvider implements JWSSigner { - - - /** - * Returns the minimal required secret length for the specified HMAC - * JWS algorithm. - * - * @param alg The HMAC JWS algorithm. Must be - * {@link #SUPPORTED_ALGORITHMS supported} and not - * {@code null}. - * - * @return The minimal required secret length, in bits. - * - * @throws JOSEException If the algorithm is not supported. - */ - public static int getMinRequiredSecretLength(final JWSAlgorithm alg) - throws JOSEException { - - if (JWSAlgorithm.HS256.equals(alg)) { - return 256; - } else if (JWSAlgorithm.HS384.equals(alg)) { - return 384; - } else if (JWSAlgorithm.HS512.equals(alg)) { - return 512; - } else { - throw new JOSEException(AlgorithmSupportMessage.unsupportedJWSAlgorithm( - alg, - SUPPORTED_ALGORITHMS)); - } - } - - - /** - * Returns the compatible JWS HMAC algorithms for the specified secret - * length. - * - * @param secretLength The secret length in bits. Must not be negative. - * - * @return The compatible HMAC algorithms, empty set if the secret - * length is too short for any algorithm. - */ - public static Set getCompatibleAlgorithms(final int secretLength) { - - Set hmacAlgs = new LinkedHashSet<>(); - - if (secretLength >= 256) - hmacAlgs.add(JWSAlgorithm.HS256); - - if (secretLength >= 384) - hmacAlgs.add(JWSAlgorithm.HS384); - - if (secretLength >= 512) - hmacAlgs.add(JWSAlgorithm.HS512); - - return Collections.unmodifiableSet(hmacAlgs); - } - - - /** - * Creates a new Message Authentication (MAC) signer. - * - * @param secret The secret. Must be at least 256 bits long and not - * {@code null}. - * - * @throws KeyLengthException If the secret length is shorter than the - * minimum 256-bit requirement. - */ - public MACSigner(final byte[] secret) - throws KeyLengthException { - - super(secret, getCompatibleAlgorithms(ByteUtils.bitLength(secret.length))); - } - - - /** - * Creates a new Message Authentication (MAC) signer. - * - * @param secretString The secret as a UTF-8 encoded string. Must be at - * least 256 bits long and not {@code null}. - * - * @throws KeyLengthException If the secret length is shorter than the - * minimum 256-bit requirement. - */ - public MACSigner(final String secretString) - throws KeyLengthException { - - this(secretString.getBytes(StandardCharset.UTF_8)); - } - - - /** - * Creates a new Message Authentication (MAC) signer. - * - * @param secretKey The secret key. Must be at least 256 bits long and - * not {@code null}. - * - * @throws KeyLengthException If the secret length is shorter than the - * minimum 256-bit requirement. - */ - public MACSigner(final SecretKey secretKey) - throws KeyLengthException { - - this(secretKey.getEncoded()); - } - - - /** - * Creates a new Message Authentication (MAC) signer. - * - * @param jwk The secret as a JWK. Must be at least 256 bits long and - * not {@code null}. - * - * @throws KeyLengthException If the secret length is shorter than the - * minimum 256-bit requirement. - */ - public MACSigner(final OctetSequenceKey jwk) - throws KeyLengthException { - - this(jwk.toByteArray()); - } - - - @Override - public Base64URL sign(final JWSHeader header, final byte[] signingInput) - throws JOSEException { - - final int minRequiredLength = getMinRequiredSecretLength(header.getAlgorithm()); - - if (getSecret().length < ByteUtils.byteLength(minRequiredLength)) { - throw new KeyLengthException("The secret length for " + header.getAlgorithm() + " must be at least " + minRequiredLength + " bits"); - } - - String jcaAlg = getJCAAlgorithmName(header.getAlgorithm()); - byte[] hmac = HMAC.compute(jcaAlg, getSecret(), signingInput, getJCAContext().getProvider()); - return Base64URL.encode(hmac); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/MACVerifier.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/MACVerifier.java deleted file mode 100644 index efac68c11..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/MACVerifier.java +++ /dev/null @@ -1,183 +0,0 @@ -/* - * 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.crypto; - - -import java.util.Set; -import javax.crypto.SecretKey; - -import com.nimbusds.jose.CriticalHeaderParamsAware; -import com.nimbusds.jose.JOSEException; -import com.nimbusds.jose.JWSHeader; -import com.nimbusds.jose.JWSVerifier; -import com.nimbusds.jose.crypto.impl.CriticalHeaderParamsDeferral; -import com.nimbusds.jose.crypto.impl.HMAC; -import com.nimbusds.jose.crypto.impl.MACProvider; -import com.nimbusds.jose.crypto.utils.ConstantTimeUtils; -import com.nimbusds.jose.jwk.OctetSequenceKey; -import com.nimbusds.jose.util.Base64URL; -import com.nimbusds.jose.util.StandardCharset; -import net.jcip.annotations.ThreadSafe; - - -/** - * Message Authentication Code (MAC) verifier of - * {@link com.nimbusds.jose.JWSObject JWS objects}. Expects a secret key. - * - *

See RFC 7518 - * section 3.2 - * for more information. - * - *

This class is thread-safe. - * - *

Supports the following algorithms: - * - *

    - *
  • {@link com.nimbusds.jose.JWSAlgorithm#HS256} - *
  • {@link com.nimbusds.jose.JWSAlgorithm#HS384} - *
  • {@link com.nimbusds.jose.JWSAlgorithm#HS512} - *
- * - * @author Vladimir Dzhuvinov - * @version 2016-06-26 - */ -@ThreadSafe -public class MACVerifier extends MACProvider implements JWSVerifier, CriticalHeaderParamsAware { - - - /** - * The critical header policy. - */ - private final CriticalHeaderParamsDeferral critPolicy = new CriticalHeaderParamsDeferral(); - - - /** - * Creates a new Message Authentication (MAC) verifier. - * - * @param secret The secret. Must be at least 256 bits long and not - * {@code null}. - * - * @throws JOSEException If the secret length is shorter than the - * minimum 256-bit requirement. - */ - public MACVerifier(final byte[] secret) - throws JOSEException { - - this(secret, null); - } - - - /** - * Creates a new Message Authentication (MAC) verifier. - * - * @param secretString The secret as a UTF-8 encoded string. Must be at - * least 256 bits long and not {@code null}. - * - * @throws JOSEException If the secret length is shorter than the - * minimum 256-bit requirement. - */ - public MACVerifier(final String secretString) - throws JOSEException { - - this(secretString.getBytes(StandardCharset.UTF_8)); - } - - - /** - * Creates a new Message Authentication (MAC) verifier. - * - * @param secretKey The secret key. Must be at least 256 bits long and - * not {@code null}. - * - * @throws JOSEException If the secret length is shorter than the - * minimum 256-bit requirement. - */ - public MACVerifier(final SecretKey secretKey) - throws JOSEException { - - this(secretKey.getEncoded()); - } - - - /** - * Creates a new Message Authentication (MAC) verifier. - * - * @param jwk The secret as a JWK. Must be at least 256 bits long and - * not {@code null}. - * - * @throws JOSEException If the secret length is shorter than the - * minimum 256-bit requirement. - */ - public MACVerifier(final OctetSequenceKey jwk) - throws JOSEException { - - this(jwk.toByteArray()); - } - - - /** - * Creates a new Message Authentication (MAC) verifier. - * - * @param secret The secret. Must be at least 256 bits long - * and not {@code null}. - * @param defCritHeaders The names of the critical header parameters - * that are deferred to the application for - * processing, empty set or {@code null} if none. - * - * @throws JOSEException If the secret length is shorter than the - * minimum 256-bit requirement. - */ - public MACVerifier(final byte[] secret, - final Set defCritHeaders) - throws JOSEException { - - super(secret, SUPPORTED_ALGORITHMS); - - critPolicy.setDeferredCriticalHeaderParams(defCritHeaders); - } - - - @Override - public Set getProcessedCriticalHeaderParams() { - - return critPolicy.getProcessedCriticalHeaderParams(); - } - - - @Override - public Set getDeferredCriticalHeaderParams() { - - return critPolicy.getProcessedCriticalHeaderParams(); - } - - - @Override - public boolean verify(final JWSHeader header, - final byte[] signedContent, - final Base64URL signature) - throws JOSEException { - - if (! critPolicy.headerPasses(header)) { - return false; - } - - String jcaAlg = getJCAAlgorithmName(header.getAlgorithm()); - byte[] expectedHMAC = HMAC.compute(jcaAlg, getSecret(), signedContent, getJCAContext().getProvider()); - return ConstantTimeUtils.areEqual(expectedHMAC, signature.decode()); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/PasswordBasedDecrypter.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/PasswordBasedDecrypter.java deleted file mode 100644 index 406a2fe8a..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/PasswordBasedDecrypter.java +++ /dev/null @@ -1,157 +0,0 @@ -/* - * 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.crypto; - - -import java.util.Set; -import javax.crypto.SecretKey; - -import com.nimbusds.jose.*; -import com.nimbusds.jose.crypto.impl.*; -import com.nimbusds.jose.util.Base64URL; -import com.nimbusds.jose.util.StandardCharset; -import net.jcip.annotations.ThreadSafe; - - -/** - * Password-based decrypter of {@link com.nimbusds.jose.JWEObject JWE objects}. - * Expects a password. - * - *

See RFC 7518 - * section 4.8 - * for more information. - * - *

This class is thread-safe. - * - *

Supports the following key management algorithms: - * - *

    - *
  • {@link com.nimbusds.jose.JWEAlgorithm#PBES2_HS256_A128KW} - *
  • {@link com.nimbusds.jose.JWEAlgorithm#PBES2_HS384_A192KW} - *
  • {@link com.nimbusds.jose.JWEAlgorithm#PBES2_HS512_A256KW} - *
- * - *

Supports the following content encryption algorithms: - * - *

    - *
  • {@link com.nimbusds.jose.EncryptionMethod#A128CBC_HS256} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A192CBC_HS384} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A256CBC_HS512} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A128GCM} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A192GCM} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A256GCM} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A128CBC_HS256_DEPRECATED} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A256CBC_HS512_DEPRECATED} - *
- * - * @author Vladimir Dzhuvinov - * @version 2016-07-26 - */ -@ThreadSafe -public class PasswordBasedDecrypter extends PasswordBasedCryptoProvider implements JWEDecrypter, CriticalHeaderParamsAware { - - - /** - * The critical header policy. - */ - private final CriticalHeaderParamsDeferral critPolicy = new CriticalHeaderParamsDeferral(); - - - /** - * Creates a new password-based decrypter. - * - * @param password The password bytes. Must not be empty or - * {@code null}. - */ - public PasswordBasedDecrypter(final byte[] password) { - - super(password); - } - - - /** - * Creates a new password-based decrypter. - * - * @param password The password, as a UTF-8 encoded string. Must not be - * empty or {@code null}. - */ - public PasswordBasedDecrypter(final String password) { - - super(password.getBytes(StandardCharset.UTF_8)); - } - - - @Override - public Set getProcessedCriticalHeaderParams() { - - return critPolicy.getProcessedCriticalHeaderParams(); - } - - - @Override - public Set getDeferredCriticalHeaderParams() { - - return critPolicy.getProcessedCriticalHeaderParams(); - } - - - @Override - public byte[] decrypt(final JWEHeader header, - final Base64URL encryptedKey, - final Base64URL iv, - final Base64URL cipherText, - final Base64URL authTag) - throws JOSEException { - - // Validate required JWE parts - if (encryptedKey == null) { - throw new JOSEException("Missing JWE encrypted key"); - } - - if (iv == null) { - throw new JOSEException("Missing JWE initialization vector (IV)"); - } - - if (authTag == null) { - throw new JOSEException("Missing JWE authentication tag"); - } - - if (header.getPBES2Salt() == null) { - throw new JOSEException("Missing JWE \"p2s\" header parameter"); - } - - final byte[] salt = header.getPBES2Salt().decode(); - - if (header.getPBES2Count() < 1) { - throw new JOSEException("Missing JWE \"p2c\" header parameter"); - } - - final int iterationCount = header.getPBES2Count(); - - critPolicy.ensureHeaderPasses(header); - - final JWEAlgorithm alg = header.getAlgorithm(); - final byte[] formattedSalt = PBKDF2.formatSalt(alg, salt); - final PRFParams prfParams = PRFParams.resolve(alg, getJCAContext().getMACProvider()); - final SecretKey psKey = PBKDF2.deriveKey(getPassword(), formattedSalt, iterationCount, prfParams); - - final SecretKey cek = AESKW.unwrapCEK(psKey, encryptedKey.decode(), getJCAContext().getKeyEncryptionProvider()); - - return ContentCryptoProvider.decrypt(header, encryptedKey, iv, cipherText, authTag, cek, getJCAContext()); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/PasswordBasedEncrypter.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/PasswordBasedEncrypter.java deleted file mode 100644 index 9da35ee33..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/PasswordBasedEncrypter.java +++ /dev/null @@ -1,188 +0,0 @@ -/* - * 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.crypto; - - -import javax.crypto.SecretKey; - -import com.nimbusds.jose.*; -import com.nimbusds.jose.crypto.impl.*; -import com.nimbusds.jose.util.Base64URL; -import com.nimbusds.jose.util.StandardCharset; -import net.jcip.annotations.ThreadSafe; - - -/** - * Password-based encrypter of {@link com.nimbusds.jose.JWEObject JWE objects}. - * Expects a password. - * - *

See RFC 7518 - * section 4.8 - * for more information. - * - *

This class is thread-safe. - * - *

Supports the following key management algorithms: - * - *

    - *
  • {@link com.nimbusds.jose.JWEAlgorithm#PBES2_HS256_A128KW} - *
  • {@link com.nimbusds.jose.JWEAlgorithm#PBES2_HS384_A192KW} - *
  • {@link com.nimbusds.jose.JWEAlgorithm#PBES2_HS512_A256KW} - *
- * - *

Supports the following content encryption algorithms: - * - *

    - *
  • {@link com.nimbusds.jose.EncryptionMethod#A128CBC_HS256} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A192CBC_HS384} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A256CBC_HS512} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A128GCM} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A192GCM} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A256GCM} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A128CBC_HS256_DEPRECATED} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A256CBC_HS512_DEPRECATED} - *
- * - * @author Vladimir Dzhuvinov - * @version 2016-07-26 - */ -@ThreadSafe -public class PasswordBasedEncrypter extends PasswordBasedCryptoProvider implements JWEEncrypter { - - - /** - * The minimum salt length (8 bytes). - */ - public static final int MIN_SALT_LENGTH = 8; - - - /** - * The cryptographic salt length, in bytes. - */ - private final int saltLength; - - - /** - * The minimum recommended iteration count (1000). - */ - public static final int MIN_RECOMMENDED_ITERATION_COUNT = 1000; - - - /** - * The iteration count. - */ - private final int iterationCount; - - - /** - * Creates a new password-based encrypter. - * - * @param password The password bytes. Must not be empty or - * {@code null}. - * @param saltLength The length of the generated cryptographic - * salts, in bytes. Must be at least 8 bytes. - * @param iterationCount The pseudo-random function (PRF) iteration - * count. Must be at least 1000. - */ - public PasswordBasedEncrypter(final byte[] password, - final int saltLength, - final int iterationCount) { - - super(password); - - if (saltLength < MIN_SALT_LENGTH) { - throw new IllegalArgumentException("The minimum salt length (p2s) is " + MIN_SALT_LENGTH + " bytes"); - } - - this.saltLength = saltLength; - - if (iterationCount < MIN_RECOMMENDED_ITERATION_COUNT) { - throw new IllegalArgumentException("The minimum recommended iteration count (p2c) is " + MIN_RECOMMENDED_ITERATION_COUNT); - } - - this.iterationCount = iterationCount; - } - - - /** - * Creates a new password-based encrypter. - * - * @param password The password, as a UTF-8 encoded string. Must - * not be empty or {@code null}. - * @param saltLength The length of the generated cryptographic - * salts, in bytes. Must be at least 8 bytes. - * @param iterationCount The pseudo-random function (PRF) iteration - * count. Must be at least 1000. - */ - public PasswordBasedEncrypter(final String password, - final int saltLength, - final int iterationCount) { - - this(password.getBytes(StandardCharset.UTF_8), saltLength, iterationCount); - } - - - @Override - public JWECryptoParts encrypt(final JWEHeader header, final byte[] clearText) - throws JOSEException { - - final JWEAlgorithm alg = header.getAlgorithm(); - final EncryptionMethod enc = header.getEncryptionMethod(); - - final byte[] salt = new byte[saltLength]; - getJCAContext().getSecureRandom().nextBytes(salt); - final byte[] formattedSalt = PBKDF2.formatSalt(alg, salt); - final PRFParams prfParams = PRFParams.resolve(alg, getJCAContext().getMACProvider()); - final SecretKey psKey = PBKDF2.deriveKey(getPassword(), formattedSalt, iterationCount, prfParams); - - // We need to work on the header - final JWEHeader updatedHeader = new JWEHeader.Builder(header). - pbes2Salt(Base64URL.encode(salt)). - pbes2Count(iterationCount). - build(); - - final SecretKey cek = ContentCryptoProvider.generateCEK(enc, getJCAContext().getSecureRandom()); - - // The second JWE part - final Base64URL encryptedKey = Base64URL.encode(AESKW.wrapCEK(cek, psKey, getJCAContext().getKeyEncryptionProvider())); - - return ContentCryptoProvider.encrypt(updatedHeader, clearText, cek, encryptedKey, getJCAContext()); - } - - - /** - * Returns the length of the generated cryptographic salts. - * - * @return The length of the generated cryptographic salts, in bytes. - */ - public int getSaltLength() { - - return saltLength; - } - - - /** - * Returns the pseudo-random function (PRF) iteration count. - * - * @return The iteration count. - */ - public int getIterationCount() { - - return iterationCount; - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/RSADecrypter.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/RSADecrypter.java deleted file mode 100644 index a98e400ed..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/RSADecrypter.java +++ /dev/null @@ -1,301 +0,0 @@ -/* - * 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.crypto; - - -import java.security.PrivateKey; -import java.util.Set; -import javax.crypto.SecretKey; - -import static com.nimbusds.jose.jwk.gen.RSAKeyGenerator.MIN_KEY_SIZE_BITS; - -import com.nimbusds.jose.*; -import com.nimbusds.jose.crypto.impl.*; -import com.nimbusds.jose.jwk.RSAKey; -import com.nimbusds.jose.util.Base64URL; -import net.jcip.annotations.ThreadSafe; - - -/** - * RSA decrypter of {@link com.nimbusds.jose.JWEObject JWE objects}. Expects a - * private RSA key. - * - *

Decrypts the encrypted Content Encryption Key (CEK) with the private RSA - * key, and then uses the CEK along with the IV and authentication tag to - * decrypt the cipher text. See RFC 7518, sections - * 4.2 and - * 4.3 for more - * information. - * - *

This class is thread-safe. - * - *

Supports the following key management algorithms: - * - *

    - *
  • {@link com.nimbusds.jose.JWEAlgorithm#RSA_OAEP_256} - *
  • {@link com.nimbusds.jose.JWEAlgorithm#RSA_OAEP} (deprecated) - *
  • {@link com.nimbusds.jose.JWEAlgorithm#RSA1_5} (deprecated) - *
- * - *

Supports the following content encryption algorithms: - * - *

    - *
  • {@link com.nimbusds.jose.EncryptionMethod#A128CBC_HS256} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A192CBC_HS384} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A256CBC_HS512} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A128GCM} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A192GCM} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A256GCM} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A128CBC_HS256_DEPRECATED} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A256CBC_HS512_DEPRECATED} - *
- * - * @author David Ortiz - * @author Vladimir Dzhuvinov - * @author Dimitar A. Stoikov - * @version 2018-10-11 - */ -@ThreadSafe -public class RSADecrypter extends RSACryptoProvider implements JWEDecrypter, CriticalHeaderParamsAware { - - - /** - * The critical header policy. - */ - private final CriticalHeaderParamsDeferral critPolicy = new CriticalHeaderParamsDeferral(); - - - /** - * The private RSA key. - */ - private final PrivateKey privateKey; - - - /** - * Stores a CEK decryption exception is one was encountered during the - * last {@link #decrypt} run. - */ - private Exception cekDecryptionException; - - - /** - * Creates a new RSA decrypter. This constructor can also accept a - * private RSA key located in a PKCS#11 store that doesn't expose the - * private key parameters (such as a smart card or HSM). - * - * @param privateKey The private RSA key. Its algorithm must be "RSA" - * and its length at least 2048 bits. Note that the - * length of an RSA key in a PKCS#11 store cannot be - * checked. Must not be {@code null}. - */ - public RSADecrypter(final PrivateKey privateKey) { - - this(privateKey, null, false); - } - - - /** - * Creates a new RSA decrypter. - * - * @param rsaJWK The RSA JSON Web Key (JWK). Must contain or reference - * a private part. Its length must be at least 2048 bits. - * Note that the length of an RSA key in a PKCS#11 store - * cannot be checked. Must not be {@code null}. - * - * @throws JOSEException If the RSA JWK doesn't contain a private part - * or its extraction failed. - */ - public RSADecrypter(final RSAKey rsaJWK) - throws JOSEException { - - this(RSAKeyUtils.toRSAPrivateKey(rsaJWK)); - } - - - /** - * Creates a new RSA decrypter. This constructor can also accept a - * private RSA key located in a PKCS#11 store that doesn't expose the - * private key parameters (such as a smart card or HSM). - * - * @param privateKey The private RSA key. Its algorithm must be - * "RSA" and its length at least 2048 bits. Note - * that the length of an RSA key in a PKCS#11 - * store cannot be checked. Must not be - * {@code null}. - * @param defCritHeaders The names of the critical header parameters - * that are deferred to the application for - * processing, empty set or {@code null} if none. - */ - public RSADecrypter(final PrivateKey privateKey, - final Set defCritHeaders) { - - this(privateKey, defCritHeaders, false); - } - - - /** - * Creates a new RSA decrypter. This constructor can also accept a - * private RSA key located in a PKCS#11 store that doesn't expose the - * private key parameters (such as a smart card or HSM). - * - * @param privateKey The private RSA key. Its algorithm must be - * "RSA" and its length at least 2048 bits. Note - * that the length of an RSA key in a PKCS#11 - * store cannot be checked. Must not be - * {@code null}. - * @param defCritHeaders The names of the critical header parameters - * that are deferred to the application for - * processing, empty set or {@code null} if none. - * @param allowWeakKey {@code true} to allow an RSA key shorter than - * 2048 bits. - */ - public RSADecrypter(final PrivateKey privateKey, - final Set defCritHeaders, - final boolean allowWeakKey) { - - if (! privateKey.getAlgorithm().equalsIgnoreCase("RSA")) { - throw new IllegalArgumentException("The private key algorithm must be RSA"); - } - - if (! allowWeakKey) { - - int keyBitLength = RSAKeyUtils.keyBitLength(privateKey); - - if (keyBitLength > 0 && keyBitLength < MIN_KEY_SIZE_BITS) { - throw new IllegalArgumentException("The RSA key size must be at least " + MIN_KEY_SIZE_BITS + " bits"); - } - } - - this.privateKey = privateKey; - - critPolicy.setDeferredCriticalHeaderParams(defCritHeaders); - } - - - /** - * Gets the private RSA key. - * - * @return The private RSA key. Casting to - * {@link java.security.interfaces.RSAPrivateKey} may not be - * possible if the key is located in a PKCS#11 store that - * doesn't expose the private key parameters. - */ - public PrivateKey getPrivateKey() { - - return privateKey; - } - - - @Override - public Set getProcessedCriticalHeaderParams() { - - return critPolicy.getProcessedCriticalHeaderParams(); - } - - - @Override - public Set getDeferredCriticalHeaderParams() { - - return critPolicy.getProcessedCriticalHeaderParams(); - } - - - @Override - public byte[] decrypt(final JWEHeader header, - final Base64URL encryptedKey, - final Base64URL iv, - final Base64URL cipherText, - final Base64URL authTag) - throws JOSEException { - - // Validate required JWE parts - if (encryptedKey == null) { - throw new JOSEException("Missing JWE encrypted key"); - } - - if (iv == null) { - throw new JOSEException("Missing JWE initialization vector (IV)"); - } - - if (authTag == null) { - throw new JOSEException("Missing JWE authentication tag"); - } - - critPolicy.ensureHeaderPasses(header); - - - // Derive the content encryption key - JWEAlgorithm alg = header.getAlgorithm(); - - SecretKey cek; - - if (alg.equals(JWEAlgorithm.RSA1_5)) { - - int keyLength = header.getEncryptionMethod().cekBitLength(); - - // Protect against MMA attack by generating random CEK to be used on decryption failure, - // see http://www.ietf.org/mail-archive/web/jose/current/msg01832.html - final SecretKey randomCEK = ContentCryptoProvider.generateCEK(header.getEncryptionMethod(), getJCAContext().getSecureRandom()); - - try { - cek = RSA1_5.decryptCEK(privateKey, encryptedKey.decode(), keyLength, getJCAContext().getKeyEncryptionProvider()); - - if (cek == null) { - // CEK length mismatch, signalled by null instead of - // exception to prevent MMA attack - cek = randomCEK; - } - - } catch (Exception e) { - // continue - cekDecryptionException = e; - cek = randomCEK; - } - - cekDecryptionException = null; - - } else if (alg.equals(JWEAlgorithm.RSA_OAEP)) { - - cek = RSA_OAEP.decryptCEK(privateKey, encryptedKey.decode(), getJCAContext().getKeyEncryptionProvider()); - - } else if (alg.equals(JWEAlgorithm.RSA_OAEP_256)) { - - cek = RSA_OAEP_256.decryptCEK(privateKey, encryptedKey.decode(), getJCAContext().getKeyEncryptionProvider()); - - } else { - - throw new JOSEException(AlgorithmSupportMessage.unsupportedJWEAlgorithm(alg, SUPPORTED_ALGORITHMS)); - } - - return ContentCryptoProvider.decrypt(header, encryptedKey, iv, cipherText, authTag, cek, getJCAContext()); - } - - - /** - * Returns the Content Encryption Key (CEK) decryption exception if one - * was encountered during the last {@link #decrypt} run. Intended for - * logging and debugging purposes. - * - * @return The recorded exception, {@code null} if none. - */ - public Exception getCEKDecryptionException() { - - return cekDecryptionException; - } -} - diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/RSAEncrypter.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/RSAEncrypter.java deleted file mode 100644 index e0fc9e67a..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/RSAEncrypter.java +++ /dev/null @@ -1,200 +0,0 @@ -/* - * 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.crypto; - - -import java.security.interfaces.RSAPublicKey; -import javax.crypto.SecretKey; - -import com.nimbusds.jose.crypto.impl.*; -import net.jcip.annotations.ThreadSafe; - -import com.nimbusds.jose.EncryptionMethod; -import com.nimbusds.jose.JOSEException; -import com.nimbusds.jose.JWEAlgorithm; -import com.nimbusds.jose.JWECryptoParts; -import com.nimbusds.jose.JWEEncrypter; -import com.nimbusds.jose.JWEHeader; -import com.nimbusds.jose.jwk.RSAKey; -import com.nimbusds.jose.util.Base64URL; - - -/** - * RSA encrypter of {@link com.nimbusds.jose.JWEObject JWE objects}. Expects a - * public RSA key. - * - *

Encrypts the plain text with a generated AES key (the Content Encryption - * Key) according to the specified JOSE encryption method, then encrypts the - * CEK with the public RSA key and returns it alongside the IV, cipher text and - * authentication tag. See RFC 7518, sections - * 4.2 and - * 4.3 for more - * information. - * - *

This class is thread-safe. - * - *

Supports the following key management algorithms: - * - *

    - *
  • {@link com.nimbusds.jose.JWEAlgorithm#RSA_OAEP_256} - *
  • {@link com.nimbusds.jose.JWEAlgorithm#RSA_OAEP} (deprecated) - *
  • {@link com.nimbusds.jose.JWEAlgorithm#RSA1_5} (deprecated) - *
- * - *

Supports the following content encryption algorithms: - * - *

    - *
  • {@link com.nimbusds.jose.EncryptionMethod#A128CBC_HS256} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A192CBC_HS384} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A256CBC_HS512} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A128GCM} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A192GCM} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A256GCM} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A128CBC_HS256_DEPRECATED} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A256CBC_HS512_DEPRECATED} - *
- * - * @author David Ortiz - * @author Vladimir Dzhuvinov - * @author Jun Yu - * @version 2018-07-17 - */ -@ThreadSafe -public class RSAEncrypter extends RSACryptoProvider implements JWEEncrypter { - - - /** - * The public RSA key. - */ - private final RSAPublicKey publicKey; - - - /** - * The externally supplied AES content encryption key (CEK) to use, - * {@code null} to generate a CEK for each JWE. - */ - private final SecretKey contentEncryptionKey; - - - /** - * Creates a new RSA encrypter. - * - * @param publicKey The public RSA key. Must not be {@code null}. - */ - public RSAEncrypter(final RSAPublicKey publicKey) { - - this(publicKey, null); - } - - - /** - * Creates a new RSA encrypter. - * - * @param rsaJWK The RSA JSON Web Key (JWK). Must not be {@code null}. - * - * @throws JOSEException If the RSA JWK extraction failed. - */ - public RSAEncrypter(final RSAKey rsaJWK) - throws JOSEException { - - this(rsaJWK.toRSAPublicKey()); - } - - - /** - * Creates a new RSA encrypter with an optionally specified content - * encryption key (CEK). - * - * @param publicKey The public RSA key. Must not be - * {@code null}. - * @param contentEncryptionKey The content encryption key (CEK) to use. - * If specified its algorithm must be "AES" - * and its length must match the expected - * for the JWE encryption method ("enc"). - * If {@code null} a CEK will be generated - * for each JWE. - */ - public RSAEncrypter(final RSAPublicKey publicKey, final SecretKey contentEncryptionKey) { - - if (publicKey == null) { - throw new IllegalArgumentException("The public RSA key must not be null"); - } - this.publicKey = publicKey; - - if (contentEncryptionKey != null) { - if (contentEncryptionKey.getAlgorithm() == null || !contentEncryptionKey.getAlgorithm().equals("AES")) { - throw new IllegalArgumentException("The algorithm of the content encryption key (CEK) must be AES"); - } else { - this.contentEncryptionKey = contentEncryptionKey; - } - } else { - this.contentEncryptionKey = null; - } - } - - - /** - * Gets the public RSA key. - * - * @return The public RSA key. - */ - public RSAPublicKey getPublicKey() { - - return publicKey; - } - - - @Override - public JWECryptoParts encrypt(final JWEHeader header, final byte[] clearText) - throws JOSEException { - - final JWEAlgorithm alg = header.getAlgorithm(); - final EncryptionMethod enc = header.getEncryptionMethod(); - - // Generate and encrypt the CEK according to the enc method - final SecretKey cek; - if (contentEncryptionKey != null) { - // Use externally supplied CEK - cek = contentEncryptionKey; - } else { - // Generate and encrypt the CEK according to the enc method - cek = ContentCryptoProvider.generateCEK(enc, getJCAContext().getSecureRandom()); - } - - final Base64URL encryptedKey; // The second JWE part - - if (alg.equals(JWEAlgorithm.RSA1_5)) { - - encryptedKey = Base64URL.encode(RSA1_5.encryptCEK(publicKey, cek, getJCAContext().getKeyEncryptionProvider())); - - } else if (alg.equals(JWEAlgorithm.RSA_OAEP)) { - - encryptedKey = Base64URL.encode(RSA_OAEP.encryptCEK(publicKey, cek, getJCAContext().getKeyEncryptionProvider())); - - } else if (alg.equals(JWEAlgorithm.RSA_OAEP_256)) { - - encryptedKey = Base64URL.encode(RSA_OAEP_256.encryptCEK(publicKey, cek, getJCAContext().getKeyEncryptionProvider())); - - } else { - - throw new JOSEException(AlgorithmSupportMessage.unsupportedJWEAlgorithm(alg, SUPPORTED_ALGORITHMS)); - } - - return ContentCryptoProvider.encrypt(header, clearText, cek, encryptedKey, getJCAContext()); - } -} \ No newline at end of file diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/RSASSASigner.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/RSASSASigner.java deleted file mode 100644 index bdae07fa2..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/RSASSASigner.java +++ /dev/null @@ -1,201 +0,0 @@ -/* - * 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.crypto; - - -import java.security.InvalidKeyException; -import java.security.PrivateKey; -import java.security.Signature; -import java.security.SignatureException; - -import static com.nimbusds.jose.jwk.gen.RSAKeyGenerator.MIN_KEY_SIZE_BITS; - -import com.nimbusds.jose.JOSEException; -import com.nimbusds.jose.JWSHeader; -import com.nimbusds.jose.JWSSigner; -import com.nimbusds.jose.crypto.impl.RSAKeyUtils; -import com.nimbusds.jose.crypto.impl.RSASSA; -import com.nimbusds.jose.crypto.impl.RSASSAProvider; -import com.nimbusds.jose.jwk.RSAKey; -import com.nimbusds.jose.util.Base64URL; -import net.jcip.annotations.ThreadSafe; - - - -/** - * RSA Signature-Scheme-with-Appendix (RSASSA) signer of - * {@link com.nimbusds.jose.JWSObject JWS objects}. Expects a private RSA key. - * - *

See RFC 7518, sections - * 3.3 and - * 3.5 for more - * information. - * - *

This class is thread-safe. - * - *

Supports the following algorithms: - * - *

    - *
  • {@link com.nimbusds.jose.JWSAlgorithm#RS256} - *
  • {@link com.nimbusds.jose.JWSAlgorithm#RS384} - *
  • {@link com.nimbusds.jose.JWSAlgorithm#RS512} - *
  • {@link com.nimbusds.jose.JWSAlgorithm#PS256} - *
  • {@link com.nimbusds.jose.JWSAlgorithm#PS384} - *
  • {@link com.nimbusds.jose.JWSAlgorithm#PS512} - *
- * - * @author Vladimir Dzhuvinov - * @author Omer Levi Hevroni - * @version 2018-10-11 - */ -@ThreadSafe -public class RSASSASigner extends RSASSAProvider implements JWSSigner { - - - /** - * The private RSA key. Represented by generic private key interface to - * support key stores that prevent exposure of the private key - * parameters via the {@link java.security.interfaces.RSAPrivateKey} - * API. - * - * See https://bitbucket.org/connect2id/nimbus-jose-jwt/issues/169 - */ - private final PrivateKey privateKey; - - - /** - * Creates a new RSA Signature-Scheme-with-Appendix (RSASSA) signer. - * This constructor can also accept a private RSA key located in a - * PKCS#11 store that doesn't expose the private key parameters (such - * as a smart card or HSM). - * - * @param privateKey The private RSA key. Its algorithm must be "RSA" - * and its length at least 2048 bits. Note that the - * length of an RSA key in a PKCS#11 store cannot be - * checked. Must not be {@code null}. - */ - public RSASSASigner(final PrivateKey privateKey) { - - this(privateKey, false); - } - - - /** - * Creates a new RSA Signature-Scheme-with-Appendix (RSASSA) signer. - * This constructor can also accept a private RSA key located in a - * PKCS#11 store that doesn't expose the private key parameters (such - * as a smart card or HSM). - * - * @param privateKey The private RSA key. Its algorithm must be - * "RSA" and its length at least 2048 bits. Note - * that the length of an RSA key in a PKCS#11 store - * cannot be checked. Must not be {@code null}. - * @param allowWeakKey {@code true} to allow an RSA key shorter than - * 2048 bits. - */ - public RSASSASigner(final PrivateKey privateKey, final boolean allowWeakKey) { - - if (! "RSA".equalsIgnoreCase(privateKey.getAlgorithm())) { - throw new IllegalArgumentException("The private key algorithm must be RSA"); - } - - if (! allowWeakKey) { - - int keyBitLength = RSAKeyUtils.keyBitLength(privateKey); - - if (keyBitLength > 0 && keyBitLength < MIN_KEY_SIZE_BITS) { - throw new IllegalArgumentException("The RSA key size must be at least " + MIN_KEY_SIZE_BITS + " bits"); - } - } - - this.privateKey = privateKey; - } - - - /** - * Creates a new RSA Signature-Scheme-with-Appendix (RSASSA) signer. - * - * @param rsaJWK The RSA JSON Web Key (JWK). Must contain or reference - * a private part. Its length must be at least 2048 bits. - * Note that the length of an RSA key in a PKCS#11 store - * cannot be checked. Must not be {@code null}. - * - * @throws JOSEException If the RSA JWK doesn't contain a private part - * or its extraction failed. - */ - public RSASSASigner(final RSAKey rsaJWK) - throws JOSEException { - - this(rsaJWK, false); - } - - - /** - * Creates a new RSA Signature-Scheme-with-Appendix (RSASSA) signer. - * - * @param rsaJWK The RSA JSON Web Key (JWK). Must contain or - * reference a private part. Its length must be at - * least 2048 bits. Note that the length of an RSA - * key in a PKCS#11 store cannot be checked. Must - * not be {@code null}. - * @param allowWeakKey {@code true} to allow an RSA key shorter than - * 2048 bits. - * - * @throws JOSEException If the RSA JWK doesn't contain a private part - * or its extraction failed. - */ - public RSASSASigner(final RSAKey rsaJWK, final boolean allowWeakKey) - throws JOSEException { - - this(RSAKeyUtils.toRSAPrivateKey(rsaJWK), allowWeakKey); - } - - - /** - * Gets the private RSA key. - * - * @return The private RSA key. Casting to - * {@link java.security.interfaces.RSAPrivateKey} may not be - * possible if the key is located in a PKCS#11 store that - * doesn't expose the private key parameters. - */ - public PrivateKey getPrivateKey() { - - return privateKey; - } - - - @Override - public Base64URL sign(final JWSHeader header, final byte[] signingInput) - throws JOSEException { - - Signature signer = RSASSA.getSignerAndVerifier(header.getAlgorithm(), getJCAContext().getProvider()); - - try { - signer.initSign(privateKey); - signer.update(signingInput); - return Base64URL.encode(signer.sign()); - - } catch (InvalidKeyException e) { - throw new JOSEException("Invalid private RSA key: " + e.getMessage(), e); - - } catch (SignatureException e) { - throw new JOSEException("RSA signature exception: " + e.getMessage(), e); - } - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/RSASSAVerifier.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/RSASSAVerifier.java deleted file mode 100644 index 88e9ffa58..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/RSASSAVerifier.java +++ /dev/null @@ -1,176 +0,0 @@ -/* - * 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.crypto; - - -import java.security.InvalidKeyException; -import java.security.Signature; -import java.security.SignatureException; -import java.security.interfaces.RSAPublicKey; -import java.util.Set; - -import com.nimbusds.jose.crypto.impl.CriticalHeaderParamsDeferral; -import com.nimbusds.jose.crypto.impl.RSASSA; -import com.nimbusds.jose.crypto.impl.RSASSAProvider; -import net.jcip.annotations.ThreadSafe; - -import com.nimbusds.jose.*; -import com.nimbusds.jose.jwk.RSAKey; -import com.nimbusds.jose.util.Base64URL; - - -/** - * RSA Signature-Scheme-with-Appendix (RSASSA) verifier of - * {@link com.nimbusds.jose.JWSObject JWS objects}. Expects a public RSA key. - * - *

See RFC 7518, sections - * 3.3 and - * 3.5 for more - * information. - * - *

This class is thread-safe. - * - *

Supports the following algorithms: - * - *

    - *
  • {@link com.nimbusds.jose.JWSAlgorithm#RS256} - *
  • {@link com.nimbusds.jose.JWSAlgorithm#RS384} - *
  • {@link com.nimbusds.jose.JWSAlgorithm#RS512} - *
  • {@link com.nimbusds.jose.JWSAlgorithm#PS256} - *
  • {@link com.nimbusds.jose.JWSAlgorithm#PS384} - *
  • {@link com.nimbusds.jose.JWSAlgorithm#PS512} - *
- * - * @author Vladimir Dzhuvinov - * @version 2015-06-02 - */ -@ThreadSafe -public class RSASSAVerifier extends RSASSAProvider implements JWSVerifier, CriticalHeaderParamsAware { - - - /** - * The critical header policy. - */ - private final CriticalHeaderParamsDeferral critPolicy = new CriticalHeaderParamsDeferral(); - - - /** - * The public RSA key. - */ - private final RSAPublicKey publicKey; - - - /** - * Creates a new RSA Signature-Scheme-with-Appendix (RSASSA) verifier. - * - * @param publicKey The public RSA key. Must not be {@code null}. - */ - public RSASSAVerifier(final RSAPublicKey publicKey) { - - this(publicKey, null); - } - - - /** - * Creates a new RSA Signature-Scheme-with-Appendix (RSASSA) verifier. - * - * @param rsaJWK The RSA JSON Web Key (JWK). Must not be {@code null}. - * - * @throws JOSEException If the RSA JWK extraction failed. - */ - public RSASSAVerifier(final RSAKey rsaJWK) - throws JOSEException { - - this(rsaJWK.toRSAPublicKey(), null); - } - - - /** - * Creates a new RSA Signature-Scheme-with-Appendix (RSASSA) verifier. - * - * @param publicKey The public RSA key. Must not be {@code null}. - * @param defCritHeaders The names of the critical header parameters - * that are deferred to the application for - * processing, empty set or {@code null} if none. - */ - public RSASSAVerifier(final RSAPublicKey publicKey, - final Set defCritHeaders) { - - if (publicKey == null) { - throw new IllegalArgumentException("The public RSA key must not be null"); - } - - this.publicKey = publicKey; - - critPolicy.setDeferredCriticalHeaderParams(defCritHeaders); - } - - - /** - * Gets the public RSA key. - * - * @return The public RSA key. - */ - public RSAPublicKey getPublicKey() { - - return publicKey; - } - - - @Override - public Set getProcessedCriticalHeaderParams() { - - return critPolicy.getProcessedCriticalHeaderParams(); - } - - - @Override - public Set getDeferredCriticalHeaderParams() { - - return critPolicy.getProcessedCriticalHeaderParams(); - } - - - @Override - public boolean verify(final JWSHeader header, - final byte[] signedContent, - final Base64URL signature) - throws JOSEException { - - if (! critPolicy.headerPasses(header)) { - return false; - } - - final Signature verifier = RSASSA.getSignerAndVerifier(header.getAlgorithm(), getJCAContext().getProvider()); - - try { - verifier.initVerify(publicKey); - - } catch (InvalidKeyException e) { - throw new JOSEException("Invalid public RSA key: " + e.getMessage(), e); - } - - try { - verifier.update(signedContent); - return verifier.verify(signature.decode()); - - } catch (SignatureException e) { - return false; - } - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/X25519Decrypter.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/X25519Decrypter.java deleted file mode 100644 index 253388a7f..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/X25519Decrypter.java +++ /dev/null @@ -1,196 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2018, 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.crypto; - - -import java.util.Collections; -import java.util.Set; -import javax.crypto.SecretKey; - -import com.nimbusds.jose.*; -import com.nimbusds.jose.crypto.impl.CriticalHeaderParamsDeferral; -import com.nimbusds.jose.crypto.impl.ECDH; -import com.nimbusds.jose.crypto.impl.ECDHCryptoProvider; -import com.nimbusds.jose.jwk.Curve; -import com.nimbusds.jose.jwk.OctetKeyPair; -import com.nimbusds.jose.util.Base64URL; - - -/** - * Curve25519 Elliptic Curve Diffie-Hellman decrypter of - * {@link com.nimbusds.jose.JWEObject JWE objects}. - * Expects a private {@link OctetKeyPair} key with {@code "crv"} X25519. - * - *

See RFC 8037 - * for more information. - * - *

See also {@link ECDHDecrypter} for ECDH on other curves. - * - *

This class is thread-safe. - * - *

Supports the following key management algorithms: - * - *

    - *
  • {@link com.nimbusds.jose.JWEAlgorithm#ECDH_ES} - *
  • {@link com.nimbusds.jose.JWEAlgorithm#ECDH_ES_A128KW} - *
  • {@link com.nimbusds.jose.JWEAlgorithm#ECDH_ES_A192KW} - *
  • {@link com.nimbusds.jose.JWEAlgorithm#ECDH_ES_A256KW} - *
- * - *

Supports the following elliptic curve: - * - *

    - *
  • {@link com.nimbusds.jose.jwk.Curve#X25519} (Curve25519) - *
- * - *

Supports the following content encryption algorithms: - * - *

    - *
  • {@link com.nimbusds.jose.EncryptionMethod#A128CBC_HS256} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A192CBC_HS384} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A256CBC_HS512} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A128GCM} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A192GCM} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A256GCM} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A128CBC_HS256_DEPRECATED} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A256CBC_HS512_DEPRECATED} - *
- * - * @author Tim McLean - * @version 2018-07-12 - */ -public class X25519Decrypter extends ECDHCryptoProvider implements JWEDecrypter, CriticalHeaderParamsAware { - - - /** - * The private key. - */ - private final OctetKeyPair privateKey; - - - /** - * The critical header policy. - */ - private final CriticalHeaderParamsDeferral critPolicy = new CriticalHeaderParamsDeferral(); - - - /** - * Creates a new Curve25519 Elliptic Curve Diffie-Hellman decrypter. - * - * @param privateKey The private key. Must not be {@code null}. - * - * @throws JOSEException If the key subtype is not supported. - */ - public X25519Decrypter(final OctetKeyPair privateKey) - throws JOSEException { - - this(privateKey, null); - } - - - /** - * Creates a new Curve25519 Elliptic Curve Diffie-Hellman decrypter. - * - * @param privateKey The private key. Must not be {@code null}. - * @param defCritHeaders The names of the critical header parameters - * that are deferred to the application for - * processing, empty set or {@code null} if none. - * - * @throws JOSEException If the key subtype is not supported. - */ - public X25519Decrypter(final OctetKeyPair privateKey, final Set defCritHeaders) - throws JOSEException { - - super(privateKey.getCurve()); - - if (! Curve.X25519.equals(privateKey.getCurve())) { - throw new JOSEException("X25519Decrypter only supports OctetKeyPairs with crv=X25519"); - } - - if (! privateKey.isPrivate()) { - throw new JOSEException("The OctetKeyPair doesn't contain a private part"); - } - - this.privateKey = privateKey; - - critPolicy.setDeferredCriticalHeaderParams(defCritHeaders); - } - - - @Override - public Set supportedEllipticCurves() { - - return Collections.singleton(Curve.X25519); - } - - - /** - * Returns the private key. - * - * @return The private key. - */ - public OctetKeyPair getPrivateKey() { - - return privateKey; - } - - - @Override - public Set getProcessedCriticalHeaderParams() { - - return critPolicy.getProcessedCriticalHeaderParams(); - } - - - @Override - public Set getDeferredCriticalHeaderParams() { - - return critPolicy.getProcessedCriticalHeaderParams(); - } - - - @Override - public byte[] decrypt(final JWEHeader header, - final Base64URL encryptedKey, - final Base64URL iv, - final Base64URL cipherText, - final Base64URL authTag) - throws JOSEException { - - // Check for unrecognizable "crit" properties - critPolicy.ensureHeaderPasses(header); - - // Get ephemeral key from header - OctetKeyPair ephemeralPublicKey = (OctetKeyPair) header.getEphemeralPublicKey(); - - if (ephemeralPublicKey == null) { - throw new JOSEException("Missing ephemeral public key \"epk\" JWE header parameter"); - } - - if (! privateKey.getCurve().equals(ephemeralPublicKey.getCurve())) { - throw new JOSEException("Curve of ephemeral public key does not match curve of private key"); - } - - // Derive 'Z' - // Note: X25519 does not require public key validation - // See https://cr.yp.to/ecdh.html#validate - SecretKey Z = ECDH.deriveSharedSecret(ephemeralPublicKey, privateKey); - - return decryptWithZ(header, Z, encryptedKey, iv, cipherText, authTag); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/X25519Encrypter.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/X25519Encrypter.java deleted file mode 100644 index ddb69154a..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/X25519Encrypter.java +++ /dev/null @@ -1,162 +0,0 @@ -/* - * 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.crypto; - - -import java.security.*; -import java.util.Collections; -import java.util.Set; -import javax.crypto.SecretKey; - -import com.google.crypto.tink.subtle.X25519; -import com.nimbusds.jose.*; -import com.nimbusds.jose.crypto.impl.ECDH; -import com.nimbusds.jose.crypto.impl.ECDHCryptoProvider; -import com.nimbusds.jose.jwk.Curve; -import com.nimbusds.jose.jwk.OctetKeyPair; -import com.nimbusds.jose.util.Base64URL; -import net.jcip.annotations.ThreadSafe; - - -/** - * Curve25519 Elliptic Curve Diffie-Hellman encrypter of - * {@link com.nimbusds.jose.JWEObject JWE objects}. - * Expects a public {@link OctetKeyPair} key with {@code "crv"} X25519. - * - *

See RFC 8037 - * for more information. - * - *

See also {@link ECDHEncrypter} for ECDH on other curves. - * - *

This class is thread-safe. - * - *

Supports the following key management algorithms: - * - *

    - *
  • {@link com.nimbusds.jose.JWEAlgorithm#ECDH_ES} - *
  • {@link com.nimbusds.jose.JWEAlgorithm#ECDH_ES_A128KW} - *
  • {@link com.nimbusds.jose.JWEAlgorithm#ECDH_ES_A192KW} - *
  • {@link com.nimbusds.jose.JWEAlgorithm#ECDH_ES_A256KW} - *
- * - *

Supports the following elliptic curve: - * - *

    - *
  • {@link com.nimbusds.jose.jwk.Curve#X25519} (Curve25519) - *
- * - *

Supports the following content encryption algorithms: - * - *

    - *
  • {@link com.nimbusds.jose.EncryptionMethod#A128CBC_HS256} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A192CBC_HS384} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A256CBC_HS512} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A128GCM} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A192GCM} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A256GCM} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A128CBC_HS256_DEPRECATED} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A256CBC_HS512_DEPRECATED} - *
- * - * @author Tim McLean - * @version 2018-07-12 - */ -@ThreadSafe -public class X25519Encrypter extends ECDHCryptoProvider implements JWEEncrypter { - - - /** - * The public key. - */ - private final OctetKeyPair publicKey; - - - /** - * Creates a new Curve25519 Elliptic Curve Diffie-Hellman encrypter. - * - * @param publicKey The public key. Must not be {@code null}. - * - * @throws JOSEException If the key subtype is not supported. - */ - public X25519Encrypter(final OctetKeyPair publicKey) - throws JOSEException { - - super(publicKey.getCurve()); - - if (! Curve.X25519.equals(publicKey.getCurve())) { - throw new JOSEException("X25519Encrypter only supports OctetKeyPairs with crv=X25519"); - } - - if (publicKey.isPrivate()) { - throw new JOSEException("X25519Encrypter requires a public key, use OctetKeyPair.toPublicJWK()"); - } - - this.publicKey = publicKey; - } - - - @Override - public Set supportedEllipticCurves() { - - return Collections.singleton(Curve.X25519); - } - - - /** - * Returns the public key. - * - * @return The public key. - */ - public OctetKeyPair getPublicKey() { - - return publicKey; - } - - - @Override - public JWECryptoParts encrypt(final JWEHeader header, final byte[] clearText) - throws JOSEException { - - // Generate ephemeral X25519 key pair - final byte[] ephemeralPrivateKeyBytes = X25519.generatePrivateKey(); - final byte[] ephemeralPublicKeyBytes; - try { - ephemeralPublicKeyBytes = X25519.publicFromPrivate(ephemeralPrivateKeyBytes); - - } catch (InvalidKeyException e) { - // Should never happen since we just generated this private key - throw new JOSEException(e.getMessage(), e); - } - - final OctetKeyPair ephemeralPrivateKey = - new OctetKeyPair.Builder(getCurve(), Base64URL.encode(ephemeralPublicKeyBytes)). - d(Base64URL.encode(ephemeralPrivateKeyBytes)). - build(); - final OctetKeyPair ephemeralPublicKey = ephemeralPrivateKey.toPublicJWK(); - - // Add the ephemeral public EC key to the header - JWEHeader updatedHeader = new JWEHeader.Builder(header). - ephemeralPublicKey(ephemeralPublicKey). - build(); - - // Derive 'Z' - SecretKey Z = ECDH.deriveSharedSecret(publicKey, ephemeralPrivateKey); - - return encryptWithZ(updatedHeader, Z, clearText); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/bc/BouncyCastleProviderSingleton.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/bc/BouncyCastleProviderSingleton.java deleted file mode 100644 index ee592fee4..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/bc/BouncyCastleProviderSingleton.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * 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.crypto.bc; - - -import org.bouncycastle.jce.provider.BouncyCastleProvider; - - -/** - * BouncyCastle JCA provider singleton, intended to prevent memory leaks by - * ensuring a single instance is loaded at all times. Application code that - * needs a BouncyCastle JCA provider should use the {@link #getInstance()} - * method to obtain an instance. - * - * @author Vladimir Dzhuvinov - */ -public final class BouncyCastleProviderSingleton { - - - /** - * The BouncyCastle provider, lazily instantiated. - */ - private static BouncyCastleProvider bouncyCastleProvider; - - - /** - * Prevents external instantiation. - */ - private BouncyCastleProviderSingleton() { } - - - /** - * Returns a BouncyCastle JCA provider instance. - * - * @return The BouncyCastle JCA provider instance. - */ - public static BouncyCastleProvider getInstance() { - - if (bouncyCastleProvider != null) { - - return bouncyCastleProvider; - - } else { - bouncyCastleProvider = new BouncyCastleProvider(); - return bouncyCastleProvider; - } - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/bc/package-info.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/bc/package-info.java deleted file mode 100644 index 8f71dd699..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/bc/package-info.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * 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. - */ - -/** - * BouncyCastle JCA provider singleton. - */ -package com.nimbusds.jose.crypto.bc; \ No newline at end of file diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/factories/DefaultJWEDecrypterFactory.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/factories/DefaultJWEDecrypterFactory.java deleted file mode 100644 index d0358bf62..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/factories/DefaultJWEDecrypterFactory.java +++ /dev/null @@ -1,190 +0,0 @@ -/* - * 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.crypto.factories; - - -import java.security.Key; -import java.security.interfaces.ECPrivateKey; -import java.security.interfaces.RSAPrivateKey; -import java.util.Collections; -import java.util.LinkedHashSet; -import java.util.Set; -import javax.crypto.SecretKey; - -import com.nimbusds.jose.*; -import com.nimbusds.jose.crypto.*; -import com.nimbusds.jose.jca.JWEJCAContext; -import com.nimbusds.jose.proc.JWEDecrypterFactory; -import net.jcip.annotations.ThreadSafe; - - -/** - * Default JSON Web Encryption (JWE) decrypter factory. - * - *

Supports all standard JWE algorithms implemented in the - * {@link com.nimbusds.jose.crypto} package. - * - * @author Vladimir Dzhuvinov - * @version 2015-11-16 - */ -@ThreadSafe -public class DefaultJWEDecrypterFactory implements JWEDecrypterFactory { - - - /** - * The supported JWE algorithms. - */ - public static final Set SUPPORTED_ALGORITHMS; - - - /** - * The supported encryption methods. - */ - public static final Set SUPPORTED_ENCRYPTION_METHODS; - - - static { - Set algs = new LinkedHashSet<>(); - algs.addAll(RSADecrypter.SUPPORTED_ALGORITHMS); - algs.addAll(ECDHDecrypter.SUPPORTED_ALGORITHMS); - algs.addAll(DirectDecrypter.SUPPORTED_ALGORITHMS); - algs.addAll(AESDecrypter.SUPPORTED_ALGORITHMS); - algs.addAll(PasswordBasedDecrypter.SUPPORTED_ALGORITHMS); - SUPPORTED_ALGORITHMS = Collections.unmodifiableSet(algs); - - Set encs = new LinkedHashSet<>(); - encs.addAll(RSADecrypter.SUPPORTED_ENCRYPTION_METHODS); - encs.addAll(ECDHDecrypter.SUPPORTED_ENCRYPTION_METHODS); - encs.addAll(DirectDecrypter.SUPPORTED_ENCRYPTION_METHODS); - encs.addAll(AESDecrypter.SUPPORTED_ENCRYPTION_METHODS); - encs.addAll(PasswordBasedDecrypter.SUPPORTED_ENCRYPTION_METHODS); - SUPPORTED_ENCRYPTION_METHODS = Collections.unmodifiableSet(encs); - } - - - /** - * The JWE JCA context. - */ - private final JWEJCAContext jcaContext = new JWEJCAContext(); - - - @Override - public Set supportedJWEAlgorithms() { - - return SUPPORTED_ALGORITHMS; - } - - - @Override - public Set supportedEncryptionMethods() { - - return SUPPORTED_ENCRYPTION_METHODS; - } - - - @Override - public JWEJCAContext getJCAContext() { - - return jcaContext; - } - - - @Override - public JWEDecrypter createJWEDecrypter(final JWEHeader header, final Key key) - throws JOSEException { - - final JWEDecrypter decrypter; - - if (RSADecrypter.SUPPORTED_ALGORITHMS.contains(header.getAlgorithm()) && - RSADecrypter.SUPPORTED_ENCRYPTION_METHODS.contains(header.getEncryptionMethod())) { - - if (!(key instanceof RSAPrivateKey)) { - throw new KeyTypeException(RSAPrivateKey.class); - } - - RSAPrivateKey rsaPrivateKey = (RSAPrivateKey)key; - - decrypter = new RSADecrypter(rsaPrivateKey); - - } else if (ECDHDecrypter.SUPPORTED_ALGORITHMS.contains(header.getAlgorithm()) && - ECDHDecrypter.SUPPORTED_ENCRYPTION_METHODS.contains(header.getEncryptionMethod())) { - - if (!(key instanceof ECPrivateKey)) { - throw new KeyTypeException(ECPrivateKey.class); - } - - ECPrivateKey ecPrivateKey = (ECPrivateKey)key; - decrypter = new ECDHDecrypter(ecPrivateKey); - - } else if (DirectDecrypter.SUPPORTED_ALGORITHMS.contains(header.getAlgorithm()) && - DirectDecrypter.SUPPORTED_ENCRYPTION_METHODS.contains(header.getEncryptionMethod())) { - - if (!(key instanceof SecretKey)) { - throw new KeyTypeException(SecretKey.class); - } - - SecretKey aesKey = (SecretKey)key; - DirectDecrypter directDecrypter = new DirectDecrypter(aesKey); - - if (! directDecrypter.supportedEncryptionMethods().contains(header.getEncryptionMethod())) { - throw new KeyLengthException(header.getEncryptionMethod().cekBitLength(), header.getEncryptionMethod()); - } - - decrypter = directDecrypter; - - } else if (AESDecrypter.SUPPORTED_ALGORITHMS.contains(header.getAlgorithm()) && - AESDecrypter.SUPPORTED_ENCRYPTION_METHODS.contains(header.getEncryptionMethod())) { - - if (!(key instanceof SecretKey)) { - throw new KeyTypeException(SecretKey.class); - } - - SecretKey aesKey = (SecretKey)key; - AESDecrypter aesDecrypter = new AESDecrypter(aesKey); - - if (! aesDecrypter.supportedJWEAlgorithms().contains(header.getAlgorithm())) { - throw new KeyLengthException(header.getAlgorithm()); - } - - decrypter = aesDecrypter; - - } else if (PasswordBasedDecrypter.SUPPORTED_ALGORITHMS.contains(header.getAlgorithm()) && - PasswordBasedDecrypter.SUPPORTED_ENCRYPTION_METHODS.contains(header.getEncryptionMethod())) { - - if (!(key instanceof SecretKey)) { - throw new KeyTypeException(SecretKey.class); - } - - byte[] password = key.getEncoded(); - decrypter = new PasswordBasedDecrypter(password); - - } else { - - throw new JOSEException("Unsupported JWE algorithm or encryption method"); - } - - // Apply JCA context - decrypter.getJCAContext().setSecureRandom(jcaContext.getSecureRandom()); - decrypter.getJCAContext().setProvider(jcaContext.getProvider()); - decrypter.getJCAContext().setKeyEncryptionProvider(jcaContext.getKeyEncryptionProvider()); - decrypter.getJCAContext().setMACProvider(jcaContext.getMACProvider()); - decrypter.getJCAContext().setContentEncryptionProvider(jcaContext.getContentEncryptionProvider()); - - return decrypter; - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/factories/DefaultJWSVerifierFactory.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/factories/DefaultJWSVerifierFactory.java deleted file mode 100644 index 7129abd51..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/factories/DefaultJWSVerifierFactory.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * 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.crypto.factories; - - -import java.security.Key; -import java.security.interfaces.ECPublicKey; -import java.security.interfaces.RSAPublicKey; -import java.util.Collections; -import java.util.LinkedHashSet; -import java.util.Set; -import javax.crypto.SecretKey; - -import com.nimbusds.jose.*; -import com.nimbusds.jose.crypto.ECDSAVerifier; -import com.nimbusds.jose.crypto.MACVerifier; -import com.nimbusds.jose.crypto.RSASSAVerifier; -import com.nimbusds.jose.jca.JCAContext; -import com.nimbusds.jose.proc.JWSVerifierFactory; -import net.jcip.annotations.ThreadSafe; - - -/** - * Default JSON Web Signature (JWS) verifier factory. - * - *

Supports all standard JWS algorithms implemented in the - * {@link com.nimbusds.jose.crypto} package. - * - * @author Vladimir Dzhuvinov - * @version 2015-11-16 - */ -@ThreadSafe -public class DefaultJWSVerifierFactory implements JWSVerifierFactory { - - - /** - * The supported JWS algorithms. - */ - public static final Set SUPPORTED_ALGORITHMS; - - - static { - Set algs = new LinkedHashSet<>(); - algs.addAll(MACVerifier.SUPPORTED_ALGORITHMS); - algs.addAll(RSASSAVerifier.SUPPORTED_ALGORITHMS); - algs.addAll(ECDSAVerifier.SUPPORTED_ALGORITHMS); - SUPPORTED_ALGORITHMS = Collections.unmodifiableSet(algs); - } - - - /** - * The JCA context. - */ - private final JCAContext jcaContext = new JCAContext(); - - - @Override - public Set supportedJWSAlgorithms() { - - return SUPPORTED_ALGORITHMS; - } - - - @Override - public JCAContext getJCAContext() { - - return jcaContext; - } - - - @Override - public JWSVerifier createJWSVerifier(final JWSHeader header, final Key key) - throws JOSEException { - - JWSVerifier verifier; - - if (MACVerifier.SUPPORTED_ALGORITHMS.contains(header.getAlgorithm())) { - - if (!(key instanceof SecretKey)) { - throw new KeyTypeException(SecretKey.class); - } - - SecretKey macKey = (SecretKey)key; - - verifier = new MACVerifier(macKey); - - } else if (RSASSAVerifier.SUPPORTED_ALGORITHMS.contains(header.getAlgorithm())) { - - if (!(key instanceof RSAPublicKey)) { - throw new KeyTypeException(RSAPublicKey.class); - } - - RSAPublicKey rsaPublicKey = (RSAPublicKey)key; - - verifier = new RSASSAVerifier(rsaPublicKey); - - } else if (ECDSAVerifier.SUPPORTED_ALGORITHMS.contains(header.getAlgorithm())) { - - if (!(key instanceof ECPublicKey)) { - throw new KeyTypeException(ECPublicKey.class); - } - - ECPublicKey ecPublicKey = (ECPublicKey)key; - - verifier = new ECDSAVerifier(ecPublicKey); - - } else { - - throw new JOSEException("Unsupported JWS algorithm: " + header.getAlgorithm()); - } - - // Apply JCA context - verifier.getJCAContext().setSecureRandom(jcaContext.getSecureRandom()); - verifier.getJCAContext().setProvider(jcaContext.getProvider()); - - return verifier; - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/factories/package-info.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/factories/package-info.java deleted file mode 100644 index 4be4110a4..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/factories/package-info.java +++ /dev/null @@ -1,22 +0,0 @@ -/* - * 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. - */ - -/** - * JWS verifier and JWE decrypter factories for use by the JOSE / JWT processor - * framework. - */ -package com.nimbusds.jose.crypto.factories; \ No newline at end of file diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/AAD.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/AAD.java deleted file mode 100644 index 30bac8a26..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/AAD.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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.crypto.impl; - - -import java.nio.ByteBuffer; -import java.nio.charset.Charset; - -import com.nimbusds.jose.JWEHeader; -import com.nimbusds.jose.util.Base64URL; -import com.nimbusds.jose.util.ByteUtils; -import com.nimbusds.jose.util.IntegerOverflowException; - - -/** - * Additional authenticated data (AAD). - * - *

See RFC 7518 (JWA), section 5.1, point 14. - * - * @author Vladimir Dzhuvinov - * @version 2017-06-01 - */ -public class AAD { - - - /** - * Computes the Additional Authenticated Data (AAD) for the specified - * JWE header. - * - * @param jweHeader The JWE header. Must not be {@code null}. - * - * @return The AAD. - */ - public static byte[] compute(final JWEHeader jweHeader) { - - return compute(jweHeader.toBase64URL()); - } - - - /** - * Computes the Additional Authenticated Data (AAD) for the specified - * BASE64URL-encoded JWE header. - * - * @param encodedJWEHeader The BASE64URL-encoded JWE header. Must not - * be {@code null}. - * - * @return The AAD. - */ - public static byte[] compute(final Base64URL encodedJWEHeader) { - - return encodedJWEHeader.toString().getBytes(Charset.forName("ASCII")); - } - - - /** - * Computes the bit length of the specified Additional Authenticated - * Data (AAD). Used in AES/CBC/PKCS5Padding/HMAC-SHA2 encryption. - * - * @param aad The Additional Authenticated Data (AAD). Must not be - * {@code null}. - * - * @return The computed AAD bit length, as a 64 bit big-endian - * representation (8 byte array). - * - * @throws IntegerOverflowException On a integer overflow. - */ - public static byte[] computeLength(final byte[] aad) - throws IntegerOverflowException { - - final int bitLength = ByteUtils.safeBitLength(aad); - return ByteBuffer.allocate(8).putLong(bitLength).array(); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/AESCBC.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/AESCBC.java deleted file mode 100644 index 4e8766256..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/AESCBC.java +++ /dev/null @@ -1,432 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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.crypto.impl; - - -import java.nio.ByteBuffer; -import java.security.Provider; -import java.security.SecureRandom; -import java.util.Arrays; -import javax.crypto.Cipher; -import javax.crypto.SecretKey; -import javax.crypto.spec.IvParameterSpec; -import javax.crypto.spec.SecretKeySpec; - -import com.nimbusds.jose.JOSEException; -import com.nimbusds.jose.JWEHeader; -import com.nimbusds.jose.crypto.*; -import com.nimbusds.jose.crypto.utils.ConstantTimeUtils; -import com.nimbusds.jose.util.Base64URL; -import com.nimbusds.jose.util.ByteUtils; -import com.nimbusds.jose.util.StandardCharset; -import net.jcip.annotations.ThreadSafe; - - -/** - * AES/CBC/PKCS5Padding and AES/CBC/PKCS5Padding/HMAC-SHA2 encryption and - * decryption methods. This class is thread-safe. - * - *

Also supports the deprecated AES/CBC/HMAC encryption using a custom - * concat KDF (JOSE draft suite 08). - * - *

See RFC 7518 (JWA), section 5.2. - * - * @author Vladimir Dzhuvinov - * @author Axel Nennker - * @version 2018-01-04 - */ -@ThreadSafe -public class AESCBC { - - - /** - * The standard Initialisation Vector (IV) length (128 bits). - */ - public static final int IV_BIT_LENGTH = 128; - - - /** - * Generates a random 128 bit (16 byte) Initialisation Vector(IV) for - * use in AES-CBC encryption. - * - * @param randomGen The secure random generator to use. Must be - * correctly initialised and not {@code null}. - * - * @return The random 128 bit IV, as 16 byte array. - */ - public static byte[] generateIV(final SecureRandom randomGen) { - - byte[] bytes = new byte[ByteUtils.byteLength(IV_BIT_LENGTH)]; - randomGen.nextBytes(bytes); - return bytes; - } - - - /** - * Creates a new AES/CBC/PKCS5Padding cipher. - * - * @param secretKey The AES key. Must not be {@code null}. - * @param forEncryption If {@code true} creates an encryption cipher, - * else creates a decryption cipher. - * @param iv The initialisation vector (IV). Must not be - * {@code null}. - * @param provider The JCA provider, or {@code null} to use the - * default one. - * - * @return The AES/CBC/PKCS5Padding cipher. - */ - private static Cipher createAESCBCCipher(final SecretKey secretKey, - final boolean forEncryption, - final byte[] iv, - final Provider provider) - throws JOSEException { - - Cipher cipher; - - try { - cipher = CipherHelper.getInstance("AES/CBC/PKCS5Padding", provider); - - SecretKeySpec keyspec = new SecretKeySpec(secretKey.getEncoded(), "AES"); - - IvParameterSpec ivSpec = new IvParameterSpec(iv); - - if (forEncryption) { - - cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivSpec); - - } else { - - cipher.init(Cipher.DECRYPT_MODE, keyspec, ivSpec); - } - - } catch (Exception e) { - - throw new JOSEException(e.getMessage(), e); - } - - return cipher; - } - - - /** - * Encrypts the specified plain text using AES/CBC/PKCS5Padding. - * - * @param secretKey The AES key. Must not be {@code null}. - * @param iv The initialisation vector (IV). Must not be - * {@code null}. - * @param plainText The plain text. Must not be {@code null}. - * @param provider The JCA provider, or {@code null} to use the - * default one. - * - * @return The cipher text. - * - * @throws JOSEException If encryption failed. - */ - public static byte[] encrypt(final SecretKey secretKey, - final byte[] iv, - final byte[] plainText, - final Provider provider) - throws JOSEException { - - Cipher cipher = createAESCBCCipher(secretKey, true, iv, provider); - - try { - return cipher.doFinal(plainText); - - } catch (Exception e) { - - throw new JOSEException(e.getMessage(), e); - } - } - - - /** - * Encrypts the specified plain text using AES/CBC/PKCS5Padding/ - * HMAC-SHA2. - * - *

See RFC 7518 (JWA), section 5.2.2.1 - * - *

See draft-mcgrew-aead-aes-cbc-hmac-sha2-01 - * - * @param secretKey The secret key. Must be 256 or 512 bits long. - * Must not be {@code null}. - * @param iv The initialisation vector (IV). Must not be - * {@code null}. - * @param plainText The plain text. Must not be {@code null}. - * @param aad The additional authenticated data. Must not be - * {@code null}. - * @param ceProvider The JCA provider for the content encryption, or - * {@code null} to use the default one. - * @param macProvider The JCA provider for the MAC computation, or - * {@code null} to use the default one. - * - * @return The authenticated cipher text. - * - * @throws JOSEException If encryption failed. - */ - public static AuthenticatedCipherText encryptAuthenticated(final SecretKey secretKey, - final byte[] iv, - final byte[] plainText, - final byte[] aad, - final Provider ceProvider, - final Provider macProvider) - throws JOSEException { - - // Extract MAC + AES/CBC keys from input secret key - CompositeKey compositeKey = new CompositeKey(secretKey); - - // Encrypt plain text - byte[] cipherText = encrypt(compositeKey.getAESKey(), iv, plainText, ceProvider); - - // AAD length to 8 byte array - byte[] al = AAD.computeLength(aad); - - // Do MAC - int hmacInputLength = aad.length + iv.length + cipherText.length + al.length; - byte[] hmacInput = ByteBuffer.allocate(hmacInputLength).put(aad).put(iv).put(cipherText).put(al).array(); - byte[] hmac = HMAC.compute(compositeKey.getMACKey(), hmacInput, macProvider); - byte[] authTag = Arrays.copyOf(hmac, compositeKey.getTruncatedMACByteLength()); - - return new AuthenticatedCipherText(cipherText, authTag); - } - - - /** - * Encrypts the specified plain text using the deprecated concat KDF - * from JOSE draft suite 09. - * - * @param header The JWE header. Must not be {@code null}. - * @param secretKey The secret key. Must be 256 or 512 bits long. - * Must not be {@code null}. - * @param encryptedKey The encrypted key. Must not be {@code null}. - * @param iv The initialisation vector (IV). Must not be - * {@code null}. - * @param plainText The plain text. Must not be {@code null}. - * @param ceProvider The JCA provider for the content encryption, or - * {@code null} to use the default one. - * @param macProvider The JCA provider for the MAC computation, or - * {@code null} to use the default one. - * - * @return The authenticated cipher text. - * - * @throws JOSEException If encryption failed. - */ - public static AuthenticatedCipherText encryptWithConcatKDF(final JWEHeader header, - final SecretKey secretKey, - final Base64URL encryptedKey, - final byte[] iv, - final byte[] plainText, - final Provider ceProvider, - final Provider macProvider) - throws JOSEException { - - byte[] epu = null; - - if (header.getCustomParam("epu") instanceof String) { - - epu = new Base64URL((String)header.getCustomParam("epu")).decode(); - } - - byte[] epv = null; - - if (header.getCustomParam("epv") instanceof String) { - - epv = new Base64URL((String)header.getCustomParam("epv")).decode(); - } - - // Generate alternative CEK using concat-KDF - SecretKey altCEK = LegacyConcatKDF.generateCEK(secretKey, header.getEncryptionMethod(), epu, epv); - - byte[] cipherText = AESCBC.encrypt(altCEK, iv, plainText, ceProvider); - - // Generate content integrity key for HMAC - SecretKey cik = LegacyConcatKDF.generateCIK(secretKey, header.getEncryptionMethod(), epu, epv); - - String macInput = header.toBase64URL().toString() + "." + - encryptedKey.toString() + "." + - Base64URL.encode(iv).toString() + "." + - Base64URL.encode(cipherText); - - byte[] mac = HMAC.compute(cik, macInput.getBytes(StandardCharset.UTF_8), macProvider); - - return new AuthenticatedCipherText(cipherText, mac); - } - - - /** - * Decrypts the specified cipher text using AES/CBC/PKCS5Padding. - * - * @param secretKey The AES key. Must not be {@code null}. - * @param iv The initialisation vector (IV). Must not be - * {@code null}. - * @param cipherText The cipher text. Must not be {@code null}. - * @param provider The JCA provider, or {@code null} to use the - * default one. - * - * @return The decrypted plain text. - * - * @throws JOSEException If decryption failed. - */ - public static byte[] decrypt(final SecretKey secretKey, - final byte[] iv, - final byte[] cipherText, - final Provider provider) - throws JOSEException { - - Cipher cipher = createAESCBCCipher(secretKey, false, iv, provider); - - try { - return cipher.doFinal(cipherText); - - } catch (Exception e) { - - throw new JOSEException(e.getMessage(), e); - } - } - - - /** - * Decrypts the specified cipher text using AES/CBC/PKCS5Padding/ - * HMAC-SHA2. - * - *

See RFC 7518 (JWA), section 5.2.2.2 - * - *

See draft-mcgrew-aead-aes-cbc-hmac-sha2-01 - * - * @param secretKey The secret key. Must be 256 or 512 bits long. - * Must not be {@code null}. - * @param iv The initialisation vector (IV). Must not be - * {@code null}. - * @param cipherText The cipher text. Must not be {@code null}. - * @param aad The additional authenticated data. Must not be - * {@code null}. - * @param authTag The authentication tag. Must not be {@code null}. - * @param ceProvider The JCA provider for the content encryption, or - * {@code null} to use the default one. - * @param macProvider The JCA provider for the MAC computation, or - * {@code null} to use the default one. - * - * @return The decrypted plain text. - * - * @throws JOSEException If decryption failed. - */ - public static byte[] decryptAuthenticated(final SecretKey secretKey, - final byte[] iv, - final byte[] cipherText, - final byte[] aad, - final byte[] authTag, - final Provider ceProvider, - final Provider macProvider) - throws JOSEException { - - - // Extract MAC + AES/CBC keys from input secret key - CompositeKey compositeKey = new CompositeKey(secretKey); - - // AAD length to 8 byte array - byte[] al = AAD.computeLength(aad); - - // Check MAC - int hmacInputLength = aad.length + iv.length + cipherText.length + al.length; - byte[] hmacInput = ByteBuffer.allocate(hmacInputLength). - put(aad). - put(iv). - put(cipherText). - put(al). - array(); - byte[] hmac = HMAC.compute(compositeKey.getMACKey(), hmacInput, macProvider); - - byte[] expectedAuthTag = Arrays.copyOf(hmac, compositeKey.getTruncatedMACByteLength()); - - if (! ConstantTimeUtils.areEqual(expectedAuthTag, authTag)) { - throw new JOSEException("MAC check failed"); - } - - return decrypt(compositeKey.getAESKey(), iv, cipherText, ceProvider); - } - - - /** - * Decrypts the specified cipher text using the deprecated concat KDF - * from JOSE draft suite 09. - * - * @param header The JWE header. Must not be {@code null}. - * @param secretKey The secret key. Must be 256 or 512 bits long. - * Must not be {@code null}. - * @param encryptedKey The encrypted key. Must not be {@code null}. - * @param iv The initialisation vector (IV). Must not be - * {@code null}. - * @param cipherText The cipher text. Must not be {@code null}. - * @param authTag The authentication tag. Must not be {@code null}. - * @param ceProvider The JCA provider for the content encryption, or - * {@code null} to use the default one. - * @param macProvider The JCA provider for the MAC computation, or - * {@code null} to use the default one. - * - * @return The decrypted plain text. - * - * @throws JOSEException If decryption failed. - */ - public static byte[] decryptWithConcatKDF(final JWEHeader header, - final SecretKey secretKey, - final Base64URL encryptedKey, - final Base64URL iv, - final Base64URL cipherText, - final Base64URL authTag, - final Provider ceProvider, - final Provider macProvider) - throws JOSEException { - - byte[] epu = null; - - if (header.getCustomParam("epu") instanceof String) { - - epu = new Base64URL((String)header.getCustomParam("epu")).decode(); - } - - byte[] epv = null; - - if (header.getCustomParam("epv") instanceof String) { - - epv = new Base64URL((String)header.getCustomParam("epv")).decode(); - } - - SecretKey cik = LegacyConcatKDF.generateCIK(secretKey, header.getEncryptionMethod(), epu, epv); - - String macInput = header.toBase64URL().toString() + "." + - encryptedKey.toString() + "." + - iv.toString() + "." + - cipherText.toString(); - - byte[] mac = HMAC.compute(cik, macInput.getBytes(StandardCharset.UTF_8), macProvider); - - if (! ConstantTimeUtils.areEqual(authTag.decode(), mac)) { - throw new JOSEException("MAC check failed"); - } - - SecretKey cekAlt = LegacyConcatKDF.generateCEK(secretKey, header.getEncryptionMethod(), epu, epv); - - return AESCBC.decrypt(cekAlt, iv.decode(), cipherText.decode(), ceProvider); - } - - - /** - * Prevents public instantiation. - */ - private AESCBC() { } -} \ No newline at end of file diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/AESCryptoProvider.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/AESCryptoProvider.java deleted file mode 100644 index 898e43906..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/AESCryptoProvider.java +++ /dev/null @@ -1,166 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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.crypto.impl; - - -import java.util.*; -import javax.crypto.SecretKey; - -import com.nimbusds.jose.EncryptionMethod; -import com.nimbusds.jose.JWEAlgorithm; -import com.nimbusds.jose.KeyLengthException; -import com.nimbusds.jose.util.ByteUtils; - - -/** - * The base abstract class for AES and AES GCM key wrap encrypters and - * decrypters of {@link com.nimbusds.jose.JWEObject JWE objects}. - * - *

Supports the following key management algorithms: - * - *

    - *
  • {@link com.nimbusds.jose.JWEAlgorithm#A128KW} - *
  • {@link com.nimbusds.jose.JWEAlgorithm#A192KW} - *
  • {@link com.nimbusds.jose.JWEAlgorithm#A256KW} - *
  • {@link com.nimbusds.jose.JWEAlgorithm#A128GCMKW} - *
  • {@link com.nimbusds.jose.JWEAlgorithm#A192GCMKW} - *
  • {@link com.nimbusds.jose.JWEAlgorithm#A256GCMKW} - *
- * - *

Supports the following content encryption algorithms: - * - *

    - *
  • {@link com.nimbusds.jose.EncryptionMethod#A128CBC_HS256} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A192CBC_HS384} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A256CBC_HS512} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A128GCM} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A192GCM} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A256GCM} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A128CBC_HS256_DEPRECATED} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A256CBC_HS512_DEPRECATED} - *
- * - * @author Melisa Halsband - * @author Vladimir Dzhuvinov - * @version 2015-06-29 - */ -public abstract class AESCryptoProvider extends BaseJWEProvider { - - - /** - * The supported JWE algorithms by the AES crypto provider class. - */ - public static final Set SUPPORTED_ALGORITHMS; - - - /** - * The supported encryption methods by the AES crypto provider class. - */ - public static final Set SUPPORTED_ENCRYPTION_METHODS = ContentCryptoProvider.SUPPORTED_ENCRYPTION_METHODS; - - - /** - * The JWE algorithms compatible with each key size in bits. - */ - public static final Map> COMPATIBLE_ALGORITHMS; - - - static { - Set algs = new LinkedHashSet<>(); - algs.add(JWEAlgorithm.A128KW); - algs.add(JWEAlgorithm.A192KW); - algs.add(JWEAlgorithm.A256KW); - algs.add(JWEAlgorithm.A128GCMKW); - algs.add(JWEAlgorithm.A192GCMKW); - algs.add(JWEAlgorithm.A256GCMKW); - SUPPORTED_ALGORITHMS = Collections.unmodifiableSet(algs); - - Map> algsMap = new HashMap<>(); - Set bit128Algs = new HashSet<>(); - Set bit192Algs = new HashSet<>(); - Set bit256Algs = new HashSet<>(); - bit128Algs.add(JWEAlgorithm.A128GCMKW); - bit128Algs.add(JWEAlgorithm.A128KW); - bit192Algs.add(JWEAlgorithm.A192GCMKW); - bit192Algs.add(JWEAlgorithm.A192KW); - bit256Algs.add(JWEAlgorithm.A256GCMKW); - bit256Algs.add(JWEAlgorithm.A256KW); - algsMap.put(128,Collections.unmodifiableSet(bit128Algs)); - algsMap.put(192,Collections.unmodifiableSet(bit192Algs)); - algsMap.put(256,Collections.unmodifiableSet(bit256Algs)); - COMPATIBLE_ALGORITHMS = Collections.unmodifiableMap(algsMap); - } - - - /** - * The Key Encryption Key (KEK). - */ - private final SecretKey kek; - - - /** - * Returns the compatible JWE algorithms for the specified Key - * Encryption Key (CEK) length. - * - * @param kekLength The KEK length in bits. - * - * @return The compatible JWE algorithms. - * - * @throws KeyLengthException If the KEK length is not compatible. - */ - private static Set getCompatibleJWEAlgorithms(final int kekLength) - throws KeyLengthException { - - Set algs = COMPATIBLE_ALGORITHMS.get(kekLength); - - if (algs == null) { - throw new KeyLengthException("The Key Encryption Key length must be 128 bits (16 bytes), 192 bits (24 bytes) or 256 bits (32 bytes)"); - } - - return algs; - } - - - /** - * Creates a new AES encryption / decryption provider. - * - * @param kek The Key Encryption Key. Must be 128 bits (16 bytes), 192 - * bits (24 bytes) or 256 bits (32 bytes). Must not be - * {@code null}. - * - * @throws KeyLengthException If the KEK length is invalid. - */ - protected AESCryptoProvider(final SecretKey kek) - throws KeyLengthException { - - super(getCompatibleJWEAlgorithms(ByteUtils.bitLength(kek.getEncoded())), ContentCryptoProvider.SUPPORTED_ENCRYPTION_METHODS); - - this.kek = kek; - } - - - /** - * Gets the Key Encryption Key (KEK). - * - * @return The Key Encryption Key. - */ - public SecretKey getKey() { - - return kek; - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/AESGCM.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/AESGCM.java deleted file mode 100644 index e2ae45540..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/AESGCM.java +++ /dev/null @@ -1,310 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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.crypto.impl; - - -import java.security.*; -import java.security.spec.InvalidParameterSpecException; -import javax.crypto.*; -import javax.crypto.spec.GCMParameterSpec; - -import com.nimbusds.jose.JOSEException; -import com.nimbusds.jose.util.ByteUtils; -import com.nimbusds.jose.util.Container; -import com.nimbusds.jose.util.KeyUtils; -import net.jcip.annotations.ThreadSafe; - - -/** - * AES/GSM/NoPadding encryption and decryption methods. Falls back to the - * BouncyCastle.org provider on Java 6. This class is thread-safe. - * - *

See RFC 7518 (JWA), section 5.1 and appendix 3. - * - * @author Vladimir Dzhuvinov - * @author Axel Nennker - * @author Dimitar A. Stoikov - * @version 2018-01-11 - */ -@ThreadSafe -public class AESGCM { - - - /** - * The standard Initialisation Vector (IV) length (96 bits). - */ - public static final int IV_BIT_LENGTH = 96; - - - /** - * The standard authentication tag length (128 bits). - */ - public static final int AUTH_TAG_BIT_LENGTH = 128; - - - /** - * Generates a random 96 bit (12 byte) Initialisation Vector(IV) for - * use in AES-GCM encryption. - * - *

See RFC 7518 (JWA), section 5.3. - * - * @param randomGen The secure random generator to use. Must be - * correctly initialised and not {@code null}. - * - * @return The random 96 bit IV, as 12 byte array. - */ - public static byte[] generateIV(final SecureRandom randomGen) { - - byte[] bytes = new byte[IV_BIT_LENGTH / 8]; - randomGen.nextBytes(bytes); - return bytes; - } - - - /** - * Encrypts the specified plain text using AES/GCM/NoPadding. - * - * @param secretKey The AES key. Must not be {@code null}. - * @param plainText The plain text. Must not be {@code null}. - * @param ivContainer The initialisation vector (IV). Must not be - * {@code null}. This is both input and output - * parameter. On input, it carries externally - * generated IV; on output, it carries the IV the - * cipher actually used. JCA/JCE providers may - * prefer to use an internally generated IV, e.g. as - * described in - * NIST - * Special Publication 800-38D . - * @param authData The authenticated data. Must not be {@code null}. - * - * @return The authenticated cipher text. - * - * @throws JOSEException If encryption failed. - */ - public static AuthenticatedCipherText encrypt(final SecretKey secretKey, - final Container ivContainer, - final byte[] plainText, - final byte[] authData, - final Provider provider) - throws JOSEException { - - // Key alg must be "AES" - final SecretKey aesKey = KeyUtils.toAESKey(secretKey); - - Cipher cipher; - - byte[] iv = ivContainer.get(); - - try { - if (provider != null) { - cipher = Cipher.getInstance("AES/GCM/NoPadding", provider); - } else { - cipher = Cipher.getInstance("AES/GCM/NoPadding"); - } - - GCMParameterSpec gcmSpec = new GCMParameterSpec(AUTH_TAG_BIT_LENGTH, iv); - cipher.init(Cipher.ENCRYPT_MODE, aesKey, gcmSpec); - - } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException e) { - - throw new JOSEException("Couldn't create AES/GCM/NoPadding cipher: " + e.getMessage(), e); - - } catch (NoClassDefFoundError e) { - // We have Java 6, GCMParameterSpec not available, - // switch to BouncyCastle API - return LegacyAESGCM.encrypt(aesKey, iv, plainText, authData); - } - - cipher.updateAAD(authData); - - byte[] cipherOutput; - - try { - cipherOutput = cipher.doFinal(plainText); - - } catch (IllegalBlockSizeException | BadPaddingException e) { - - throw new JOSEException("Couldn't encrypt with AES/GCM/NoPadding: " + e.getMessage(), e); - } - - final int tagPos = cipherOutput.length - ByteUtils.byteLength(AUTH_TAG_BIT_LENGTH); - - byte[] cipherText = ByteUtils.subArray(cipherOutput, 0, tagPos); - byte[] authTag = ByteUtils.subArray(cipherOutput, tagPos, ByteUtils.byteLength(AUTH_TAG_BIT_LENGTH)); - - // retrieve the actual IV used by the cipher -- it may be internally-generated. - ivContainer.set(actualIVOf(cipher)); - - return new AuthenticatedCipherText(cipherText, authTag); - } - - - /** - * Retrieves the actual algorithm parameters and validates them. - * - * @param cipher The cipher to interrogate for the parameters it - * actually used. - * - * @return The IV used by the specified cipher. - * - * @throws JOSEException If retrieval of the algorithm parameters from - * the cipher failed, or the parameters are - * deemed unusable. - * - * @see {@link #actualParamsOf(Cipher)} - * @see #validate(byte[], int) - */ - private static byte[] actualIVOf(final Cipher cipher) - throws JOSEException { - - GCMParameterSpec actualParams = actualParamsOf(cipher); - - byte[] iv = actualParams.getIV(); - int tLen = actualParams.getTLen(); - - validate(iv, tLen); - - return iv; - } - - - /** - * Validates the specified IV and authentication tag according to the - * AES GCM requirements in - * JWA RFC. - * - * @param iv The IV to check for compliance. - * @param authTagLength The authentication tag length to check for - * compliance. - * - * @throws JOSEException If the parameters don't match the JWA - * requirements. - * - * @see #IV_BIT_LENGTH - * @see #AUTH_TAG_BIT_LENGTH - */ - private static void validate(final byte[] iv, final int authTagLength) - throws JOSEException { - - if (ByteUtils.safeBitLength(iv) != IV_BIT_LENGTH) { - throw new JOSEException(String.format("IV length of %d bits is required, got %d", IV_BIT_LENGTH, ByteUtils.safeBitLength(iv))); - } - - if (authTagLength != AUTH_TAG_BIT_LENGTH) { - throw new JOSEException(String.format("Authentication tag length of %d bits is required, got %d", AUTH_TAG_BIT_LENGTH, authTagLength)); - } - } - - - /** - * Retrieves the actual AES GCM parameters used by the specified - * cipher. - * - * @param cipher The cipher to interrogate. Non-{@code null}. - * - * @return The AES GCM parameters. Non-{@code null}. - * - * @throws JOSEException If the parameters cannot be retrieved, are - * uninitialized, or are not in the correct form. We want to have the - * actual parameters used by the cipher and not rely on the assumption - * that they were the same as those we supplied it with. If at runtime - * the assumption is incorrect, the ciphertext would not be - * decryptable. - */ - private static GCMParameterSpec actualParamsOf(final Cipher cipher) - throws JOSEException { - - AlgorithmParameters algorithmParameters = cipher.getParameters(); - - if (algorithmParameters == null) { - throw new JOSEException("AES GCM ciphers are expected to make use of algorithm parameters"); - } - - try { - // Note: GCMParameterSpec appears in Java 7 - return algorithmParameters.getParameterSpec(GCMParameterSpec.class); - } catch (InvalidParameterSpecException shouldNotHappen) { - throw new JOSEException(shouldNotHappen.getMessage(), shouldNotHappen); - } - } - - - /** - * Decrypts the specified cipher text using AES/GCM/NoPadding. - * - * @param secretKey The AES key. Must not be {@code null}. - * @param iv The initialisation vector (IV). Must not be - * {@code null}. - * @param cipherText The cipher text. Must not be {@code null}. - * @param authData The authenticated data. Must not be {@code null}. - * @param authTag The authentication tag. Must not be {@code null}. - * - * @return The decrypted plain text. - * - * @throws JOSEException If decryption failed. - */ - public static byte[] decrypt(final SecretKey secretKey, - final byte[] iv, - final byte[] cipherText, - final byte[] authData, - final byte[] authTag, - final Provider provider) - throws JOSEException { - - // Key alg must be "AES" - final SecretKey aesKey = KeyUtils.toAESKey(secretKey); - - Cipher cipher; - - try { - if (provider != null) { - cipher = Cipher.getInstance("AES/GCM/NoPadding", provider); - } else { - cipher = Cipher.getInstance("AES/GCM/NoPadding"); - } - - GCMParameterSpec gcmSpec = new GCMParameterSpec(AUTH_TAG_BIT_LENGTH, iv); - cipher.init(Cipher.DECRYPT_MODE, aesKey, gcmSpec); - - } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException e) { - - throw new JOSEException("Couldn't create AES/GCM/NoPadding cipher: " + e.getMessage(), e); - - } catch (NoClassDefFoundError e) { - // We have Java 6, GCMParameterSpec not available, - // switch to BouncyCastle API - return LegacyAESGCM.decrypt(aesKey, iv, cipherText, authData, authTag); - } - - cipher.updateAAD(authData); - - try { - return cipher.doFinal(ByteUtils.concat(cipherText, authTag)); - - } catch (IllegalBlockSizeException | BadPaddingException e) { - - throw new JOSEException("AES/GCM/NoPadding decryption failed: " + e.getMessage(), e); - } - } - - - /** - * Prevents public instantiation. - */ - private AESGCM() { } -} \ No newline at end of file diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/AESGCMKW.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/AESGCMKW.java deleted file mode 100644 index 72a870bba..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/AESGCMKW.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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.crypto.impl; - - -import java.security.Provider; -import javax.crypto.SecretKey; -import javax.crypto.spec.SecretKeySpec; - -import com.nimbusds.jose.JOSEException; -import com.nimbusds.jose.KeyLengthException; -import com.nimbusds.jose.util.ByteUtils; -import com.nimbusds.jose.util.Container; -import net.jcip.annotations.ThreadSafe; - - -/** - * AES GCM methods for Content Encryption Key (CEK) encryption and - * decryption. This class is thread-safe. - * - *

See RFC 7518 (JWA), section 4.7. - * - * @author Melisa Halsband - * @author Vladimir Dzhuvinov - * @version 2017-06-01 - */ -@ThreadSafe -public class AESGCMKW { - - - /** - * Encrypts the specified Content Encryption Key (CEK). - * - * @param cek The Content Encryption Key (CEK) to encrypt. Must - * not be {@code null}. - * @param iv The initialisation vector (IV). Must not be - * {@code null}. The contained IV must not be - * {@code null} either. - * @param kek The AES Key Encryption Key (KEK). Must not be - * {@code null}. - * @param provider The specific JCA provider to use, {@code null} - * implies the default system one. - * - * @return The encrypted Content Encryption Key (CEK). - * - * @throws JOSEException If encryption failed. - */ - public static AuthenticatedCipherText encryptCEK(final SecretKey cek, - final Container iv, - final SecretKey kek, - Provider provider) - throws JOSEException { - - return AESGCM.encrypt(kek, iv, cek.getEncoded(), new byte[0], provider); - } - - - /** - * Decrypts the specified encrypted Content Encryption Key (CEK). - * - * @param kek The AES Key Encription Key. Must not be - * {@code null}. - * @param iv The initialisation vector (IV). Must not be - * {@code null}. - * @param authEncrCEK The encrypted Content Encryption Key (CEK) to - * decrypt and authentication tag. Must not be - * {@code null}. - * @param provider The JCA provider, or {@code null} to use the - * default one. - * - * @return The decrypted Content Encryption Key (CEK). - * - * @throws JOSEException If decryption failed. - */ - public static SecretKey decryptCEK(final SecretKey kek, - final byte[] iv, - final AuthenticatedCipherText authEncrCEK, - final int keyLength, - final Provider provider) - throws JOSEException { - - byte[] keyBytes = AESGCM.decrypt(kek, iv, authEncrCEK.getCipherText(), new byte[0], authEncrCEK.getAuthenticationTag(), provider); - - if (ByteUtils.safeBitLength(keyBytes) != keyLength) { - - throw new KeyLengthException("CEK key length mismatch: " + ByteUtils.safeBitLength(keyBytes) + " != " + keyLength); - } - - return new SecretKeySpec(keyBytes, "AES"); - } - - - /** - * Prevents public instantiation. - */ - private AESGCMKW() { } -} \ No newline at end of file diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/AESKW.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/AESKW.java deleted file mode 100644 index cd119d3b7..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/AESKW.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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.crypto.impl; - - -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.Provider; -import javax.crypto.Cipher; -import javax.crypto.IllegalBlockSizeException; -import javax.crypto.NoSuchPaddingException; -import javax.crypto.SecretKey; - -import com.nimbusds.jose.JOSEException; -import com.nimbusds.jose.util.KeyUtils; -import net.jcip.annotations.ThreadSafe; - - -/** - * AES key Wrapping methods for Content Encryption Key (CEK) encryption and - * decryption. This class is thread-safe. - * - *

See RFC 7518 (JWA), section 4.4. - * - * @author Melisa Halsband - * @author Vladimir Dzhuvinov - * @version 2018-03-09 - */ -@ThreadSafe -public class AESKW { - - - /** - * Wraps the specified Content Encryption Key (CEK). - * - * @param cek The Content Encryption Key (CEK) to wrap. Must not - * be {@code null}. - * @param kek The AES Key Encryption Key (KEK) (wrapping key). - * Must not be {@code null}. - * @param provider The specific JCA provider to use, {@code null} - * implies the default system one. - * - * @return The wrapped Content Encryption Key (CEK). - * - * @throws JOSEException If wrapping failed. - */ - public static byte[] wrapCEK(final SecretKey cek, - final SecretKey kek, - final Provider provider) - throws JOSEException { - - try { - Cipher cipher; - - if (provider != null) { - cipher = Cipher.getInstance("AESWrap", provider); - } else { - cipher = Cipher.getInstance("AESWrap"); - } - - cipher.init(Cipher.WRAP_MODE, kek); - return cipher.wrap(cek); - - } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException e) { - throw new JOSEException("Couldn't wrap AES key: " + e.getMessage(), e); - } - } - - - /** - * Unwraps the specified encrypted Content Encryption Key (CEK). - * - * @param kek The AES Key Encryption Key (KEK) (wrapping key). - * Must not be {@code null}. - * @param encryptedCEK The wrapped Content Encryption Key (CEK) with - * authentication tag. Must not be {@code null}. - * @param provider The specific JCA provider to use, {@code null} - * implies the default system one. - * - * @return The unwrapped Content Encryption Key (CEK). - * - * @throws JOSEException If unwrapping failed. - */ - public static SecretKey unwrapCEK(final SecretKey kek, - final byte[] encryptedCEK, - final Provider provider) - throws JOSEException { - - try { - Cipher cipher; - - if (provider != null) { - cipher = Cipher.getInstance("AESWrap", provider); - } else { - cipher = Cipher.getInstance("AESWrap"); - } - - cipher.init(Cipher.UNWRAP_MODE, KeyUtils.toAESKey(kek)); // Make sure key alg is "AES" - return (SecretKey)cipher.unwrap(encryptedCEK, "AES", Cipher.SECRET_KEY); - - } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException e) { - - throw new JOSEException("Couldn't unwrap AES key: " + e.getMessage(), e); - } - } - - - /** - * Prevents public instantiation. - */ - private AESKW() { - } -} \ No newline at end of file diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/AlgorithmParametersHelper.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/AlgorithmParametersHelper.java deleted file mode 100644 index 1c12d675f..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/AlgorithmParametersHelper.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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.crypto.impl; - - -import java.security.AlgorithmParameters; -import java.security.NoSuchAlgorithmException; -import java.security.Provider; - - -/** - * Utility for creating {@link java.security.AlgorithmParameters} objects with - * an optional JCA provider. - * - * @author Justin Richer - */ -public class AlgorithmParametersHelper { - - - /** - * Creates a new {@link java.security.AlgorithmParameters} instance. - * - * @param name The name of the requested algorithm. Must not be - * {@code null}. - * @param provider The JCA provider, or {@code null} to use the default - * one. - * - * @return The AlgorithmParameters instance. - * - * @throws NoSuchAlgorithmException If an AlgorithmParameterGeneratorSpi - * implementation for the specified - * algorithm is not available from the - * specified Provider object. - */ - public static AlgorithmParameters getInstance(final String name, final Provider provider) - throws NoSuchAlgorithmException { - - if (provider == null) { - return AlgorithmParameters.getInstance(name); - } else { - return AlgorithmParameters.getInstance(name, provider); - } - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/AlgorithmSupportMessage.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/AlgorithmSupportMessage.java deleted file mode 100644 index 856d61471..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/AlgorithmSupportMessage.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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.crypto.impl; - - -import java.util.Collection; - -import com.nimbusds.jose.EncryptionMethod; -import com.nimbusds.jose.JWEAlgorithm; -import com.nimbusds.jose.JWSAlgorithm; -import com.nimbusds.jose.jwk.Curve; - - -/** - * Algorithm support messages, intended for JOSE exceptions. - * - * @author Vladimir Dzhuvinov - * @version 2015-05-20 - */ -public class AlgorithmSupportMessage { - - - /** - * Itemises the specified collection to human readable string. - * - * @param collection The collection, with valid {@code toString} - * methods. Must not be {@code null}. - * - * @return The string. - */ - private static String itemize(final Collection collection) { - - StringBuilder sb = new StringBuilder(); - - Object[] items = collection.toArray(); - - for (int i=0; i < items.length; i++) { - - if (i == 0) { - // no delimiter - } else if (i < items.length - 1) { - sb.append(", "); - } else if (i == items.length - 1) { - sb.append(" or "); - } - - sb.append(items[i].toString()); - } - - return sb.toString(); - } - - - /** - * Returns a message that the specified JWS algorithm is not supported. - * - * @param unsupported The unsupported JWS algorithm. Must not be - * {@code null}. - * @param supported The supported JWS algorithms. Must not be - * {@code null}. - * - * @return The message. - */ - public static String unsupportedJWSAlgorithm(final JWSAlgorithm unsupported, - final Collection supported) { - - return "Unsupported JWS algorithm " + unsupported + ", must be " + itemize(supported); - } - - - /** - * Returns a message that the specified JWE algorithm is not supported. - * - * @param unsupported The unsupported JWE algorithm. Must not be - * {@code null}. - * @param supported The supported JWE algorithms. Must not be - * {@code null}. - * - * @return The message. - */ - public static String unsupportedJWEAlgorithm(final JWEAlgorithm unsupported, - final Collection supported) { - - return "Unsupported JWE algorithm " + unsupported + ", must be " + itemize(supported); - } - - - /** - * Returns a message that the specified JWE encryption method is not - * supported. - * - * @param unsupported The unsupported JWE encryption method. Must not - * be {@code null}. - * @param supported The supported JWE encryption methods. Must not be - * {@code null}. - * - * @return The message. - */ - public static String unsupportedEncryptionMethod(final EncryptionMethod unsupported, - final Collection supported) { - - return "Unsupported JWE encryption method " + unsupported + ", must be " + itemize(supported); - } - - - /** - * Returns a message that the specified elliptic curve is not - * supported. - * - * @param unsupported The unsupported elliptic curve. Must not be - * {@code null}. - * @param supported The supported elliptic curves. Must not be - * {@code null}. - * - * @return The message. - */ - public static String unsupportedEllipticCurve(final Curve unsupported, - final Collection supported) { - - return "Unsupported elliptic curve " + unsupported + ", must be " + itemize(supported); - } - - - /** - * Prevents public instantiation. - */ - private AlgorithmSupportMessage() { - - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/AuthenticatedCipherText.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/AuthenticatedCipherText.java deleted file mode 100644 index 1951b4584..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/AuthenticatedCipherText.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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.crypto.impl; - - -import net.jcip.annotations.Immutable; - - -/** - * Authenticated cipher text. This class is immutable. - * - * @author Vladimir Dzhuvinov - * @version 2013-05-06 - */ -@Immutable -public final class AuthenticatedCipherText { - - - /** - * The cipher text. - */ - private final byte[] cipherText; - - - /** - * The authentication tag. - */ - private final byte[] authenticationTag; - - - /** - * Creates a new authenticated cipher text. - * - * @param cipherText The cipher text. Must not be {@code null}. - * @param authenticationTag The authentication tag. Must not be - * {@code null}. - */ - public AuthenticatedCipherText(final byte[] cipherText, final byte[] authenticationTag) { - - if (cipherText == null) - throw new IllegalArgumentException("The cipher text must not be null"); - - this.cipherText = cipherText; - - - if (authenticationTag == null) - throw new IllegalArgumentException("The authentication tag must not be null"); - - this.authenticationTag = authenticationTag; - } - - - /** - * Gets the cipher text. - * - * @return The cipher text. - */ - public byte[] getCipherText() { - - return cipherText; - } - - - /** - * Gets the authentication tag. - * - * @return The authentication tag. - */ - public byte[] getAuthenticationTag() { - - return authenticationTag; - } -} \ No newline at end of file diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/BaseJWEProvider.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/BaseJWEProvider.java deleted file mode 100644 index 87c8e0561..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/BaseJWEProvider.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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.crypto.impl; - - -import java.util.Collections; -import java.util.Set; - -import com.nimbusds.jose.EncryptionMethod; -import com.nimbusds.jose.JWEAlgorithm; -import com.nimbusds.jose.JWEProvider; -import com.nimbusds.jose.jca.JWEJCAContext; - - -/** - * The base abstract class for JSON Web Encryption (JWE) encrypters and - * decrypters. - * - * @author Vladimir Dzhuvinov - * @version 2015-11-16 - */ -abstract class BaseJWEProvider implements JWEProvider { - - - /** - * The supported algorithms by the JWE provider instance. - */ - private final Set algs; - - - /** - * The supported encryption methods by the JWE provider instance. - */ - private final Set encs; - - - /** - * The JWE JCA context. - */ - private final JWEJCAContext jcaContext = new JWEJCAContext(); - - - /** - * Creates a new base JWE provider. - * - * @param algs The supported algorithms by the JWE provider instance. - * Must not be {@code null}. - * @param encs The supported encryption methods by the JWE provider - * instance. Must not be {@code null}. - */ - public BaseJWEProvider(final Set algs, - final Set encs) { - - if (algs == null) { - throw new IllegalArgumentException("The supported JWE algorithm set must not be null"); - } - - this.algs = Collections.unmodifiableSet(algs); - - - if (encs == null) { - throw new IllegalArgumentException("The supported encryption methods must not be null"); - } - - this.encs = encs; - } - - - @Override - public Set supportedJWEAlgorithms() { - - return algs; - } - - - @Override - public Set supportedEncryptionMethods() { - - return encs; - } - - - @Override - public JWEJCAContext getJCAContext() { - - return jcaContext; - } -} - diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/BaseJWSProvider.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/BaseJWSProvider.java deleted file mode 100644 index 9ac5e8a6a..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/BaseJWSProvider.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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.crypto.impl; - - -import java.util.Collections; -import java.util.Set; - -import com.nimbusds.jose.JWSAlgorithm; -import com.nimbusds.jose.JWSProvider; -import com.nimbusds.jose.jca.JCAContext; - - -/** - * The base abstract class for JSON Web Signature (JWS) signers and verifiers. - * - * @author Vladimir Dzhuvinov - * @version 2015-11-16 - */ -public abstract class BaseJWSProvider implements JWSProvider { - - - /** - * The supported algorithms by the JWS provider instance. - */ - private final Set algs; - - - /** - * The JCA context. - */ - private final JCAContext jcaContext = new JCAContext(); - - - /** - * Creates a new base JWS provider. - * - * @param algs The supported algorithms by the JWS provider instance. - * Must not be {@code null}. - */ - public BaseJWSProvider(final Set algs) { - - if (algs == null) { - throw new IllegalArgumentException("The supported JWS algorithm set must not be null"); - } - - this.algs = Collections.unmodifiableSet(algs); - } - - - @Override - public Set supportedJWSAlgorithms() { - - return algs; - } - - - @Override - public JCAContext getJCAContext() { - - return jcaContext; - } -} - diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/CipherHelper.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/CipherHelper.java deleted file mode 100644 index dae147013..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/CipherHelper.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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.crypto.impl; - - -import java.security.NoSuchAlgorithmException; -import java.security.Provider; -import javax.crypto.Cipher; -import javax.crypto.NoSuchPaddingException; - -import net.jcip.annotations.ThreadSafe; - - -/** - * Helper utilities for instantiating ciphers. - * - * @author Cedric Staub - * @version 2014-01-22 - */ -@ThreadSafe -public class CipherHelper { - - - /** - * Instantiates a cipher with an (optional) JCA provider. - * - * @param name The name of the cipher. Must not be {@code null}. - * @param provider The JCA provider, or {@code null} to use the default - * one. - */ - public static Cipher getInstance(String name, Provider provider) - throws NoSuchAlgorithmException, NoSuchPaddingException { - - if (provider == null) { - return Cipher.getInstance(name); - } else { - return Cipher.getInstance(name, provider); - } - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/CompositeKey.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/CompositeKey.java deleted file mode 100644 index 0f599b2bf..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/CompositeKey.java +++ /dev/null @@ -1,156 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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.crypto.impl; - - -import javax.crypto.SecretKey; -import javax.crypto.spec.SecretKeySpec; - -import com.nimbusds.jose.KeyLengthException; -import net.jcip.annotations.Immutable; - - -/** - * Composite key used in AES/CBC/PKCS5Padding/HMAC-SHA2 encryption. This class - * is immutable. - * - *

See RFC 7518 (JWA), section 5.2. - * - *

See draft-mcgrew-aead-aes-cbc-hmac-sha2-01 - * - * @author Vladimir Dzhuvinov - * @version 2015-06-29 - */ -@Immutable -public final class CompositeKey { - - - /** - * The input key. - */ - private final SecretKey inputKey; - - - /** - * The extracted MAC key. - */ - private final SecretKey macKey; - - - /** - * The extracted AES key. - */ - private final SecretKey encKey; - - - /** - * The expected truncated MAC output length. - */ - private final int truncatedMacLength; - - - /** - * Creates a new composite key from the specified secret key. - * - * @param inputKey The input key. Must be 256, 384 or 512 bits long. - * Must not be {@code null}. - * - * @throws KeyLengthException If the input key length is not supported. - */ - public CompositeKey(final SecretKey inputKey) - throws KeyLengthException { - - this.inputKey = inputKey; - - byte[] secretKeyBytes = inputKey.getEncoded(); - - if (secretKeyBytes.length == 32) { - - // AES_128_CBC_HMAC_SHA_256 - // 256 bit key -> 128 bit MAC key + 128 bit AES key - macKey = new SecretKeySpec(secretKeyBytes, 0, 16, "HMACSHA256"); - encKey = new SecretKeySpec(secretKeyBytes, 16, 16, "AES"); - truncatedMacLength = 16; - - } else if (secretKeyBytes.length == 48) { - - // AES_192_CBC_HMAC_SHA_384 - // 384 bit key -> 129 bit MAC key + 192 bit AES key - macKey = new SecretKeySpec(secretKeyBytes, 0, 24, "HMACSHA384"); - encKey = new SecretKeySpec(secretKeyBytes, 24, 24, "AES"); - truncatedMacLength = 24; - - - } else if (secretKeyBytes.length == 64) { - - // AES_256_CBC_HMAC_SHA_512 - // 512 bit key -> 256 bit MAC key + 256 bit AES key - macKey = new SecretKeySpec(secretKeyBytes, 0, 32, "HMACSHA512"); - encKey = new SecretKeySpec(secretKeyBytes, 32, 32, "AES"); - truncatedMacLength = 32; - - } else { - - throw new KeyLengthException("Unsupported AES/CBC/PKCS5Padding/HMAC-SHA2 key length, must be 256, 384 or 512 bits"); - } - } - - - /** - * Gets the input key. - * - * @return The input key. - */ - public SecretKey getInputKey() { - - return inputKey; - } - - - /** - * Gets the extracted MAC key. - * - * @return The extracted MAC key. - */ - public SecretKey getMACKey() { - - return macKey; - } - - - /** - * Gets the expected truncated MAC length. - * - * @return The expected truncated MAC length, in bytes. - */ - public int getTruncatedMACByteLength() { - - return truncatedMacLength; - } - - - /** - * Gets the extracted encryption key. - * - * @return The extracted encryption key. - */ - public SecretKey getAESKey() { - - return encKey; - } -} \ No newline at end of file diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/ConcatKDF.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/ConcatKDF.java deleted file mode 100644 index 94cdebb9f..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/ConcatKDF.java +++ /dev/null @@ -1,312 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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.crypto.impl; - - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.security.Provider; -import javax.crypto.SecretKey; -import javax.crypto.spec.SecretKeySpec; - -import com.nimbusds.jose.JOSEException; -import com.nimbusds.jose.jca.JCAAware; -import com.nimbusds.jose.jca.JCAContext; -import com.nimbusds.jose.util.Base64URL; -import com.nimbusds.jose.util.ByteUtils; -import com.nimbusds.jose.util.IntegerUtils; -import com.nimbusds.jose.util.StandardCharset; -import net.jcip.annotations.ThreadSafe; - - -/** - * Concatenation Key Derivation Function (KDF). This class is thread-safe. - * - *

See NIST.800-56A. - * - * @author Vladimir Dzhuvinov - * @version 2017-06-01 - */ -@ThreadSafe -public class ConcatKDF implements JCAAware { - - - /** - * The JCA name of the hash algorithm. - */ - private final String jcaHashAlg; - - - /** - * The JCA context.. - */ - private final JCAContext jcaContext = new JCAContext(); - - - /** - * Creates a new concatenation Key Derivation Function (KDF) with the - * specified hash algorithm. - * - * @param jcaHashAlg The JCA name of the hash algorithm. Must be - * supported and not {@code null}. - */ - public ConcatKDF(final String jcaHashAlg) { - - if (jcaHashAlg == null) { - throw new IllegalArgumentException("The JCA hash algorithm must not be null"); - } - - this.jcaHashAlg = jcaHashAlg; - } - - - /** - * Returns the JCA name of the hash algorithm. - * - * @return The JCA name of the hash algorithm. - */ - public String getHashAlgorithm() { - - return jcaHashAlg; - } - - - @Override - public JCAContext getJCAContext() { - - return jcaContext; - } - - - /** - * Derives a key from the specified inputs. - * - * @param sharedSecret The shared secret. Must not be {@code null}. - * @param keyLengthBits The length of the key to derive, in bits. - * @param otherInfo Other info, {@code null} if not specified. - * - * @return The derived key, with algorithm set to "AES". - * - * @throws JOSEException If the key derivation failed. - */ - public SecretKey deriveKey(final SecretKey sharedSecret, - final int keyLengthBits, - final byte[] otherInfo) - throws JOSEException { - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - - final MessageDigest md = getMessageDigest(); - - for (int i=1; i <= computeDigestCycles(ByteUtils.safeBitLength(md.getDigestLength()), keyLengthBits); i++) { - - byte[] counterBytes = IntegerUtils.toBytes(i); - - md.update(counterBytes); - md.update(sharedSecret.getEncoded()); - - if (otherInfo != null) { - md.update(otherInfo); - } - - try { - baos.write(md.digest()); - } catch (IOException e) { - throw new JOSEException("Couldn't write derived key: " + e.getMessage(), e); - } - } - - byte[] derivedKeyMaterial = baos.toByteArray(); - - final int keyLengthBytes = ByteUtils.byteLength(keyLengthBits); - - if (derivedKeyMaterial.length == keyLengthBytes) { - // Return immediately - return new SecretKeySpec(derivedKeyMaterial, "AES"); - } - - return new SecretKeySpec(ByteUtils.subArray(derivedKeyMaterial, 0, keyLengthBytes), "AES"); - } - - - /** - * Derives a key from the specified inputs. - * - * @param sharedSecret The shared secret. Must not be {@code null}. - * @param keyLength The length of the key to derive, in bits. - * @param algID The algorithm identifier, {@code null} if not - * specified. - * @param partyUInfo The partyUInfo, {@code null} if not specified. - * @param partyVInfo The partyVInfo {@code null} if not specified. - * @param suppPubInfo The suppPubInfo, {@code null} if not specified. - * @param suppPrivInfo The suppPrivInfo, {@code null} if not specified. - * - * @return The derived key, with algorithm set to "AES". - * - * @throws JOSEException If the key derivation failed. - */ - public SecretKey deriveKey(final SecretKey sharedSecret, - final int keyLength, - final byte[] algID, - final byte[] partyUInfo, - final byte[] partyVInfo, - final byte[] suppPubInfo, - final byte[] suppPrivInfo) - throws JOSEException { - - final byte[] otherInfo = composeOtherInfo(algID, partyUInfo, partyVInfo, suppPubInfo, suppPrivInfo); - - return deriveKey(sharedSecret, keyLength, otherInfo); - } - - - /** - * Composes the other info as {@code algID || partyUInfo || partyVInfo - * || suppPubInfo || suppPrivInfo}. - * - * @param algID The algorithm identifier, {@code null} if not - * specified. - * @param partyUInfo The partyUInfo, {@code null} if not specified. - * @param partyVInfo The partyVInfo {@code null} if not specified. - * @param suppPubInfo The suppPubInfo, {@code null} if not specified. - * @param suppPrivInfo The suppPrivInfo, {@code null} if not specified. - * - * @return The resulting other info. - */ - public static byte[] composeOtherInfo(final byte[] algID, - final byte[] partyUInfo, - final byte[] partyVInfo, - final byte[] suppPubInfo, - final byte[] suppPrivInfo) { - - return ByteUtils.concat(algID, partyUInfo, partyVInfo, suppPubInfo, suppPrivInfo); - } - - - /** - * Returns a message digest instance for the configured - * {@link #jcaHashAlg hash algorithm}. - * - * @return The message digest instance. - * - * @throws JOSEException If the message digest algorithm is not - * supported by the underlying JCA provider. - */ - private MessageDigest getMessageDigest() - throws JOSEException { - - final Provider provider = getJCAContext().getProvider(); - - try { - if (provider == null) - return MessageDigest.getInstance(jcaHashAlg); - else - return MessageDigest.getInstance(jcaHashAlg, provider); - } catch (NoSuchAlgorithmException e) { - throw new JOSEException("Couldn't get message digest for KDF: " + e.getMessage(), e); - } - } - - - /** - * Computes the required digest (hashing) cycles for the specified - * message digest length and derived key length. - * - * @param digestLengthBits The length of the message digest, in bits. - * @param keyLengthBits The length of the derived key, in bits. - * - * @return The digest cycles. - */ - public static int computeDigestCycles(final int digestLengthBits, final int keyLengthBits) { - - // return the ceiling of keyLength / digestLength - - return (keyLengthBits + digestLengthBits - 1) / digestLengthBits; - } - - - /** - * Encodes no / empty data as an empty byte array. - * - * @return The encoded data. - */ - public static byte[] encodeNoData() { - - return new byte[0]; - } - - - /** - * Encodes the specified integer data as a four byte array. - * - * @param data The integer data to encode. - * - * @return The encoded data. - */ - public static byte[] encodeIntData(final int data) { - - return IntegerUtils.toBytes(data); - } - - - /** - * Encodes the specified string data as {@code data.length || data}. - * - * @param data The string data, UTF-8 encoded. May be {@code null}. - * - * @return The encoded data. - */ - public static byte[] encodeStringData(final String data) { - - byte[] bytes = data != null ? data.getBytes(StandardCharset.UTF_8) : null; - return encodeDataWithLength(bytes); - } - - - /** - * Encodes the specified data as {@code data.length || data}. - * - * @param data The data to encode, may be {@code null}. - * - * @return The encoded data. - */ - public static byte[] encodeDataWithLength(final byte[] data) { - - byte[] bytes = data != null ? data : new byte[0]; - byte[] length = IntegerUtils.toBytes(bytes.length); - return ByteUtils.concat(length, bytes); - } - - - /** - * Encodes the specified BASE64URL encoded data - * {@code data.length || data}. - * - * @param data The data to encode, may be {@code null}. - * - * @return The encoded data. - */ - public static byte[] encodeDataWithLength(final Base64URL data) { - - byte[] bytes = data != null ? data.decode() : null; - return encodeDataWithLength(bytes); - } -} - diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/ContentCryptoProvider.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/ContentCryptoProvider.java deleted file mode 100644 index 75dd5c9c6..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/ContentCryptoProvider.java +++ /dev/null @@ -1,310 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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.crypto.impl; - - -import java.security.SecureRandom; -import java.util.*; -import javax.crypto.SecretKey; -import javax.crypto.spec.SecretKeySpec; - -import com.nimbusds.jose.*; -import com.nimbusds.jose.jca.JWEJCAContext; -import com.nimbusds.jose.util.Base64URL; -import com.nimbusds.jose.util.ByteUtils; -import com.nimbusds.jose.util.Container; -import com.nimbusds.jose.util.IntegerOverflowException; - - -/** - * JWE content encryption / decryption provider. - * - * @author Vladimir Dzhuvinov - * @version 2017-06-01 - */ -public class ContentCryptoProvider { - - - /** - * The supported encryption methods. - */ - public static final Set SUPPORTED_ENCRYPTION_METHODS; - - - /** - * The encryption methods compatible with each key size in bits. - */ - public static final Map> COMPATIBLE_ENCRYPTION_METHODS; - - - static { - Set methods = new LinkedHashSet<>(); - methods.add(EncryptionMethod.A128CBC_HS256); - methods.add(EncryptionMethod.A192CBC_HS384); - methods.add(EncryptionMethod.A256CBC_HS512); - methods.add(EncryptionMethod.A128GCM); - methods.add(EncryptionMethod.A192GCM); - methods.add(EncryptionMethod.A256GCM); - methods.add(EncryptionMethod.A128CBC_HS256_DEPRECATED); - methods.add(EncryptionMethod.A256CBC_HS512_DEPRECATED); - SUPPORTED_ENCRYPTION_METHODS = Collections.unmodifiableSet(methods); - - Map> encsMap = new HashMap<>(); - Set bit128Encs = new HashSet<>(); - Set bit192Encs = new HashSet<>(); - Set bit256Encs = new HashSet<>(); - Set bit384Encs = new HashSet<>(); - Set bit512Encs = new HashSet<>(); - bit128Encs.add(EncryptionMethod.A128GCM); - bit192Encs.add(EncryptionMethod.A192GCM); - bit256Encs.add(EncryptionMethod.A256GCM); - bit256Encs.add(EncryptionMethod.A128CBC_HS256); - bit256Encs.add(EncryptionMethod.A128CBC_HS256_DEPRECATED); - bit384Encs.add(EncryptionMethod.A192CBC_HS384); - bit512Encs.add(EncryptionMethod.A256CBC_HS512); - bit512Encs.add(EncryptionMethod.A256CBC_HS512_DEPRECATED); - encsMap.put(128,Collections.unmodifiableSet(bit128Encs)); - encsMap.put(192,Collections.unmodifiableSet(bit192Encs)); - encsMap.put(256,Collections.unmodifiableSet(bit256Encs)); - encsMap.put(384,Collections.unmodifiableSet(bit384Encs)); - encsMap.put(512, Collections.unmodifiableSet(bit512Encs)); - COMPATIBLE_ENCRYPTION_METHODS = Collections.unmodifiableMap(encsMap); - } - - - /** - * Generates a Content Encryption Key (CEK) for the specified JOSE - * encryption method. - * - * @param enc The encryption method. Must not be {@code null}. - * @param randomGen The secure random generator to use. Must not be - * {@code null}. - * - * @return The generated CEK (with algorithm "AES"). - * - * @throws JOSEException If the encryption method is not supported. - */ - public static SecretKey generateCEK(final EncryptionMethod enc, final SecureRandom randomGen) - throws JOSEException { - - if (! SUPPORTED_ENCRYPTION_METHODS.contains(enc)) { - throw new JOSEException(AlgorithmSupportMessage.unsupportedEncryptionMethod(enc, SUPPORTED_ENCRYPTION_METHODS)); - } - - final byte[] cekMaterial = new byte[ByteUtils.byteLength(enc.cekBitLength())]; - - randomGen.nextBytes(cekMaterial); - - return new SecretKeySpec(cekMaterial, "AES"); - } - - - /** - * Checks the length of the Content Encryption Key (CEK) according to - * the encryption method. - * - * @param cek The CEK. Must not be {@code null}. - * @param enc The encryption method. Must not be {@code null}. - * - * @throws KeyLengthException If the CEK length doesn't match the - * encryption method. - */ - private static void checkCEKLength(final SecretKey cek, final EncryptionMethod enc) - throws KeyLengthException { - - try { - if (enc.cekBitLength() != ByteUtils.safeBitLength(cek.getEncoded())) { - throw new KeyLengthException("The Content Encryption Key (CEK) length for " + enc + " must be " + enc.cekBitLength() + " bits"); - } - } catch (IntegerOverflowException e) { - throw new KeyLengthException("The Content Encryption Key (CEK) is too long: " + e.getMessage()); - } - } - - - /** - * Encrypts the specified clear text (content). - * - * @param header The final JWE header. Must not be {@code null}. - * @param clearText The clear text to encrypt and optionally - * compress. Must not be {@code null}. - * @param cek The Content Encryption Key (CEK). Must not be - * {@code null}. - * @param encryptedKey The encrypted CEK, {@code null} if not required. - * @param jcaProvider The JWE JCA provider specification. Must not be - * {@code null}. - * - * @return The JWE crypto parts. - * - * @throws JOSEException If encryption failed. - */ - public static JWECryptoParts encrypt(final JWEHeader header, - final byte[] clearText, - final SecretKey cek, - final Base64URL encryptedKey, - final JWEJCAContext jcaProvider) - throws JOSEException { - - checkCEKLength(cek, header.getEncryptionMethod()); - - // Apply compression if instructed - final byte[] plainText = DeflateHelper.applyCompression(header, clearText); - - // Compose the AAD - final byte[] aad = AAD.compute(header); - - // Encrypt the plain text according to the JWE enc - final byte[] iv; - final AuthenticatedCipherText authCipherText; - - if ( header.getEncryptionMethod().equals(EncryptionMethod.A128CBC_HS256) || - header.getEncryptionMethod().equals(EncryptionMethod.A192CBC_HS384) || - header.getEncryptionMethod().equals(EncryptionMethod.A256CBC_HS512) ) { - - iv = AESCBC.generateIV(jcaProvider.getSecureRandom()); - - authCipherText = AESCBC.encryptAuthenticated( - cek, iv, plainText, aad, - jcaProvider.getContentEncryptionProvider(), - jcaProvider.getMACProvider()); - - } else if (header.getEncryptionMethod().equals(EncryptionMethod.A128GCM) || - header.getEncryptionMethod().equals(EncryptionMethod.A192GCM) || - header.getEncryptionMethod().equals(EncryptionMethod.A256GCM) ) { - - Container ivContainer = new Container<>(AESGCM.generateIV(jcaProvider.getSecureRandom())); - - authCipherText = AESGCM.encrypt( - cek, ivContainer, plainText, aad, - jcaProvider.getContentEncryptionProvider()); - - iv = ivContainer.get(); - - } else if (header.getEncryptionMethod().equals(EncryptionMethod.A128CBC_HS256_DEPRECATED) || - header.getEncryptionMethod().equals(EncryptionMethod.A256CBC_HS512_DEPRECATED) ) { - - iv = AESCBC.generateIV(jcaProvider.getSecureRandom()); - - authCipherText = AESCBC.encryptWithConcatKDF( - header, cek, encryptedKey, iv, plainText, - jcaProvider.getContentEncryptionProvider(), - jcaProvider.getMACProvider()); - - } else { - - throw new JOSEException(AlgorithmSupportMessage.unsupportedEncryptionMethod( - header.getEncryptionMethod(), - SUPPORTED_ENCRYPTION_METHODS)); - } - - return new JWECryptoParts( - header, - encryptedKey, - Base64URL.encode(iv), - Base64URL.encode(authCipherText.getCipherText()), - Base64URL.encode(authCipherText.getAuthenticationTag())); - } - - - /** - * Decrypts the specified cipher text. - * - * @param header The JWE header. Must not be {@code null}. - * @param encryptedKey The encrypted key, {@code null} if not - * specified. - * @param iv The initialisation vector (IV). Must not be - * {@code null}. - * @param cipherText The cipher text. Must not be {@code null}. - * @param authTag The authentication tag. Must not be - * {@code null}. - * @param cek The Content Encryption Key (CEK). Must not be - * {@code null}. - * @param jcaProvider The JWE JCA provider specification. Must not be - * {@code null}. - * - * @return The clear text. - * - * @throws JOSEException If decryption failed. - */ - public static byte[] decrypt(final JWEHeader header, - final Base64URL encryptedKey, - final Base64URL iv, - final Base64URL cipherText, - final Base64URL authTag, - final SecretKey cek, - final JWEJCAContext jcaProvider) - throws JOSEException { - - checkCEKLength(cek, header.getEncryptionMethod()); - - // Compose the AAD - byte[] aad = AAD.compute(header); - - // Decrypt the cipher text according to the JWE enc - - byte[] plainText; - - if (header.getEncryptionMethod().equals(EncryptionMethod.A128CBC_HS256) || - header.getEncryptionMethod().equals(EncryptionMethod.A192CBC_HS384) || - header.getEncryptionMethod().equals(EncryptionMethod.A256CBC_HS512)) { - - plainText = AESCBC.decryptAuthenticated( - cek, - iv.decode(), - cipherText.decode(), - aad, - authTag.decode(), - jcaProvider.getContentEncryptionProvider(), - jcaProvider.getMACProvider()); - - } else if (header.getEncryptionMethod().equals(EncryptionMethod.A128GCM) || - header.getEncryptionMethod().equals(EncryptionMethod.A192GCM) || - header.getEncryptionMethod().equals(EncryptionMethod.A256GCM)) { - - plainText = AESGCM.decrypt( - cek, - iv.decode(), - cipherText.decode(), - aad, - authTag.decode(), - jcaProvider.getContentEncryptionProvider()); - - } else if (header.getEncryptionMethod().equals(EncryptionMethod.A128CBC_HS256_DEPRECATED) || - header.getEncryptionMethod().equals(EncryptionMethod.A256CBC_HS512_DEPRECATED)) { - - plainText = AESCBC.decryptWithConcatKDF( - header, - cek, - encryptedKey, - iv, - cipherText, - authTag, - jcaProvider.getContentEncryptionProvider(), - jcaProvider.getMACProvider()); - - } else { - throw new JOSEException(AlgorithmSupportMessage.unsupportedEncryptionMethod( - header.getEncryptionMethod(), - SUPPORTED_ENCRYPTION_METHODS)); - } - - - // Apply decompression if requested - return DeflateHelper.applyDecompression(header, plainText); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/CriticalHeaderParamsDeferral.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/CriticalHeaderParamsDeferral.java deleted file mode 100644 index 3f4937084..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/CriticalHeaderParamsDeferral.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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.crypto.impl; - - -import java.util.Collections; -import java.util.Set; - -import com.nimbusds.jose.CriticalHeaderParamsAware; -import com.nimbusds.jose.Header; -import com.nimbusds.jose.JOSEException; -import com.nimbusds.jose.JWEHeader; - - -/** - * Critical ({@code crit}) header parameters deferral policy. - * - * @see CriticalHeaderParamsAware - * - * @author Vladimir Dzhuvinov - * @version 2015-05-20 - */ -public class CriticalHeaderParamsDeferral { - - - /** - * The names of the deferred critical headers. - */ - private Set deferredParams = Collections.emptySet(); - - - /** - * Returns the names of the critical ({@code crit}) header parameters - * that are understood and processed. - * - * @return Empty immutable set. - */ - public Set getProcessedCriticalHeaderParams() { - - return Collections.emptySet(); - } - - - /** - * Returns the names of the critical ({@code crit}) header parameters - * that are deferred to the application for processing. - * - * @return The names of the critical header parameters that are - * deferred to the application for processing, as an - * unmodifiable set, empty set if none. - */ - public Set getDeferredCriticalHeaderParams() { - - return Collections.unmodifiableSet(deferredParams); - } - - - /** - * Sets the names of the critical ({@code crit}) header parameters - * that are deferred to the application for processing. - * - * @param defCritHeaders The names of the critical header parameters - * that are deferred to the application for - * processing, empty set or {@code null} if none. - */ - public void setDeferredCriticalHeaderParams(final Set defCritHeaders) { - - if (defCritHeaders == null) { - this.deferredParams = Collections.emptySet(); - } else { - this.deferredParams = defCritHeaders; - } - } - - - /** - * Returns {@code true} if the specified header passes the critical - * parameters check. - * - * @param header The JWS or JWE header to check. Must not be - * {@code null}. - * - * @return {@code true} if the header passes, {@code false} if the - * header contains one or more critical header parameters which - * are not marked for deferral to the application. - */ - public boolean headerPasses(final Header header) { - - Set crit = header.getCriticalParams(); - - if (crit == null || crit.isEmpty()) { - return true; // OK - } - - // Ensure all marked as deferred - return deferredParams != null && deferredParams.containsAll(crit); - } - - - /** - * Throws a JOSE exception if the specified JWE header doesn't pass the - * critical header parameters check. - * - * @param header The JWE header to check. Must not be {@code null}. - * - * @throws JOSEException If the JWE header doesn't pass the check. - */ - public void ensureHeaderPasses(final JWEHeader header) - throws JOSEException { - - if (! headerPasses(header)) { - throw new JOSEException("Unsupported critical header parameter(s)"); - } - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/DeflateHelper.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/DeflateHelper.java deleted file mode 100644 index 78fa9b1ba..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/DeflateHelper.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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.crypto.impl; - - -import com.nimbusds.jose.CompressionAlgorithm; -import com.nimbusds.jose.JOSEException; -import com.nimbusds.jose.JWEHeader; -import com.nimbusds.jose.util.DeflateUtils; -import net.jcip.annotations.ThreadSafe; - - -/** - * Deflate (RFC 1951) helper methods, intended for use by JWE encrypters and - * decrypters. This class is thread-safe. - * - * @author Vladimir Dzhuvinov - * @version 2014-07-08 - */ -@ThreadSafe -public class DeflateHelper { - - - /** - * Applies compression to the specified plain text if requested. - * - * @param jweHeader The JWE header. Must not be {@code null}. - * @param bytes The plain text bytes. Must not be {@code null}. - * - * @return The bytes to encrypt. - * - * @throws JOSEException If compression failed or the requested - * compression algorithm is not supported. - */ - public static byte[] applyCompression(final JWEHeader jweHeader, final byte[] bytes) - throws JOSEException { - - CompressionAlgorithm compressionAlg = jweHeader.getCompressionAlgorithm(); - - if (compressionAlg == null) { - - return bytes; - - } else if (compressionAlg.equals(CompressionAlgorithm.DEF)) { - - try { - return DeflateUtils.compress(bytes); - - } catch (Exception e) { - - throw new JOSEException("Couldn't compress plain text: " + e.getMessage(), e); - } - - } else { - - throw new JOSEException("Unsupported compression algorithm: " + compressionAlg); - } - } - - - /** - * Applies decompression to the specified plain text if requested. - * - * @param jweHeader The JWE header. Must not be {@code null}. - * @param bytes The plain text bytes. Must not be {@code null}. - * - * @return The output bytes, decompressed if requested. - * - * @throws JOSEException If decompression failed or the requested - * compression algorithm is not supported. - */ - public static byte[] applyDecompression(final JWEHeader jweHeader, final byte[] bytes) - throws JOSEException { - - CompressionAlgorithm compressionAlg = jweHeader.getCompressionAlgorithm(); - - if (compressionAlg == null) { - - return bytes; - - } else if (compressionAlg.equals(CompressionAlgorithm.DEF)) { - - try { - return DeflateUtils.decompress(bytes); - - } catch (Exception e) { - - throw new JOSEException("Couldn't decompress plain text: " + e.getMessage(), e); - } - - } else { - - throw new JOSEException("Unsupported compression algorithm: " + compressionAlg); - } - } -} \ No newline at end of file diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/DirectCryptoProvider.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/DirectCryptoProvider.java deleted file mode 100644 index 7b6261667..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/DirectCryptoProvider.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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.crypto.impl; - - -import java.util.Collections; -import java.util.LinkedHashSet; -import java.util.Set; -import javax.crypto.SecretKey; - -import com.nimbusds.jose.EncryptionMethod; -import com.nimbusds.jose.JWEAlgorithm; -import com.nimbusds.jose.KeyLengthException; -import com.nimbusds.jose.util.ByteUtils; - - -/** - * The base abstract class for direct encrypters and decrypters of - * {@link com.nimbusds.jose.JWEObject JWE objects} with a shared symmetric key. - * - *

Supports the following key management algorithms: - * - *

    - *
  • {@link com.nimbusds.jose.JWEAlgorithm#DIR} - *
- * - *

Supports the following content encryption algorithms: - * - *

    - *
  • {@link com.nimbusds.jose.EncryptionMethod#A128CBC_HS256} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A192CBC_HS384} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A256CBC_HS512} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A128GCM} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A192GCM} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A256GCM} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A128CBC_HS256_DEPRECATED} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A256CBC_HS512_DEPRECATED} - *
- * - * @author Vladimir Dzhuvinov - * @version 2015-06-29 - */ -public abstract class DirectCryptoProvider extends BaseJWEProvider { - - - /** - * The supported JWE algorithms by the direct crypto provider class. - */ - public static final Set SUPPORTED_ALGORITHMS; - - - /** - * The supported encryption methods by the direct crypto provider - * class. - */ - public static final Set SUPPORTED_ENCRYPTION_METHODS = ContentCryptoProvider.SUPPORTED_ENCRYPTION_METHODS; - - - static { - Set algs = new LinkedHashSet<>(); - algs.add(JWEAlgorithm.DIR); - SUPPORTED_ALGORITHMS = Collections.unmodifiableSet(algs); - } - - - /** - * Returns the compatible encryption methods for the specified Content - * Encryption Key (CEK) length. - * - * @param cekLength The CEK length in bits. - * - * @return The compatible encryption methods. - * - * @throws KeyLengthException If the CEK length is not compatible. - */ - private static Set getCompatibleEncryptionMethods(final int cekLength) - throws KeyLengthException { - - Set encs = ContentCryptoProvider.COMPATIBLE_ENCRYPTION_METHODS.get(cekLength); - - if (encs == null) { - throw new KeyLengthException("The Content Encryption Key length must be 128 bits (16 bytes), 192 bits (24 bytes), 256 bits (32 bytes), 384 bits (48 bytes) or 512 bites (64 bytes)"); - } - - return encs; - } - - - /** - * The Content Encryption Key (CEK). - */ - private final SecretKey cek; - - - /** - * Creates a new direct encryption / decryption provider. - * - * @param cek The Content Encryption Key (CEK). Must be 128 bits (16 - * bytes), 192 bits (24 bytes), 256 bits (32 bytes), 384 - * bits (48 bytes) or 512 bits (64 bytes) long. Must not be - * {@code null}. - * - * @throws KeyLengthException If the CEK length is not compatible. - */ - protected DirectCryptoProvider(final SecretKey cek) - throws KeyLengthException { - - super(SUPPORTED_ALGORITHMS, getCompatibleEncryptionMethods(ByteUtils.bitLength(cek.getEncoded()))); - - this.cek = cek; - } - - - /** - * Gets the Content Encryption Key (CEK). - * - * @return The key. - */ - public SecretKey getKey() { - - return cek; - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/ECDH.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/ECDH.java deleted file mode 100644 index 81e5abbf7..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/ECDH.java +++ /dev/null @@ -1,288 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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.crypto.impl; - - -import java.nio.charset.Charset; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.Provider; -import java.security.interfaces.ECPublicKey; -import javax.crypto.KeyAgreement; -import javax.crypto.SecretKey; -import javax.crypto.spec.SecretKeySpec; - -import com.google.crypto.tink.subtle.X25519; -import com.nimbusds.jose.EncryptionMethod; -import com.nimbusds.jose.JOSEException; -import com.nimbusds.jose.JWEAlgorithm; -import com.nimbusds.jose.JWEHeader; -import com.nimbusds.jose.jwk.Curve; -import com.nimbusds.jose.jwk.OctetKeyPair; - - -/** - * Elliptic Curve Diffie-Hellman key agreement functions and utilities. - * - * @author Vladimir Dzhuvinov - * @version 2018-12-12 - */ -public class ECDH { - - - /** - * Enumeration of the Elliptic Curve Diffie-Hellman Ephemeral Static - * algorithm modes. - */ - public enum AlgorithmMode { - - /** - * Direct key agreement mode. - */ - DIRECT, - - - /** - * Key wrapping mode. - */ - KW - } - - - /** - * Resolves the ECDH algorithm mode. - * - * @param alg The JWE algorithm. Must be supported and not - * {@code null}. - * - * @return The algorithm mode. - * - * @throws JOSEException If the JWE algorithm is not supported. - */ - public static AlgorithmMode resolveAlgorithmMode(final JWEAlgorithm alg) - throws JOSEException { - - if (alg.equals(JWEAlgorithm.ECDH_ES)) { - - return AlgorithmMode.DIRECT; - - } else if (alg.equals(JWEAlgorithm.ECDH_ES_A128KW) || - alg.equals(JWEAlgorithm.ECDH_ES_A192KW) || - alg.equals(JWEAlgorithm.ECDH_ES_A256KW)) { - - return AlgorithmMode.KW; - } else { - - throw new JOSEException(AlgorithmSupportMessage.unsupportedJWEAlgorithm( - alg, - ECDHCryptoProvider.SUPPORTED_ALGORITHMS)); - } - } - - - /** - * Returns the bit length of the shared key (derived via concat KDF) - * for the specified JWE ECDH algorithm. - * - * @param alg The JWE ECDH algorithm. Must be supported and not - * {@code null}. - * @param enc The encryption method. Must be supported} and not - * {@code null}. - * - * @return The bit length of the shared key. - * - * @throws JOSEException If the JWE algorithm or encryption method is - * not supported. - */ - public static int sharedKeyLength(final JWEAlgorithm alg, final EncryptionMethod enc) - throws JOSEException { - - if (alg.equals(JWEAlgorithm.ECDH_ES)) { - - int length = enc.cekBitLength(); - - if (length == 0) { - throw new JOSEException("Unsupported JWE encryption method " + enc); - } - - return length; - - } else if (alg.equals(JWEAlgorithm.ECDH_ES_A128KW)) { - return 128; - } else if (alg.equals(JWEAlgorithm.ECDH_ES_A192KW)) { - return 192; - } else if (alg.equals(JWEAlgorithm.ECDH_ES_A256KW)) { - return 256; - } else { - throw new JOSEException(AlgorithmSupportMessage.unsupportedJWEAlgorithm( - alg, ECDHCryptoProvider.SUPPORTED_ALGORITHMS)); - } - } - - - /** - * Derives a shared secret (also called 'Z') from the specified ECDH - * key agreement. - * - * @param publicKey The public EC key, i.e. the consumer's public EC - * key on encryption, or the ephemeral public EC key - * on decryption. Must not be {@code null}. - * @param privateKey The private EC Key, i.e. the ephemeral private EC - * key on encryption, or the consumer's private EC - * key on decryption. Must not be {@code null}. - * @param provider The specific JCA provider for the ECDH key - * agreement, {@code null} to use the default one. - * - * @return The derived shared secret ('Z'), with algorithm "AES". - * - * @throws JOSEException If derivation of the shared secret failed. - */ - public static SecretKey deriveSharedSecret(final ECPublicKey publicKey, - final PrivateKey privateKey, - final Provider provider) - throws JOSEException { - - // Get an ECDH key agreement instance from the JCA provider - KeyAgreement keyAgreement; - - try { - if (provider != null) { - keyAgreement = KeyAgreement.getInstance("ECDH", provider); - } else { - keyAgreement = KeyAgreement.getInstance("ECDH"); - } - - } catch (NoSuchAlgorithmException e) { - throw new JOSEException("Couldn't get an ECDH key agreement instance: " + e.getMessage(), e); - } - - try { - keyAgreement.init(privateKey); - keyAgreement.doPhase(publicKey, true); - - } catch (InvalidKeyException e) { - throw new JOSEException("Invalid key for ECDH key agreement: " + e.getMessage(), e); - } - - return new SecretKeySpec(keyAgreement.generateSecret(), "AES"); - } - - - /** - * Derives a shared secret (also called 'Z') from the specified ECDH - * key agreement. - * - * @param publicKey The public OKP key, i.e. the consumer's public EC - * key on encryption, or the ephemeral public EC key - * on decryption. Must not be {@code null}. - * @param privateKey The private OKP key, i.e. the ephemeral private EC - * key on encryption, or the consumer's private EC - * key on decryption. Must not be {@code null}. - * - * @return The derived shared secret ('Z'), with algorithm "AES". - * - * @throws JOSEException If derivation of the shared secret failed. - */ - public static SecretKey deriveSharedSecret(final OctetKeyPair publicKey, final OctetKeyPair privateKey) - throws JOSEException { - - if (publicKey.isPrivate()) { - throw new JOSEException("Expected public key but received OKP with 'd' value"); - } - - if (! Curve.X25519.equals(publicKey.getCurve())) { - throw new JOSEException("Expected public key OKP with crv=X25519"); - } - - if (! privateKey.isPrivate()) { - throw new JOSEException("Expected private key but received OKP without 'd' value"); - } - - if (! Curve.X25519.equals(privateKey.getCurve())) { - throw new JOSEException("Expected private key OKP with crv=X25519"); - } - - final byte[] privateKeyBytes = privateKey.getDecodedD(); - final byte[] publicKeyBytes = publicKey.getDecodedX(); - - final byte[] sharedSecretBytes; - try { - sharedSecretBytes = X25519.computeSharedSecret(privateKeyBytes, publicKeyBytes); - } catch (InvalidKeyException e) { - throw new JOSEException(e.getMessage(), e); - } - - return new SecretKeySpec(sharedSecretBytes, "AES"); - } - - - /** - * Derives a shared key (via concat KDF). - * - * @param header The JWE header. Its algorithm and encryption method - * must be supported. Must not be {@code null}. - * @param Z The derived shared secret ('Z'). Must not be - * {@code null}. - * @param concatKDF The concat KDF. Must be initialised and not - * {@code null}. - * - * @return The derived shared key. - * - * @throws JOSEException If derivation of the shared key failed. - */ - public static SecretKey deriveSharedKey(final JWEHeader header, - final SecretKey Z, - final ConcatKDF concatKDF) - throws JOSEException { - - final int sharedKeyLength = sharedKeyLength(header.getAlgorithm(), header.getEncryptionMethod()); - - // Set the alg ID for the concat KDF - AlgorithmMode algMode = resolveAlgorithmMode(header.getAlgorithm()); - - final String algID; - - if (algMode == AlgorithmMode.DIRECT) { - // algID = enc - algID = header.getEncryptionMethod().getName(); - } else if (algMode == AlgorithmMode.KW) { - // algID = alg - algID = header.getAlgorithm().getName(); - } else { - throw new JOSEException("Unsupported JWE ECDH algorithm mode: " + algMode); - } - - return concatKDF.deriveKey( - Z, - sharedKeyLength, - ConcatKDF.encodeDataWithLength(algID.getBytes(Charset.forName("ASCII"))), - ConcatKDF.encodeDataWithLength(header.getAgreementPartyUInfo()), - ConcatKDF.encodeDataWithLength(header.getAgreementPartyVInfo()), - ConcatKDF.encodeIntData(sharedKeyLength), - ConcatKDF.encodeNoData()); - } - - - /** - * Prevents public instantiation. - */ - private ECDH() { - - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/ECDHCryptoProvider.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/ECDHCryptoProvider.java deleted file mode 100644 index 3dfb91274..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/ECDHCryptoProvider.java +++ /dev/null @@ -1,254 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2019, Connect2id Ltd and contributors. - * - * 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.crypto.impl; - - -import java.util.Collections; -import java.util.LinkedHashSet; -import java.util.Set; - -import javax.crypto.SecretKey; - -import com.nimbusds.jose.EncryptionMethod; -import com.nimbusds.jose.JOSEException; -import com.nimbusds.jose.JWEAlgorithm; -import com.nimbusds.jose.JWECryptoParts; -import com.nimbusds.jose.JWEHeader; -import com.nimbusds.jose.jwk.Curve; -import com.nimbusds.jose.util.Base64URL; - - -/** - * The base abstract class for Elliptic Curve Diffie-Hellman encrypters and - * decrypters of {@link com.nimbusds.jose.JWEObject JWE objects}. - * - *

Supports the following key management algorithms: - * - *

    - *
  • {@link com.nimbusds.jose.JWEAlgorithm#ECDH_ES} - *
  • {@link com.nimbusds.jose.JWEAlgorithm#ECDH_ES_A128KW} - *
  • {@link com.nimbusds.jose.JWEAlgorithm#ECDH_ES_A192KW} - *
  • {@link com.nimbusds.jose.JWEAlgorithm#ECDH_ES_A256KW} - *
- * - *

Supports the following elliptic curves: - * - *

    - *
  • {@link com.nimbusds.jose.jwk.Curve#P_256} - *
  • {@link com.nimbusds.jose.jwk.Curve#P_384} - *
  • {@link com.nimbusds.jose.jwk.Curve#P_521} - *
  • {@link com.nimbusds.jose.jwk.Curve#X25519} - *
- * - *

Supports the following content encryption algorithms: - * - *

    - *
  • {@link com.nimbusds.jose.EncryptionMethod#A128CBC_HS256} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A192CBC_HS384} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A256CBC_HS512} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A128GCM} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A192GCM} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A256GCM} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A128CBC_HS256_DEPRECATED} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A256CBC_HS512_DEPRECATED} - *
- * - * @author Tim McLean - * @author Vladimir Dzhuvinov - * @author Fernando González Callejas - * @version 2019-01-24 - */ -public abstract class ECDHCryptoProvider extends BaseJWEProvider { - - - /** - * The supported JWE algorithms by the ECDH crypto provider class. - */ - public static final Set SUPPORTED_ALGORITHMS; - - - /** - * The supported encryption methods by the ECDH crypto provider class. - */ - public static final Set SUPPORTED_ENCRYPTION_METHODS = ContentCryptoProvider.SUPPORTED_ENCRYPTION_METHODS; - - - static { - Set algs = new LinkedHashSet<>(); - algs.add(JWEAlgorithm.ECDH_ES); - algs.add(JWEAlgorithm.ECDH_ES_A128KW); - algs.add(JWEAlgorithm.ECDH_ES_A192KW); - algs.add(JWEAlgorithm.ECDH_ES_A256KW); - SUPPORTED_ALGORITHMS = Collections.unmodifiableSet(algs); - } - - - /** - * The elliptic curve. - */ - private final Curve curve; - - - /** - * The Concatenation Key Derivation Function (KDF). - */ - private final ConcatKDF concatKDF; - - - /** - * Creates a new Elliptic Curve Diffie-Hellman encryption /decryption - * provider. - * - * @param curve The elliptic curve. Must be supported and not - * {@code null}. - * - * @throws JOSEException If the elliptic curve is not supported. - */ - protected ECDHCryptoProvider(final Curve curve) - throws JOSEException { - - super(SUPPORTED_ALGORITHMS, ContentCryptoProvider.SUPPORTED_ENCRYPTION_METHODS); - - Curve definedCurve = curve != null ? curve : new Curve("unknown"); - - if (! supportedEllipticCurves().contains(curve)) { - throw new JOSEException(AlgorithmSupportMessage.unsupportedEllipticCurve( - definedCurve, supportedEllipticCurves())); - } - - this.curve = curve; - - concatKDF = new ConcatKDF("SHA-256"); - } - - - /** - * Returns the Concatenation Key Derivation Function (KDF). - * - * @return The concat KDF. - */ - protected ConcatKDF getConcatKDF() { - - return concatKDF; - } - - - /** - * Returns the names of the supported elliptic curves. These correspond - * to the {@code crv} EC JWK parameter. - * - * @return The supported elliptic curves. - */ - public abstract Set supportedEllipticCurves(); - - - /** - * Returns the elliptic curve of the key (JWK designation). - * - * @return The elliptic curve. - */ - public Curve getCurve() { - - return curve; - } - - /** - * Encrypts the specified plaintext using the specified shared secret - * ("Z"). - */ - protected JWECryptoParts encryptWithZ(final JWEHeader header, final SecretKey Z, final byte[] clearText) - throws JOSEException { - - return this.encryptWithZ(header, Z, clearText, null); - } - - /** - * Encrypts the specified plaintext using the specified shared secret - * ("Z") and, if provided, the content encryption key (CEK). - */ - protected JWECryptoParts encryptWithZ(final JWEHeader header, - final SecretKey Z, - final byte[] clearText, - final SecretKey contentEncryptionKey) - throws JOSEException { - - final JWEAlgorithm alg = header.getAlgorithm(); - final ECDH.AlgorithmMode algMode = ECDH.resolveAlgorithmMode(alg); - final EncryptionMethod enc = header.getEncryptionMethod(); - - // Derive shared key via concat KDF - getConcatKDF().getJCAContext().setProvider(getJCAContext().getMACProvider()); // update before concat - SecretKey sharedKey = ECDH.deriveSharedKey(header, Z, getConcatKDF()); - - final SecretKey cek; - final Base64URL encryptedKey; // The CEK encrypted (second JWE part) - - if (algMode.equals(ECDH.AlgorithmMode.DIRECT)) { - cek = sharedKey; - encryptedKey = null; - } else if (algMode.equals(ECDH.AlgorithmMode.KW)) { - if(contentEncryptionKey != null) { // Use externally supplied CEK - cek = contentEncryptionKey; - } else { // Generate the CEK according to the enc method - cek = ContentCryptoProvider.generateCEK(enc, getJCAContext().getSecureRandom()); - } - encryptedKey = Base64URL.encode(AESKW.wrapCEK(cek, sharedKey, getJCAContext().getKeyEncryptionProvider())); - } else { - throw new JOSEException("Unexpected JWE ECDH algorithm mode: " + algMode); - } - - return ContentCryptoProvider.encrypt(header, clearText, cek, encryptedKey, getJCAContext()); - } - - - /** - * Decrypts the encrypted JWE parts using the specified shared secret ("Z"). - */ - protected byte[] decryptWithZ(final JWEHeader header, - final SecretKey Z, - final Base64URL encryptedKey, - final Base64URL iv, - final Base64URL cipherText, - final Base64URL authTag) - throws JOSEException { - - final JWEAlgorithm alg = header.getAlgorithm(); - final ECDH.AlgorithmMode algMode = ECDH.resolveAlgorithmMode(alg); - - // Derive shared key via concat KDF - getConcatKDF().getJCAContext().setProvider(getJCAContext().getMACProvider()); // update before concat - SecretKey sharedKey = ECDH.deriveSharedKey(header, Z, getConcatKDF()); - - final SecretKey cek; - - if (algMode.equals(ECDH.AlgorithmMode.DIRECT)) { - cek = sharedKey; - } else if (algMode.equals(ECDH.AlgorithmMode.KW)) { - if (encryptedKey == null) { - throw new JOSEException("Missing JWE encrypted key"); - } - cek = AESKW.unwrapCEK(sharedKey, encryptedKey.decode(), getJCAContext().getKeyEncryptionProvider()); - } else { - throw new JOSEException("Unexpected JWE ECDH algorithm mode: " + algMode); - } - - return ContentCryptoProvider.decrypt(header, encryptedKey, iv, cipherText, authTag, cek, getJCAContext()); - } - - -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/ECDSA.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/ECDSA.java deleted file mode 100644 index ed6565c5a..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/ECDSA.java +++ /dev/null @@ -1,318 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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.crypto.impl; - - -import java.security.NoSuchAlgorithmException; -import java.security.Provider; -import java.security.Signature; -import java.security.interfaces.ECKey; -import java.security.spec.ECParameterSpec; - -import com.nimbusds.jose.JOSEException; -import com.nimbusds.jose.JWSAlgorithm; -import com.nimbusds.jose.jwk.Curve; - - -/** - * Elliptic Curve Digital Signature Algorithm (ECDSA) functions and utilities. - * - * @author Vladimir Dzhuvinov - * @author Aleksei Doroganov - * @version 2018-03-28 - */ -public class ECDSA { - - - /** - * Resolves the matching EC DSA algorithm for the specified EC key - * (public or private). - * - * @param ecKey The EC key. Must not be {@code null}. - * - * @return The matching EC DSA algorithm. - * - * @throws JOSEException If the elliptic curve of key is not supported. - */ - public static JWSAlgorithm resolveAlgorithm(final ECKey ecKey) - throws JOSEException { - - ECParameterSpec ecParameterSpec = ecKey.getParams(); - return resolveAlgorithm(Curve.forECParameterSpec(ecParameterSpec)); - } - - - /** - * Resolves the matching EC DSA algorithm for the specified elliptic - * curve. - * - * @param curve The elliptic curve. May be {@code null}. - * - * @return The matching EC DSA algorithm. - * - * @throws JOSEException If the elliptic curve of key is not supported. - */ - public static JWSAlgorithm resolveAlgorithm(final Curve curve) - throws JOSEException { - - if (curve == null) { - throw new JOSEException("The EC key curve is not supported, must be P-256, P-384 or P-521"); - } else if (Curve.P_256.equals(curve)) { - return JWSAlgorithm.ES256; - } else if (Curve.P_256K.equals(curve)) { - return JWSAlgorithm.ES256K; - } else if (Curve.P_384.equals(curve)) { - return JWSAlgorithm.ES384; - } else if (Curve.P_521.equals(curve)) { - return JWSAlgorithm.ES512; - } else { - throw new JOSEException("Unexpected curve: " + curve); - } - } - - - /** - * Creates a new JCA signer / verifier for ECDSA. - * - * @param alg The ECDSA JWS algorithm. Must not be - * {@code null}. - * @param jcaProvider The JCA provider, {@code null} if not specified. - * - * @return The JCA signer / verifier instance. - * - * @throws JOSEException If a JCA signer / verifier couldn't be - * created. - */ - public static Signature getSignerAndVerifier(final JWSAlgorithm alg, - final Provider jcaProvider) - throws JOSEException { - - String jcaAlg; - - if (alg.equals(JWSAlgorithm.ES256)) { - jcaAlg = "SHA256withECDSA"; - } else if (alg.equals(JWSAlgorithm.ES256K)) { - jcaAlg = "SHA256withECDSA"; - } else if (alg.equals(JWSAlgorithm.ES384)) { - jcaAlg = "SHA384withECDSA"; - } else if (alg.equals(JWSAlgorithm.ES512)) { - jcaAlg = "SHA512withECDSA"; - } else { - throw new JOSEException( - AlgorithmSupportMessage.unsupportedJWSAlgorithm( - alg, - ECDSAProvider.SUPPORTED_ALGORITHMS)); - } - - try { - if (jcaProvider != null) { - return Signature.getInstance(jcaAlg, jcaProvider); - } else { - return Signature.getInstance(jcaAlg); - } - } catch (NoSuchAlgorithmException e) { - throw new JOSEException("Unsupported ECDSA algorithm: " + e.getMessage(), e); - } - } - - - /** - * Returns the expected signature byte array length (R + S parts) for - * the specified ECDSA algorithm. - * - * @param alg The ECDSA algorithm. Must be supported and not - * {@code null}. - * - * @return The expected byte array length for the signature. - * - * @throws JOSEException If the algorithm is not supported. - */ - public static int getSignatureByteArrayLength(final JWSAlgorithm alg) - throws JOSEException { - - if (alg.equals(JWSAlgorithm.ES256)) { - - return 64; - - } else if (alg.equals(JWSAlgorithm.ES256K)) { - - return 64; - - } else if (alg.equals(JWSAlgorithm.ES384)) { - - return 96; - - } else if (alg.equals(JWSAlgorithm.ES512)) { - - return 132; - - } else { - - throw new JOSEException(AlgorithmSupportMessage.unsupportedJWSAlgorithm( - alg, - ECDSAProvider.SUPPORTED_ALGORITHMS)); - } - } - - - /** - * Transcodes the JCA ASN.1/DER-encoded signature into the concatenated - * R + S format expected by ECDSA JWS. - * - * @param derSignature The ASN1./DER-encoded. Must not be {@code null}. - * @param outputLength The expected length of the ECDSA JWS signature. - * - * @return The ECDSA JWS encoded signature. - * - * @throws JOSEException If the ASN.1/DER signature format is invalid. - */ - public static byte[] transcodeSignatureToConcat(final byte[] derSignature, int outputLength) - throws JOSEException { - - if (derSignature.length < 8 || derSignature[0] != 48) { - throw new JOSEException("Invalid ECDSA signature format"); - } - - int offset; - if (derSignature[1] > 0) { - offset = 2; - } else if (derSignature[1] == (byte) 0x81) { - offset = 3; - } else { - throw new JOSEException("Invalid ECDSA signature format"); - } - - byte rLength = derSignature[offset + 1]; - - int i; - for (i = rLength; (i > 0) && (derSignature[(offset + 2 + rLength) - i] == 0); i--) { - // do nothing - } - - byte sLength = derSignature[offset + 2 + rLength + 1]; - - int j; - for (j = sLength; (j > 0) && (derSignature[(offset + 2 + rLength + 2 + sLength) - j] == 0); j--) { - // do nothing - } - - int rawLen = Math.max(i, j); - rawLen = Math.max(rawLen, outputLength / 2); - - if ((derSignature[offset - 1] & 0xff) != derSignature.length - offset - || (derSignature[offset - 1] & 0xff) != 2 + rLength + 2 + sLength - || derSignature[offset] != 2 - || derSignature[offset + 2 + rLength] != 2) { - throw new JOSEException("Invalid ECDSA signature format"); - } - - final byte[] concatSignature = new byte[2 * rawLen]; - - System.arraycopy(derSignature, (offset + 2 + rLength) - i, concatSignature, rawLen - i, i); - System.arraycopy(derSignature, (offset + 2 + rLength + 2 + sLength) - j, concatSignature, 2 * rawLen - j, j); - - return concatSignature; - } - - - - /** - * Transcodes the ECDSA JWS signature into ASN.1/DER format for use by - * the JCA verifier. - * - * @param jwsSignature The JWS signature, consisting of the - * concatenated R and S values. Must not be - * {@code null}. - * - * @return The ASN.1/DER encoded signature. - * - * @throws JOSEException If the ECDSA JWS signature format is invalid. - */ - public static byte[] transcodeSignatureToDER(byte[] jwsSignature) - throws JOSEException { - - // Adapted from org.apache.xml.security.algorithms.implementations.SignatureECDSA - - int rawLen = jwsSignature.length / 2; - - int i; - - for (i = rawLen; (i > 0) && (jwsSignature[rawLen - i] == 0); i--) { - // do nothing - } - - int j = i; - - if (jwsSignature[rawLen - i] < 0) { - j += 1; - } - - int k; - - for (k = rawLen; (k > 0) && (jwsSignature[2 * rawLen - k] == 0); k--) { - // do nothing - } - - int l = k; - - if (jwsSignature[2 * rawLen - k] < 0) { - l += 1; - } - - int len = 2 + j + 2 + l; - - if (len > 255) { - throw new JOSEException("Invalid ECDSA signature format"); - } - - int offset; - - final byte derSignature[]; - - if (len < 128) { - derSignature = new byte[2 + 2 + j + 2 + l]; - offset = 1; - } else { - derSignature = new byte[3 + 2 + j + 2 + l]; - derSignature[1] = (byte) 0x81; - offset = 2; - } - - derSignature[0] = 48; - derSignature[offset++] = (byte) len; - derSignature[offset++] = 2; - derSignature[offset++] = (byte) j; - - System.arraycopy(jwsSignature, rawLen - i, derSignature, (offset + j) - i, i); - - offset += j; - - derSignature[offset++] = 2; - derSignature[offset++] = (byte) l; - - System.arraycopy(jwsSignature, 2 * rawLen - k, derSignature, (offset + l) - k, k); - - return derSignature; - } - - - /** - * Prevents public instantiation. - */ - private ECDSA() {} -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/ECDSAProvider.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/ECDSAProvider.java deleted file mode 100644 index bac226164..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/ECDSAProvider.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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.crypto.impl; - - -import java.util.Collections; -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.Set; - -import com.nimbusds.jose.JOSEException; -import com.nimbusds.jose.JWSAlgorithm; - - -/** - * The base abstract class for Elliptic Curve Digital Signature Algorithm - * (ECDSA) signers and validators of {@link com.nimbusds.jose.JWSObject JWS - * objects}. - * - *

Supports the following algorithms: - * - *

    - *
  • {@link com.nimbusds.jose.JWSAlgorithm#ES256} - *
  • {@link com.nimbusds.jose.JWSAlgorithm#ES256K} - *
  • {@link com.nimbusds.jose.JWSAlgorithm#ES384} - *
  • {@link com.nimbusds.jose.JWSAlgorithm#ES512} - *
- * - * @author Axel Nennker - * @author Vladimir Dzhuvinov - * @version 2017-05-13 - */ -public abstract class ECDSAProvider extends BaseJWSProvider { - - - /** - * The supported JWS algorithms by the EC-DSA provider class. - */ - public static final Set SUPPORTED_ALGORITHMS; - - - static { - Set algs = new LinkedHashSet<>(); - algs.add(JWSAlgorithm.ES256); - algs.add(JWSAlgorithm.ES256K); - algs.add(JWSAlgorithm.ES384); - algs.add(JWSAlgorithm.ES512); - SUPPORTED_ALGORITHMS = Collections.unmodifiableSet(algs); - } - - - /** - * Creates a new Elliptic Curve Digital Signature Algorithm (ECDSA) - * provider. - * - * @param alg The EC-DSA algorithm. Must be supported and not - * {@code null}. - * - * @throws JOSEException If JWS algorithm is not supported. - */ - protected ECDSAProvider(final JWSAlgorithm alg) - throws JOSEException { - - super(new HashSet<>(Collections.singletonList(alg))); - - if (! SUPPORTED_ALGORITHMS.contains(alg)) { - throw new JOSEException("Unsupported EC DSA algorithm: " + alg); - } - } - - - /** - * Returns the supported ECDSA algorithm. - * - * @see #supportedJWSAlgorithms() - * - * @return The supported ECDSA algorithm. - */ - public JWSAlgorithm supportedECDSAAlgorithm() { - - return supportedJWSAlgorithms().iterator().next(); - } -} - diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/EdDSAProvider.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/EdDSAProvider.java deleted file mode 100644 index 321be1f57..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/EdDSAProvider.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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.crypto.impl; - - -import java.util.Collections; -import java.util.Set; - -import com.nimbusds.jose.JWSAlgorithm; - - -/** - * The base abstract class for Edwards-curve Digital Signature Algorithm - * (EdDSA) signers and validators of {@link com.nimbusds.jose.JWSObject JWS - * objects}. - * - *

Supports the following algorithm: - * - *

    - *
  • {@link com.nimbusds.jose.JWSAlgorithm#EdDSA} - *
- * - * @author Tim McLean - * @version 2018-07-11 - */ -public abstract class EdDSAProvider extends BaseJWSProvider { - - - /** - * The supported JWS algorithms by the EdDSA provider class. - */ - public static final Set SUPPORTED_ALGORITHMS; - - - static { - SUPPORTED_ALGORITHMS = Collections.singleton(JWSAlgorithm.EdDSA); - } - - - /** - * Creates a new Edwards-curve Digital Signature Algorithm (EdDSA) - * provider. - */ - protected EdDSAProvider() { - - super(SUPPORTED_ALGORITHMS); - } -} - diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/HMAC.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/HMAC.java deleted file mode 100644 index d79eaa792..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/HMAC.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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.crypto.impl; - - -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.Provider; -import javax.crypto.Mac; -import javax.crypto.SecretKey; -import javax.crypto.spec.SecretKeySpec; - -import com.nimbusds.jose.JOSEException; -import net.jcip.annotations.ThreadSafe; - - -/** - * Static methods for Hash-based Message Authentication Codes (HMAC). This - * class is thread-safe. - * - * @author Axel Nennker - * @author Vladimir Dzhuvinov - * @version 2015-04-23 - */ -@ThreadSafe -public class HMAC { - - - public static Mac getInitMac(final SecretKey secretKey, - final Provider provider) - throws JOSEException { - - Mac mac; - - try { - if (provider != null) { - mac = Mac.getInstance(secretKey.getAlgorithm(), provider); - } else { - mac = Mac.getInstance(secretKey.getAlgorithm()); - } - - mac.init(secretKey); - - } catch (NoSuchAlgorithmException e) { - - throw new JOSEException("Unsupported HMAC algorithm: " + e.getMessage(), e); - - } catch (InvalidKeyException e) { - - throw new JOSEException("Invalid HMAC key: " + e.getMessage(), e); - } - - return mac; - } - - - /** - * Computes a Hash-based Message Authentication Code (HMAC) for the - * specified secret and message. - * - * @param alg The Java Cryptography Architecture (JCA) HMAC - * algorithm name. Must not be {@code null}. - * @param secret The secret. Must not be {@code null}. - * @param message The message. Must not be {@code null}. - * @param provider The JCA provider, or {@code null} to use the default - * one. - * - * @return A MAC service instance. - * - * @throws JOSEException If the algorithm is not supported or the - * MAC secret key is invalid. - */ - public static byte[] compute(final String alg, - final byte[] secret, - final byte[] message, - final Provider provider) - throws JOSEException { - - return compute(new SecretKeySpec(secret, alg), message, provider); - } - - - /** - * Computes a Hash-based Message Authentication Code (HMAC) for the - * specified secret key and message. - * - * @param secretKey The secret key, with the appropriate HMAC - * algorithm. Must not be {@code null}. - * @param message The message. Must not be {@code null}. - * @param provider The JCA provider, or {@code null} to use the - * default one. - * - * @return A MAC service instance. - * - * @throws JOSEException If the algorithm is not supported or the MAC - * secret key is invalid. - */ - public static byte[] compute(final SecretKey secretKey, - final byte[] message, - final Provider provider) - throws JOSEException { - - Mac mac = getInitMac(secretKey, provider); - mac.update(message); - return mac.doFinal(); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/LegacyAESGCM.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/LegacyAESGCM.java deleted file mode 100644 index 3322914fb..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/LegacyAESGCM.java +++ /dev/null @@ -1,219 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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.crypto.impl; - - -import javax.crypto.SecretKey; - -import com.nimbusds.jose.JOSEException; -import net.jcip.annotations.ThreadSafe; -import org.bouncycastle.crypto.BlockCipher; -import org.bouncycastle.crypto.CipherParameters; -import org.bouncycastle.crypto.InvalidCipherTextException; -import org.bouncycastle.crypto.engines.AESEngine; -import org.bouncycastle.crypto.modes.GCMBlockCipher; -import org.bouncycastle.crypto.params.AEADParameters; -import org.bouncycastle.crypto.params.KeyParameter; - - -/** - * Legacy AES/GSM/NoPadding encryption and decryption methods. Uses the - * BouncyCastle.org API. This class is thread-safe. - * - * @author Vladimir Dzhuvinov - * @author Axel Nennker - * @version 2015-11-15 - */ -@ThreadSafe -public class LegacyAESGCM { - - - /** - * The standard authentication tag length (128 bits). - */ - public static final int AUTH_TAG_BIT_LENGTH = 128; - - - /** - * Creates a new AES cipher. - * - * @param secretKey The AES key. Must not be {@code null}. - * @param forEncryption If {@code true} creates an AES encryption - * cipher, else creates an AES decryption - * cipher. - * - * @return The AES cipher. - */ - public static AESEngine createAESCipher(final SecretKey secretKey, - final boolean forEncryption) { - - AESEngine cipher = new AESEngine(); - - CipherParameters cipherParams = new KeyParameter(secretKey.getEncoded()); - - cipher.init(forEncryption, cipherParams); - - return cipher; - } - - - /** - * Creates a new AES/GCM/NoPadding cipher. - * - * @param secretKey The AES key. Must not be {@code null}. - * @param forEncryption If {@code true} creates an encryption cipher, - * else creates a decryption cipher. - * @param iv The initialisation vector (IV). Must not be - * {@code null}. - * @param authData The authenticated data. Must not be - * {@code null}. - * - * @return The AES/GCM/NoPadding cipher. - */ - private static GCMBlockCipher createAESGCMCipher(final SecretKey secretKey, - final boolean forEncryption, - final byte[] iv, - final byte[] authData) { - - // Initialise AES cipher - BlockCipher cipher = createAESCipher(secretKey, forEncryption); - - // Create GCM cipher with AES - GCMBlockCipher gcm = new GCMBlockCipher(cipher); - - AEADParameters aeadParams = new AEADParameters(new KeyParameter(secretKey.getEncoded()), - AUTH_TAG_BIT_LENGTH, - iv, - authData); - gcm.init(forEncryption, aeadParams); - - return gcm; - } - - - /** - * Encrypts the specified plain text using AES/GCM/NoPadding. - * - * @param secretKey The AES key. Must not be {@code null}. - * @param plainText The plain text. Must not be {@code null}. - * @param iv The initialisation vector (IV). Must not be - * {@code null}. - * @param authData The authenticated data. Must not be {@code null}. - * - * @return The authenticated cipher text. - * - * @throws JOSEException If encryption failed. - */ - public static AuthenticatedCipherText encrypt(final SecretKey secretKey, - final byte[] iv, - final byte[] plainText, - final byte[] authData) - throws JOSEException { - - // Initialise AES/GCM cipher for encryption - GCMBlockCipher cipher = createAESGCMCipher(secretKey, true, iv, authData); - - - // Prepare output buffer - int outputLength = cipher.getOutputSize(plainText.length); - byte[] output = new byte[outputLength]; - - - // Produce cipher text - int outputOffset = cipher.processBytes(plainText, 0, plainText.length, output, 0); - - - // Produce authentication tag - try { - outputOffset += cipher.doFinal(output, outputOffset); - - } catch (InvalidCipherTextException e) { - - throw new JOSEException("Couldn't generate GCM authentication tag: " + e.getMessage(), e); - } - - // Split output into cipher text and authentication tag - int authTagLength = AUTH_TAG_BIT_LENGTH / 8; - - byte[] cipherText = new byte[outputOffset - authTagLength]; - byte[] authTag = new byte[authTagLength]; - - System.arraycopy(output, 0, cipherText, 0, cipherText.length); - System.arraycopy(output, outputOffset - authTagLength, authTag, 0, authTag.length); - - return new AuthenticatedCipherText(cipherText, authTag); - } - - - /** - * Decrypts the specified cipher text using AES/GCM/NoPadding. - * - * @param secretKey The AES key. Must not be {@code null}. - * @param iv The initialisation vector (IV). Must not be - * {@code null}. - * @param cipherText The cipher text. Must not be {@code null}. - * @param authData The authenticated data. Must not be {@code null}. - * @param authTag The authentication tag. Must not be {@code null}. - * - * @return The decrypted plain text. - * - * @throws JOSEException If decryption failed. - */ - public static byte[] decrypt(final SecretKey secretKey, - final byte[] iv, - final byte[] cipherText, - final byte[] authData, - final byte[] authTag) - throws JOSEException { - - // Initialise AES/GCM cipher for decryption - GCMBlockCipher cipher = createAESGCMCipher(secretKey, false, iv, authData); - - - // Join cipher text and authentication tag to produce cipher input - byte[] input = new byte[cipherText.length + authTag.length]; - - System.arraycopy(cipherText, 0, input, 0, cipherText.length); - System.arraycopy(authTag, 0, input, cipherText.length, authTag.length); - - int outputLength = cipher.getOutputSize(input.length); - - byte[] output = new byte[outputLength]; - - - // Decrypt - int outputOffset = cipher.processBytes(input, 0, input.length, output, 0); - - // Validate authentication tag - try { - outputOffset += cipher.doFinal(output, outputOffset); - - } catch (InvalidCipherTextException e) { - - throw new JOSEException("Couldn't validate GCM authentication tag: " + e.getMessage(), e); - } - - return output; - } - - - /** - * Prevents public instantiation. - */ - private LegacyAESGCM() { } -} \ No newline at end of file diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/LegacyConcatKDF.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/LegacyConcatKDF.java deleted file mode 100644 index 792c7c1d0..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/LegacyConcatKDF.java +++ /dev/null @@ -1,274 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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.crypto.impl; - - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import javax.crypto.SecretKey; -import javax.crypto.spec.SecretKeySpec; - -import com.nimbusds.jose.EncryptionMethod; -import com.nimbusds.jose.JOSEException; -import com.nimbusds.jose.util.IntegerUtils; -import com.nimbusds.jose.util.StandardCharset; - - -/** - * Legacy implementation of a Concatenation Key Derivation Function (KDF) for - * use by the deprecated {@code A128CBC+HS256} and {@code A256CBC+HS512} - * encryption methods. Provides static methods for deriving the Content - * Encryption Key (CEK) and the Content Integrity Key (CIK) from a Content - * Master Key (CMKs). - * - *

See draft-ietf-jose-json-web-encryption-08, appendices A.4 and A.5. - * - *

See NIST.800-56A. - * - * @author Vladimir Dzhuvinov - * @version 2018-01-04 - */ -public class LegacyConcatKDF { - - - /** - * The four byte array (32-byte) representation of 1. - */ - private static final byte[] ONE_BYTES = { (byte)0, (byte)0, (byte)0, (byte)1 }; - - - /** - * The four byte array (32-bit) representation of 0. - */ - private static final byte[] ZERO_BYTES = { (byte)0, (byte)0, (byte)0, (byte)0 }; - - - /** - * The byte array representation of the string "Encryption". - */ - private static final byte[] ENCRYPTION_BYTES = { - - (byte)69, (byte)110, (byte)99, (byte)114, (byte)121, (byte)112, (byte)116, (byte)105, (byte)111, (byte)110 - }; - - - /** - * The byte array representation of the string "Integrity". - */ - private static final byte[] INTEGRITY_BYTES = { - - (byte)73, (byte)110, (byte)116, (byte)101, (byte)103, (byte)114, (byte)105, (byte)116, (byte)121 - }; - - - /** - * Generates a Content Encryption Key (CEK) from the specified - * Content Master Key (CMK) and JOSE encryption method. - * - * @param key The Content Master Key (CMK). Must not be {@code null}. - * @param enc The JOSE encryption method. Must not be {@code null}. - * @param epu The value of the encryption PartyUInfo header parameter, - * {@code null} if not specified. - * @param epv The value of the encryption PartyVInfo header parameter, - * {@code null} if not specified. - * - * @return The generated AES CEK. - * - * @throws JOSEException If CEK generation failed. - */ - public static SecretKey generateCEK(final SecretKey key, - final EncryptionMethod enc, - final byte[] epu, - final byte[] epv) - throws JOSEException { - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - - int hashBitLength; - - try { - // Write [0, 0, 0, 1] - baos.write(ONE_BYTES); - - // Append CMK - byte[] cmkBytes = key.getEncoded(); - baos.write(cmkBytes); - - // Append [CEK-bit-length...] - final int cmkBitLength = cmkBytes.length * 8; - hashBitLength = cmkBitLength; - final int cekBitLength = cmkBitLength / 2; - byte[] cekBitLengthBytes = IntegerUtils.toBytes(cekBitLength); - baos.write(cekBitLengthBytes); - - // Append the encryption method value, e.g. "A128CBC+HS256" - byte[] encBytes = enc.toString().getBytes(StandardCharset.UTF_8); - baos.write(encBytes); - - // Append encryption PartyUInfo=Datalen || Data - if (epu != null) { - - baos.write(IntegerUtils.toBytes(epu.length)); - baos.write(epu); - - } else { - baos.write(ZERO_BYTES); - } - - // Append encryption PartyVInfo=Datalen || Data - if (epv != null) { - - baos.write(IntegerUtils.toBytes(epv.length)); - baos.write(epv); - - } else { - baos.write(ZERO_BYTES); - } - - // Append "Encryption" label - baos.write(ENCRYPTION_BYTES); - - } catch (IOException e) { - - throw new JOSEException(e.getMessage(), e); - } - - // Write out - byte[] hashInput = baos.toByteArray(); - - MessageDigest md; - - try { - // SHA-256 or SHA-512 - md = MessageDigest.getInstance("SHA-" + hashBitLength); - - } catch (NoSuchAlgorithmException e) { - - throw new JOSEException(e.getMessage(), e); - } - - byte[] hashOutput = md.digest(hashInput); - - byte[] cekBytes = new byte[hashOutput.length / 2]; - System.arraycopy(hashOutput, 0, cekBytes, 0, cekBytes.length); - - return new SecretKeySpec(cekBytes, "AES"); - } - - - /** - * Generates a Content Integrity Key (CIK) from the specified - * Content Master Key (CMK) and JOSE encryption method. - * - * @param key The Content Master Key (CMK). Must not be {@code null}. - * @param enc The JOSE encryption method. Must not be {@code null}. - * @param epu The value of the encryption PartyUInfo header parameter, - * {@code null} if not specified. - * @param epv The value of the encryption PartyVInfo header parameter, - * {@code null} if not specified. - * - * @return The generated HMAC SHA CIK. - * - * @throws JOSEException If CIK generation failed. - */ - public static SecretKey generateCIK(final SecretKey key, - final EncryptionMethod enc, - final byte[] epu, - final byte[] epv) - throws JOSEException { - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - - int hashBitLength; - int cikBitLength; - - try { - // Write [0, 0, 0, 1] - baos.write(ONE_BYTES); - - // Append CMK - byte[] cmkBytes = key.getEncoded(); - baos.write(cmkBytes); - - // Append [CIK-bit-length...] - final int cmkBitLength = cmkBytes.length * 8; - hashBitLength = cmkBitLength; - cikBitLength = cmkBitLength; - byte[] cikBitLengthBytes = IntegerUtils.toBytes(cikBitLength); - baos.write(cikBitLengthBytes); - - // Append the encryption method value, e.g. "A128CBC+HS256" - byte[] encBytes = enc.toString().getBytes(StandardCharset.UTF_8); - baos.write(encBytes); - - // Append encryption PartyUInfo=Datalen || Data - if (epu != null) { - - baos.write(IntegerUtils.toBytes(epu.length)); - baos.write(epu); - - } else { - baos.write(ZERO_BYTES); - } - - // Append encryption PartyVInfo=Datalen || Data - if (epv != null) { - - baos.write(IntegerUtils.toBytes(epv.length)); - baos.write(epv); - - } else { - baos.write(ZERO_BYTES); - } - - // Append "Encryption" label - baos.write(INTEGRITY_BYTES); - - } catch (IOException e) { - - throw new JOSEException(e.getMessage(), e); - } - - // Write out - byte[] hashInput = baos.toByteArray(); - - MessageDigest md; - - try { - // SHA-256 or SHA-512 - md = MessageDigest.getInstance("SHA-" + hashBitLength); - - } catch (NoSuchAlgorithmException e) { - - throw new JOSEException(e.getMessage(), e); - } - - // HMACSHA256 or HMACSHA512 - return new SecretKeySpec(md.digest(hashInput), "HMACSHA" + cikBitLength); - } - - - /** - * Prevents public instantiation. - */ - private LegacyConcatKDF() { - - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/MACProvider.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/MACProvider.java deleted file mode 100644 index c61c38a7d..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/MACProvider.java +++ /dev/null @@ -1,156 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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.crypto.impl; - - -import java.util.Collections; -import java.util.LinkedHashSet; -import java.util.Set; -import javax.crypto.SecretKey; -import javax.crypto.spec.SecretKeySpec; - -import com.nimbusds.jose.JOSEException; -import com.nimbusds.jose.JWSAlgorithm; -import com.nimbusds.jose.KeyLengthException; -import com.nimbusds.jose.util.StandardCharset; - - -/** - * The base abstract class for Message Authentication Code (MAC) signers and - * verifiers of {@link com.nimbusds.jose.JWSObject JWS objects}. - * - *

Supports the following algorithms: - * - *

    - *
  • {@link com.nimbusds.jose.JWSAlgorithm#HS256} - *
  • {@link com.nimbusds.jose.JWSAlgorithm#HS384} - *
  • {@link com.nimbusds.jose.JWSAlgorithm#HS512} - *
- * - * @author Vladimir Dzhuvinov - * @version 2016-07-27 - */ -public abstract class MACProvider extends BaseJWSProvider { - - - /** - * The supported JWS algorithms by the MAC provider class. - */ - public static final Set SUPPORTED_ALGORITHMS; - - - static { - Set algs = new LinkedHashSet<>(); - algs.add(JWSAlgorithm.HS256); - algs.add(JWSAlgorithm.HS384); - algs.add(JWSAlgorithm.HS512); - SUPPORTED_ALGORITHMS = Collections.unmodifiableSet(algs); - } - - - /** - * Gets the matching Java Cryptography Architecture (JCA) algorithm - * name for the specified HMAC-based JSON Web Algorithm (JWA). - * - * @param alg The JSON Web Algorithm (JWA). Must be supported and not - * {@code null}. - * - * @return The matching JCA algorithm name. - * - * @throws JOSEException If the algorithm is not supported. - */ - protected static String getJCAAlgorithmName(final JWSAlgorithm alg) - throws JOSEException { - - if (alg.equals(JWSAlgorithm.HS256)) { - return "HMACSHA256"; - } else if (alg.equals(JWSAlgorithm.HS384)) { - return "HMACSHA384"; - } else if (alg.equals(JWSAlgorithm.HS512)) { - return "HMACSHA512"; - } else { - throw new JOSEException(AlgorithmSupportMessage.unsupportedJWSAlgorithm( - alg, - SUPPORTED_ALGORITHMS)); - } - } - - - /** - * The secret. - */ - private final byte[] secret; - - - /** - * Creates a new Message Authentication (MAC) provider. - * - * @param secret The secret. Must be at least 256 bits long and - * not {@code null}. - * @param supportedAlgs The supported HMAC algorithms. Must not be - * {@code null}. - * - * @throws KeyLengthException If the secret length is shorter than the - * minimum 256-bit requirement. - */ - protected MACProvider(final byte[] secret, - final Set supportedAlgs) - throws KeyLengthException { - - super(supportedAlgs); - - if (secret.length < 256 / 8) { - throw new KeyLengthException("The secret length must be at least 256 bits"); - } - - this.secret = secret; - } - - - /** - * Gets the secret key. - * - * @return The secret key. - */ - public SecretKey getSecretKey() { - - return new SecretKeySpec(secret, "MAC"); - } - - - /** - * Gets the secret bytes. - * - * @return The secret bytes. - */ - public byte[] getSecret() { - - return secret; - } - - - /** - * Gets the secret as a UTF-8 encoded string. - * - * @return The secret as a UTF-8 encoded string. - */ - public String getSecretString() { - - return new String(secret, StandardCharset.UTF_8); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/PBKDF2.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/PBKDF2.java deleted file mode 100644 index b5076e004..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/PBKDF2.java +++ /dev/null @@ -1,223 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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.crypto.impl; - - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import javax.crypto.Mac; -import javax.crypto.SecretKey; -import javax.crypto.spec.SecretKeySpec; - -import com.nimbusds.jose.JOSEException; -import com.nimbusds.jose.JWEAlgorithm; -import com.nimbusds.jose.util.ByteUtils; -import com.nimbusds.jose.util.IntegerUtils; -import com.nimbusds.jose.util.StandardCharset; - - -/** - * Password-Based Key Derivation Function 2 (PBKDF2) utilities. Provides static - * methods to generate Key Encryption Keys (KEK) from passwords. Adopted from - * jose4j by Brian Campbell. - * - * @author Brian Campbell - * @author Yavor Vassilev - * @version 2016-07-26 - */ -public class PBKDF2 { - - - /** - * Zero byte array of length one. - */ - public static byte[] ZERO_BYTE = { 0 }; - - - /** - * Formats the specified cryptographic salt for use in PBKDF2. - * - *
-	 * UTF8(JWE-alg) || 0x00 || Salt Input
-	 * 
- * - * @param alg The JWE algorithm. Must not be {@code null}. - * @param salt The cryptographic salt. Must not be empty or null. - * - * @return The formatted salt for use in PBKDF2. - */ - public static byte[] formatSalt(final JWEAlgorithm alg, final byte[] salt) - throws JOSEException { - - byte[] algBytes = alg.toString().getBytes(StandardCharset.UTF_8); - - ByteArrayOutputStream out = new ByteArrayOutputStream(); - - try { - out.write(algBytes); - out.write(ZERO_BYTE); - out.write(salt); - - } catch (IOException e) { - - throw new JOSEException(e.getMessage(), e); - } - - return out.toByteArray(); - } - - - /** - * Derives a PBKDF2 key from the specified password and parameters. - * - * @param password The password. Must not be {@code null}. - * @param formattedSalt The formatted cryptographic salt. Must not be - * {@code null}. - * @param iterationCount The iteration count. Must be positive. - * @param prfParams The Pseudo-Random Function (PRF) parameters. - * Must not be {@code null}. - * - * @return The derived secret key (with "AES" algorithm). - * - * @throws JOSEException If the key derivation failed. - */ - public static SecretKey deriveKey(final byte[] password, - final byte[] formattedSalt, - final int iterationCount, - final PRFParams prfParams) - throws JOSEException { - - SecretKey macKey = new SecretKeySpec(password, prfParams.getMACAlgorithm()); - - Mac prf = HMAC.getInitMac(macKey, prfParams.getMacProvider()); - - int hLen = prf.getMacLength(); - - // 1. If dkLen > (2^32 - 1) * hLen, output "derived key too long" and - // stop. - long maxDerivedKeyLength = 4294967295L; // value of (long) Math.pow(2, 32) - 1; - if (prfParams.getDerivedKeyByteLength() > maxDerivedKeyLength) { - throw new JOSEException("derived key too long " + prfParams.getDerivedKeyByteLength()); - } - - // 2. Let l be the number of hLen-octet blocks in the derived key, - // rounding up, and let r be the number of octets in the last - // block: - // - // l = CEIL (dkLen / hLen) , - // r = dkLen - (l - 1) * hLen . - // - // Here, CEIL (x) is the "ceiling" function, i.e. the smallest - // integer greater than, or equal to, x. - int l = (int) Math.ceil((double) prfParams.getDerivedKeyByteLength() / (double) hLen); - int r = prfParams.getDerivedKeyByteLength() - (l - 1) * hLen; - - // 3. For each block of the derived key apply the function F defined - // below to the password P, the salt S, the iteration count c, and - // the block index to compute the block: - // - // T_1 = F (P, S, c, 1) , - // T_2 = F (P, S, c, 2) , - // ... - // T_l = F (P, S, c, l) , - // - // where the function F is defined as the exclusive-or sum of the - // first c iterates of the underlying pseudorandom function PRF - // applied to the password P and the concatenation of the salt S - // and the block index i: - // - // F (P, S, c, i) = U_1 \xor U_2 \xor ... \xor U_c - // - // where - // - // U_1 = PRF (P, S || INT (i)) , - // U_2 = PRF (P, U_1) , - // ... - // U_c = PRF (P, U_{c-1}) . - // - // Here, INT (i) is a four-octet encoding of the integer i, most - // significant octet first. - - // 4. Concatenate the blocks and extract the first dkLen octets to - // produce a derived key DK: - // - // DK = T_1 || T_2 || ... || T_l<0..r-1> - // - ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - for (int i = 0; i < l; i++) { - byte[] block = extractBlock(formattedSalt, iterationCount, i + 1, prf); - if (i == (l - 1)) { - block = ByteUtils.subArray(block, 0, r); - } - byteArrayOutputStream.write(block, 0, block.length); - } - - // 5. Output the derived key DK. - return new SecretKeySpec(byteArrayOutputStream.toByteArray(), "AES"); - } - - - /** - * Block extraction iteration. - * - * @param salt The cryptographic salt. Must not be - * {@code null}. - * @param iterationCount The iteration count. - * @param blockIndex The block index. - * @param prf The pseudo-random function (HMAC). Must not be - * {@code null. - * - * @return The block. - */ - private static byte[] extractBlock(byte[] salt, int iterationCount, int blockIndex, Mac prf) { - - byte[] currentU; - byte[] lastU = null; - byte[] xorU = null; - - for (int i = 1; i <= iterationCount; i++) - { - byte[] inputBytes; - if (i == 1) - { - inputBytes = ByteUtils.concat(salt, IntegerUtils.toBytes(blockIndex)); - currentU = prf.doFinal(inputBytes); - xorU = currentU; - } - else - { - currentU = prf.doFinal(lastU); - for (int j = 0; j < currentU.length; j++) - { - xorU[j] = (byte) (currentU[j] ^ xorU[j]); - } - } - - lastU = currentU; - } - return xorU; - } - - - /** - * Prevents public instantiation. - */ - private PBKDF2() { - - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/PRFParams.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/PRFParams.java deleted file mode 100644 index b79542660..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/PRFParams.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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.crypto.impl; - - -import java.security.Provider; - -import com.nimbusds.jose.JOSEException; -import com.nimbusds.jose.JWEAlgorithm; -import net.jcip.annotations.Immutable; - - -/** - * Pseudo-Random Function (PRF) parameters, intended for use in the Password- - * Based Key Derivation Function 2 (PBKDF2). - * - * @author Vladimir Dzhuvinov - * @version 2015-05-26 - */ -@Immutable -public final class PRFParams { - - - /** - * The JCA MAC algorithm name. - */ - private final String jcaMacAlg; - - - /** - * The JCA MAC provider, {@code null} to use the default one. - */ - private final Provider macProvider; - - - /** - * The byte length of the key to derive. - */ - private final int dkLen; - - - /** - * Creates a new pseudo-random function parameters instance. - * - * @param jcaMacAlg The JCA MAC algorithm name. Must not be - * {@code null}. - * @param macProvider The JCA MAC provider, {@code null} to use the - * default one. - * @param dkLen The byte length of the key to derive. - - */ - public PRFParams(String jcaMacAlg, Provider macProvider, int dkLen) { - this.jcaMacAlg = jcaMacAlg; - this.macProvider = macProvider; - this.dkLen = dkLen; - } - - - /** - * Returns the JCA MAC algorithm name. - * - * @return The JCA MAC algorithm name. - */ - public String getMACAlgorithm() { - - return jcaMacAlg; - } - - - /** - * Returns the JCA MAC provider. - * - * @return The JCA MAC provider, {@code null} to use the default one. - */ - public Provider getMacProvider() { - - return macProvider; - } - - - /** - * Returns the byte length of the key to derive. - * - * @return The byte length of the key to derive. - */ - public int getDerivedKeyByteLength() { - - return dkLen; - } - - - /** - * Resolves the Pseudo-Random Function (PRF) parameters for the - * specified PBES2 JWE algorithm. - * - * @param alg The JWE algorithm. Must be supported and not - * {@code null}. - * @param macProvider The specific MAC JCA provider, {@code null} to - * use the default one. - * - * @return The PRF parameters. - * - * @throws JOSEException If the JWE algorithm is not supported. - */ - public static PRFParams resolve(final JWEAlgorithm alg, - final Provider macProvider) - throws JOSEException { - - final String jcaMagAlg; - final int dkLen; - - if (JWEAlgorithm.PBES2_HS256_A128KW.equals(alg)) { - jcaMagAlg = "HmacSHA256"; - dkLen = 16; - } else if (JWEAlgorithm.PBES2_HS384_A192KW.equals(alg)) { - jcaMagAlg = "HmacSHA384"; - dkLen = 24; - } else if (JWEAlgorithm.PBES2_HS512_A256KW.equals(alg)) { - jcaMagAlg = "HmacSHA512"; - dkLen = 32; - } else { - throw new JOSEException(AlgorithmSupportMessage.unsupportedJWEAlgorithm( - alg, - PasswordBasedCryptoProvider.SUPPORTED_ALGORITHMS)); - } - - return new PRFParams(jcaMagAlg, macProvider, dkLen); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/PasswordBasedCryptoProvider.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/PasswordBasedCryptoProvider.java deleted file mode 100644 index 42977de46..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/PasswordBasedCryptoProvider.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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.crypto.impl; - - -import java.util.Collections; -import java.util.LinkedHashSet; -import java.util.Set; - -import com.nimbusds.jose.EncryptionMethod; -import com.nimbusds.jose.JWEAlgorithm; -import com.nimbusds.jose.util.StandardCharset; - - -/** - * The base abstract class for password-based encrypters and decrypters of - * {@link com.nimbusds.jose.JWEObject JWE objects}. - * - *

Supports the following key management algorithms: - * - *

    - *
  • {@link com.nimbusds.jose.JWEAlgorithm#PBES2_HS256_A128KW} - *
  • {@link com.nimbusds.jose.JWEAlgorithm#PBES2_HS384_A192KW} - *
  • {@link com.nimbusds.jose.JWEAlgorithm#PBES2_HS512_A256KW} - *
- * - *

Supports the following content encryption algorithms: - * - *

    - *
  • {@link com.nimbusds.jose.EncryptionMethod#A128CBC_HS256} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A192CBC_HS384} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A256CBC_HS512} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A128GCM} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A192GCM} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A256GCM} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A128CBC_HS256_DEPRECATED} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A256CBC_HS512_DEPRECATED} - *
- * - * @author Vladimir Dzhuvinov - * @version 2016-07-26 - */ -public abstract class PasswordBasedCryptoProvider extends BaseJWEProvider { - - - /** - * The supported JWE algorithms by the password-based crypto provider - * class. - */ - public static final Set SUPPORTED_ALGORITHMS; - - - /** - * The supported encryption methods by the password-base crypto - * provider class. - */ - public static final Set SUPPORTED_ENCRYPTION_METHODS = ContentCryptoProvider.SUPPORTED_ENCRYPTION_METHODS; - - - static { - Set algs = new LinkedHashSet<>(); - algs.add(JWEAlgorithm.PBES2_HS256_A128KW); - algs.add(JWEAlgorithm.PBES2_HS384_A192KW); - algs.add(JWEAlgorithm.PBES2_HS512_A256KW); - SUPPORTED_ALGORITHMS = Collections.unmodifiableSet(algs); - } - - - /** - * The password. - */ - private final byte[] password; - - - /** - * Creates a new password-based encryption / decryption provider. - * - * @param password The password bytes. Must not be empty or - * {@code null}. - */ - protected PasswordBasedCryptoProvider(final byte[] password) { - - super(SUPPORTED_ALGORITHMS, ContentCryptoProvider.SUPPORTED_ENCRYPTION_METHODS); - - if (password == null || password.length == 0) { - throw new IllegalArgumentException("The password must not be null or empty"); - } - - this.password = password; - } - - - /** - * Returns the password. - * - * @return The password bytes. - */ - public byte[] getPassword() { - - return password; - } - - - /** - * Returns the password. - * - * @return The password as a UTF-8 encoded string. - */ - public String getPasswordString() { - - return new String(password, StandardCharset.UTF_8); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/RSA1_5.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/RSA1_5.java deleted file mode 100644 index 4d8421623..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/RSA1_5.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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.crypto.impl; - - -import java.security.PrivateKey; -import java.security.Provider; -import java.security.interfaces.RSAPublicKey; -import javax.crypto.Cipher; -import javax.crypto.IllegalBlockSizeException; -import javax.crypto.SecretKey; -import javax.crypto.spec.SecretKeySpec; - -import com.nimbusds.jose.JOSEException; -import com.nimbusds.jose.util.ByteUtils; -import net.jcip.annotations.ThreadSafe; - - -/** - * RSAES-PKCS1-V1_5 methods for Content Encryption Key (CEK) encryption and - * decryption. This class is thread-safe. - * - * @author Vladimir Dzhuvinov - * @version 2017-06-01 - */ -@ThreadSafe -public class RSA1_5 { - - - /** - * Encrypts the specified Content Encryption Key (CEK). - * - * @param pub The public RSA key. Must not be {@code null}. - * @param cek The Content Encryption Key (CEK) to encrypt. Must - * not be {@code null}. - * @param provider The JCA provider, or {@code null} to use the default - * one. - * - * @return The encrypted Content Encryption Key (CEK). - * - * @throws JOSEException If encryption failed. - */ - public static byte[] encryptCEK(final RSAPublicKey pub, final SecretKey cek, Provider provider) - throws JOSEException { - - try { - Cipher cipher = CipherHelper.getInstance("RSA/ECB/PKCS1Padding", provider); - cipher.init(Cipher.ENCRYPT_MODE, pub); - return cipher.doFinal(cek.getEncoded()); - - } catch (IllegalBlockSizeException e) { - throw new JOSEException("RSA block size exception: The RSA key is too short, try a longer one", e); - } catch (Exception e) { - // java.security.NoSuchAlgorithmException - // java.security.InvalidKeyException - throw new JOSEException("Couldn't encrypt Content Encryption Key (CEK): " + e.getMessage(), e); - } - } - - - /** - * Decrypts the specified encrypted Content Encryption Key (CEK). - * - * @param priv The private RSA key. Must not be {@code null}. - * @param encryptedCEK The encrypted Content Encryption Key (CEK) to - * decrypt. Must not be {@code null}. - * @param provider The JCA provider, or {@code null} to use the - * default one. - * - * @return The decrypted Content Encryption Key (CEK), {@code null} if - * there was a CEK key length mismatch. - * - * @throws JOSEException If decryption failed. - */ - public static SecretKey decryptCEK(final PrivateKey priv, - final byte[] encryptedCEK, - final int keyLength, - final Provider provider) - throws JOSEException { - - try { - Cipher cipher = CipherHelper.getInstance("RSA/ECB/PKCS1Padding", provider); - cipher.init(Cipher.DECRYPT_MODE, priv); - byte[] secretKeyBytes = cipher.doFinal(encryptedCEK); - - if (ByteUtils.safeBitLength(secretKeyBytes) != keyLength) { - // CEK key length mismatch - return null; - } - - return new SecretKeySpec(secretKeyBytes, "AES"); - - } catch (Exception e) { - - // java.security.NoSuchAlgorithmException - // java.security.InvalidKeyException - // javax.crypto.IllegalBlockSizeException - // javax.crypto.BadPaddingException - throw new JOSEException("Couldn't decrypt Content Encryption Key (CEK): " + e.getMessage(), e); - } - } - - - /** - * Prevents public instantiation. - */ - private RSA1_5() { } -} \ No newline at end of file diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/RSACryptoProvider.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/RSACryptoProvider.java deleted file mode 100644 index a1c86f823..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/RSACryptoProvider.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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.crypto.impl; - - -import java.util.Collections; -import java.util.LinkedHashSet; -import java.util.Set; - -import com.nimbusds.jose.EncryptionMethod; -import com.nimbusds.jose.JWEAlgorithm; - - -/** - * The base abstract class for RSA encrypters and decrypters of - * {@link com.nimbusds.jose.JWEObject JWE objects}. - * - *

Supports the following key management algorithms: - * - *

    - *
  • {@link com.nimbusds.jose.JWEAlgorithm#RSA1_5} - *
  • {@link com.nimbusds.jose.JWEAlgorithm#RSA_OAEP} - *
  • {@link com.nimbusds.jose.JWEAlgorithm#RSA_OAEP_256} - *
- * - *

Supports the following content encryption algorithms: - * - *

    - *
  • {@link com.nimbusds.jose.EncryptionMethod#A128CBC_HS256} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A192CBC_HS384} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A256CBC_HS512} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A128GCM} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A192GCM} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A256GCM} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A128CBC_HS256_DEPRECATED} - *
  • {@link com.nimbusds.jose.EncryptionMethod#A256CBC_HS512_DEPRECATED} - *
- * - * @author David Ortiz - * @author Vladimir Dzhuvinov - * @version 2015-05-26 - */ -public abstract class RSACryptoProvider extends BaseJWEProvider { - - - /** - * The supported JWE algorithms by the RSA crypto provider class. - */ - public static final Set SUPPORTED_ALGORITHMS; - - - /** - * The supported encryption methods by the RSA crypto provider class. - */ - public static final Set SUPPORTED_ENCRYPTION_METHODS = ContentCryptoProvider.SUPPORTED_ENCRYPTION_METHODS; - - - static { - Set algs = new LinkedHashSet<>(); - algs.add(JWEAlgorithm.RSA1_5); - algs.add(JWEAlgorithm.RSA_OAEP); - algs.add(JWEAlgorithm.RSA_OAEP_256); - SUPPORTED_ALGORITHMS = Collections.unmodifiableSet(algs); - } - - - /** - * Creates a new RSA encryption / decryption provider. - */ - protected RSACryptoProvider() { - - super(SUPPORTED_ALGORITHMS, ContentCryptoProvider.SUPPORTED_ENCRYPTION_METHODS); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/RSAKeyUtils.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/RSAKeyUtils.java deleted file mode 100644 index 08c314ec7..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/RSAKeyUtils.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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.crypto.impl; - - -import java.security.PrivateKey; -import java.security.interfaces.RSAPrivateKey; - -import com.nimbusds.jose.JOSEException; -import com.nimbusds.jose.jwk.RSAKey; - - -/** - * RSA JWK conversion utility. - */ -public class RSAKeyUtils { - - - /** - * Returns the private RSA key of the specified RSA JWK. Supports - * PKCS#11 keys stores. - * - * @param rsaJWK The RSA JWK. Must not be {@code null}. - * - * @return The private RSA key. - * - * @throws JOSEException If the RSA JWK doesn't contain a private part. - */ - public static PrivateKey toRSAPrivateKey(final RSAKey rsaJWK) - throws JOSEException { - - if (! rsaJWK.isPrivate()) { - throw new JOSEException("The RSA JWK doesn't contain a private part"); - } - - return rsaJWK.toPrivateKey(); - } - - - /** - * Returns the length in bits of the specified RSA private key. - * - * @param privateKey The RSA private key. Must not be {@code null}. - * - * @return The key length in bits, -1 if the length couldn't be - * determined, e.g. for a PKCS#11 backed key which doesn't - * expose an RSAPrivateKey interface or support the - * {@code getModulus()} method. - */ - public static int keyBitLength(final PrivateKey privateKey) { - - if (! (privateKey instanceof RSAPrivateKey)) { - return -1; // May be an PKCS#11 backed key - } - - RSAPrivateKey rsaPrivateKey = (RSAPrivateKey)privateKey; - - try { - return rsaPrivateKey.getModulus().bitLength(); - } catch (Exception e) { - // Some PKCS#11 backed keys still have the - // RSAPrivateKey interface, but will throw an exception - // here - return -1; - } - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/RSASSA.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/RSASSA.java deleted file mode 100644 index 4741d6c47..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/RSASSA.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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.crypto.impl; - - -import java.security.InvalidAlgorithmParameterException; -import java.security.NoSuchAlgorithmException; -import java.security.Provider; -import java.security.Signature; -import java.security.spec.MGF1ParameterSpec; -import java.security.spec.PSSParameterSpec; - -import com.nimbusds.jose.JOSEException; -import com.nimbusds.jose.JWSAlgorithm; - - -/** - * RSA-SSA functions and utilities. - * - * @author Vladimir Dzhuvinov - * @version 2015-05-31 - */ -public class RSASSA { - - - /** - * Returns a signer and verifier for the specified RSASSA-based JSON - * Web Algorithm (JWA). - * - * @param alg The JSON Web Algorithm (JWA). Must be supported and not - * {@code null}. - * - * @return A signer and verifier instance. - * - * @throws JOSEException If the algorithm is not supported. - */ - public static Signature getSignerAndVerifier(final JWSAlgorithm alg, - final Provider provider) - throws JOSEException { - - // The JCE crypto provider uses different alg names - - final String jcaAlg; - - PSSParameterSpec pssSpec = null; - - if (alg.equals(JWSAlgorithm.RS256)) { - jcaAlg = "SHA256withRSA"; - } else if (alg.equals(JWSAlgorithm.RS384)) { - jcaAlg = "SHA384withRSA"; - } else if (alg.equals(JWSAlgorithm.RS512)) { - jcaAlg = "SHA512withRSA"; - } else if (alg.equals(JWSAlgorithm.PS256)) { - jcaAlg = "SHA256withRSAandMGF1"; - // JWA mandates salt length must equal hash - pssSpec = new PSSParameterSpec("SHA256", "MGF1", MGF1ParameterSpec.SHA256, 32, 1); - } else if (alg.equals(JWSAlgorithm.PS384)) { - jcaAlg = "SHA384withRSAandMGF1"; - // JWA mandates salt length must equal hash - pssSpec = new PSSParameterSpec("SHA384", "MGF1", MGF1ParameterSpec.SHA384, 48, 1); - } else if (alg.equals(JWSAlgorithm.PS512)) { - jcaAlg = "SHA512withRSAandMGF1"; - // JWA mandates salt length must equal hash - pssSpec = new PSSParameterSpec("SHA512", "MGF1", MGF1ParameterSpec.SHA512, 64, 1); - } else { - throw new JOSEException(AlgorithmSupportMessage.unsupportedJWSAlgorithm(alg, RSASSAProvider.SUPPORTED_ALGORITHMS)); - } - - final Signature signature; - try { - if (provider != null) { - signature = Signature.getInstance(jcaAlg, provider); - } else { - signature = Signature.getInstance(jcaAlg); - } - } catch (NoSuchAlgorithmException e) { - throw new JOSEException("Unsupported RSASSA algorithm: " + e.getMessage(), e); - } - - - if (pssSpec != null) { - try { - signature.setParameter(pssSpec); - } catch (InvalidAlgorithmParameterException e) { - throw new JOSEException("Invalid RSASSA-PSS salt length parameter: " + e.getMessage(), e); - } - } - - return signature; - } - - - /** - * Prevents public instantiation. - */ - private RSASSA() { - - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/RSASSAProvider.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/RSASSAProvider.java deleted file mode 100644 index 5d7770994..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/RSASSAProvider.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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.crypto.impl; - - -import java.util.Collections; -import java.util.LinkedHashSet; -import java.util.Set; - -import com.nimbusds.jose.JWSAlgorithm; - - -/** - * The base abstract class for RSA signers and verifiers of {@link - * com.nimbusds.jose.JWSObject JWS objects}. - * - *

Supports the following algorithms: - * - *

    - *
  • {@link com.nimbusds.jose.JWSAlgorithm#RS256} - *
  • {@link com.nimbusds.jose.JWSAlgorithm#RS384} - *
  • {@link com.nimbusds.jose.JWSAlgorithm#RS512} - *
  • {@link com.nimbusds.jose.JWSAlgorithm#PS256} - *
  • {@link com.nimbusds.jose.JWSAlgorithm#PS384} - *
  • {@link com.nimbusds.jose.JWSAlgorithm#PS512} - *
- * - * @author Vladimir Dzhuvinov - * @version 2015-05-31 - */ -public abstract class RSASSAProvider extends BaseJWSProvider { - - - /** - * The supported JWS algorithms by the RSA-SSA provider class. - */ - public static final Set SUPPORTED_ALGORITHMS; - - - static { - Set algs = new LinkedHashSet<>(); - algs.add(JWSAlgorithm.RS256); - algs.add(JWSAlgorithm.RS384); - algs.add(JWSAlgorithm.RS512); - algs.add(JWSAlgorithm.PS256); - algs.add(JWSAlgorithm.PS384); - algs.add(JWSAlgorithm.PS512); - SUPPORTED_ALGORITHMS = Collections.unmodifiableSet(algs); - } - - - /** - * Creates a new RSASSA provider. - */ - protected RSASSAProvider() { - - super(SUPPORTED_ALGORITHMS); - } -} - diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/RSA_OAEP.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/RSA_OAEP.java deleted file mode 100644 index a1bb54a0e..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/RSA_OAEP.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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.crypto.impl; - - -import java.security.PrivateKey; -import java.security.Provider; -import java.security.SecureRandom; -import java.security.interfaces.RSAPublicKey; -import javax.crypto.Cipher; -import javax.crypto.IllegalBlockSizeException; -import javax.crypto.SecretKey; -import javax.crypto.spec.SecretKeySpec; - -import com.nimbusds.jose.JOSEException; -import net.jcip.annotations.ThreadSafe; - - -/** - * RSAES OAEP methods for Content Encryption Key (CEK) encryption and - * decryption. Uses the BouncyCastle.org provider. This class is thread-safe - * - * @author Vladimir Dzhuvinov - * @version 2017-11-27 - */ -@ThreadSafe -public class RSA_OAEP { - - - /** - * The JCA algorithm name for RSA-OAEP. - */ - private static final String RSA_OEAP_JCA_ALG = "RSA/ECB/OAEPWithSHA-1AndMGF1Padding"; - - - /** - * Encrypts the specified Content Encryption Key (CEK). - * - * @param pub The public RSA key. Must not be {@code null}. - * @param cek The Content Encryption Key (CEK) to encrypt. Must - * not be {@code null}. - * @param provider The JCA provider, or {@code null} to use the default - * one. - * - * @return The encrypted Content Encryption Key (CEK). - * - * @throws JOSEException If encryption failed. - */ - public static byte[] encryptCEK(final RSAPublicKey pub, final SecretKey cek, final Provider provider) - throws JOSEException { - - try { - Cipher cipher = CipherHelper.getInstance(RSA_OEAP_JCA_ALG, provider); - cipher.init(Cipher.ENCRYPT_MODE, pub, new SecureRandom()); - return cipher.doFinal(cek.getEncoded()); - - } catch (IllegalBlockSizeException e) { - throw new JOSEException("RSA block size exception: The RSA key is too short, try a longer one", e); - } catch (Exception e) { - // java.security.NoSuchAlgorithmException - // java.security.NoSuchPaddingException - // java.security.InvalidKeyException - // javax.crypto.BadPaddingException - throw new JOSEException(e.getMessage(), e); - } - } - - - /** - * Decrypts the specified encrypted Content Encryption Key (CEK). - * - * @param priv The private RSA key. Must not be {@code null}. - * @param encryptedCEK The encrypted Content Encryption Key (CEK) to - * decrypt. Must not be {@code null}. - * @param provider The JCA provider, or {@code null} to use the - * default one. - * - * @return The decrypted Content Encryption Key (CEK). - * - * @throws JOSEException If decryption failed. - */ - public static SecretKey decryptCEK(final PrivateKey priv, - final byte[] encryptedCEK, final Provider provider) - throws JOSEException { - - try { - Cipher cipher = CipherHelper.getInstance(RSA_OEAP_JCA_ALG, provider); - cipher.init(Cipher.DECRYPT_MODE, priv); - return new SecretKeySpec(cipher.doFinal(encryptedCEK), "AES"); - - } catch (Exception e) { - // java.security.NoSuchAlgorithmException - // java.security.NoSuchPaddingException - // java.security.InvalidKeyException - // javax.crypto.IllegalBlockSizeException - // javax.crypto.BadPaddingException - throw new JOSEException(e.getMessage(), e); - } - } - - - /** - * Prevents public instantiation. - */ - private RSA_OAEP() { } -} \ No newline at end of file diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/RSA_OAEP_256.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/RSA_OAEP_256.java deleted file mode 100644 index 41934c7f5..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/RSA_OAEP_256.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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.crypto.impl; - - -import java.security.AlgorithmParameters; -import java.security.PrivateKey; -import java.security.Provider; -import java.security.interfaces.RSAPublicKey; -import java.security.spec.AlgorithmParameterSpec; -import java.security.spec.MGF1ParameterSpec; -import javax.crypto.Cipher; -import javax.crypto.IllegalBlockSizeException; -import javax.crypto.SecretKey; -import javax.crypto.spec.OAEPParameterSpec; -import javax.crypto.spec.PSource; -import javax.crypto.spec.SecretKeySpec; - -import com.nimbusds.jose.JOSEException; -import net.jcip.annotations.ThreadSafe; - - -/** - * RSAES OAEP (SHA-256) methods for Content Encryption Key (CEK) encryption and - * decryption. Uses the BouncyCastle.org provider. This class is thread-safe - * - * @author Vladimir Dzhuvinov - * @author Justin Richer - * @version 2017-11-27 - */ -@ThreadSafe -public class RSA_OAEP_256 { - - - /** - * The JCA algorithm name for RSA-OAEP-256. - */ - private static final String RSA_OEAP_256_JCA_ALG = "RSA/ECB/OAEPWithSHA-256AndMGF1Padding"; - - - /** - * Encrypts the specified Content Encryption Key (CEK). - * - * @param pub The public RSA key. Must not be {@code null}. - * @param cek The Content Encryption Key (CEK) to encrypt. Must - * not be {@code null}. - * @param provider The JCA provider, or {@code null} to use the default - * one. - * - * @return The encrypted Content Encryption Key (CEK). - * - * @throws JOSEException If encryption failed. - */ - public static byte[] encryptCEK(final RSAPublicKey pub, final SecretKey cek, final Provider provider) - throws JOSEException { - - try { - AlgorithmParameters algp = AlgorithmParametersHelper.getInstance("OAEP", provider); - AlgorithmParameterSpec paramSpec = new OAEPParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT); - algp.init(paramSpec); - Cipher cipher = CipherHelper.getInstance(RSA_OEAP_256_JCA_ALG, provider); - cipher.init(Cipher.ENCRYPT_MODE, pub, algp); - return cipher.doFinal(cek.getEncoded()); - - } catch (IllegalBlockSizeException e) { - throw new JOSEException("RSA block size exception: The RSA key is too short, try a longer one", e); - } catch (Exception e) { - // java.security.NoSuchAlgorithmException - // java.security.NoSuchPaddingException - // java.security.InvalidKeyException - // javax.crypto.BadPaddingException - throw new JOSEException(e.getMessage(), e); - } - } - - - /** - * Decrypts the specified encrypted Content Encryption Key (CEK). - * - * @param priv The private RSA key. Must not be {@code null}. - * @param encryptedCEK The encrypted Content Encryption Key (CEK) to - * decrypt. Must not be {@code null}. - * @param provider The JCA provider, or {@code null} to use the - * default one. - * - * @return The decrypted Content Encryption Key (CEK). - * - * @throws JOSEException If decryption failed. - */ - public static SecretKey decryptCEK(final PrivateKey priv, - final byte[] encryptedCEK, final Provider provider) - throws JOSEException { - - try { - AlgorithmParameters algp = AlgorithmParametersHelper.getInstance("OAEP", provider); - AlgorithmParameterSpec paramSpec = new OAEPParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT); - algp.init(paramSpec); - Cipher cipher = CipherHelper.getInstance(RSA_OEAP_256_JCA_ALG, provider); - cipher.init(Cipher.DECRYPT_MODE, priv, algp); - return new SecretKeySpec(cipher.doFinal(encryptedCEK), "AES"); - - } catch (Exception e) { - // java.security.NoSuchAlgorithmException - // java.security.NoSuchPaddingException - // java.security.InvalidKeyException - // javax.crypto.IllegalBlockSizeException - // javax.crypto.BadPaddingException - throw new JOSEException(e.getMessage(), e); - } - } - - - /** - * Prevents public instantiation. - */ - private RSA_OAEP_256() { } -} \ No newline at end of file diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/package-info.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/package-info.java deleted file mode 100644 index d7fbad55e..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/impl/package-info.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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. - */ -/** - * Cryptographic primitives and framework for the JWS signers / verifiers and - * JWE encrypters / decrypters in the {@link com.nimbusds.jose.crypto} package. - */ -package com.nimbusds.jose.crypto.impl; \ No newline at end of file diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/package-info.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/package-info.java deleted file mode 100644 index c6c14e581..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/package-info.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * 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. - */ - -/** - * Implementations of all standard Javascript Object Signing and Encryption - * (JOSE) algorithms. - * - *

Provides {@link com.nimbusds.jose.JWSSigner signers} and - * {@link com.nimbusds.jose.JWSVerifier verifiers} for the following JSON Web - * Signature (JWS) algorithms: - * - *

    - *
  • For HMAC algorithms HS256, HS384 and HS512: - *
      - *
    • {@link com.nimbusds.jose.crypto.MACSigner} - *
    • {@link com.nimbusds.jose.crypto.MACVerifier} - *
    - *
  • For RSA-SSA signatures RS256, RS384, RS512, PS256, PS384 and PS512: - *
      - *
    • {@link com.nimbusds.jose.crypto.RSASSASigner} - *
    • {@link com.nimbusds.jose.crypto.RSASSAVerifier} - *
    - *
  • For ECDSA signatures ES256, ES384 and ES512: - *
      - *
    • {@link com.nimbusds.jose.crypto.ECDSASigner} - *
    • {@link com.nimbusds.jose.crypto.ECDSAVerifier} - *
    - *
  • For EdDSA signatures Ed25519: - *
      - *
    • {@link com.nimbusds.jose.crypto.Ed25519Signer} - *
    • {@link com.nimbusds.jose.crypto.Ed25519Verifier} - *
    - *
- * - *

Provides {@link com.nimbusds.jose.JWEEncrypter encrypters} and - * {@link com.nimbusds.jose.JWEDecrypter decrypters} for the following JSON - * Web Encryption (JWE) algorithms: - * - *

    - *
  • For RSA PKCS#1 v1.5 and RSA OAEP: - *
      - *
    • {@link com.nimbusds.jose.crypto.RSAEncrypter} - *
    • {@link com.nimbusds.jose.crypto.RSADecrypter} - *
    - *
  • For AES key wrap and AES GCM key encryption: - *
      - *
    • {@link com.nimbusds.jose.crypto.AESEncrypter} - *
    • {@link com.nimbusds.jose.crypto.AESDecrypter} - *
    - *
  • For direct encryption (using a shared symmetric key): - *
      - *
    • {@link com.nimbusds.jose.crypto.DirectEncrypter} - *
    • {@link com.nimbusds.jose.crypto.DirectDecrypter} - *
    - *
  • For Elliptic Curve Diffie-Hellman (ECDH) encryption: - *
      - *
    • {@link com.nimbusds.jose.crypto.ECDHEncrypter} - *
    • {@link com.nimbusds.jose.crypto.ECDHDecrypter} - *
    • {@link com.nimbusds.jose.crypto.X25519Encrypter} (for Curve25519 only) - *
    • {@link com.nimbusds.jose.crypto.X25519Decrypter} (for Curve25519 only) - *
    - *
  • For password-based (PBKDF2) encryption: - *
      - *
    • {@link com.nimbusds.jose.crypto.PasswordBasedEncrypter} - *
    • {@link com.nimbusds.jose.crypto.PasswordBasedDecrypter} - *
    - *
- * - *

References: - * - *

- */ -package com.nimbusds.jose.crypto; diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/utils/ConstantTimeUtils.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/utils/ConstantTimeUtils.java deleted file mode 100644 index 518667656..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/utils/ConstantTimeUtils.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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.crypto.utils; - - -/** - * Array utilities. - * - * @author Vladimir Dzhuvinov - * @version 2017-04-26 - */ -public class ConstantTimeUtils { - - - /** - * Checks the specified arrays for equality in constant time. Intended - * to mitigate timing attacks. - * - * @param a The first array. Must not be {@code null}. - * @param b The second array. Must not be {@code null}. - * - * @return {@code true} if the two arrays are equal, else - * {@code false}. - */ - public static boolean areEqual(final byte[] a, final byte[] b) { - - // From http://codahale.com/a-lesson-in-timing-attacks/ - - if (a.length != b.length) { - return false; - } - - int result = 0; - for (int i = 0; i < a.length; i++) { - result |= a[i] ^ b[i]; - } - - return result == 0; - } - - - /** - * Prevents public instantiation. - */ - private ConstantTimeUtils() { } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/utils/ECChecks.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/utils/ECChecks.java deleted file mode 100644 index e2bc2264c..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/utils/ECChecks.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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.crypto.utils; - - -import java.math.BigInteger; -import java.security.interfaces.ECPrivateKey; -import java.security.interfaces.ECPublicKey; -import java.security.spec.ECFieldFp; -import java.security.spec.ECParameterSpec; -import java.security.spec.ECPoint; -import java.security.spec.EllipticCurve; - - -/** - * Elliptic curve checks. - * - * @author Vladimir Dzhuvinov - * @version 2017-04-13 - */ -public class ECChecks { - - - /** - * Checks if the specified (ephemeral) public key is on the curve of - * the private key. Intended to prevent an "Invalid Curve Attack", - * independent from any JCA provider checks (the SUN provider in Java - * 1.8.0_51+ and BouncyCastle have them, other / older provider do - * not). - * - *

See https://www.cs.bris.ac.uk/Research/CryptographySecurity/RWC/2017/nguyen.quan.pdf - * - * @param publicKey The public EC key. Must not be {@code null}. - * @param privateKey The private EC key. Must not be {@code null}. - * - * @return {@code true} if public key passed the curve check. - */ - public static boolean isPointOnCurve(final ECPublicKey publicKey, final ECPrivateKey privateKey) { - - return isPointOnCurve(publicKey, privateKey.getParams()); - } - - - /** - * Checks if the specified (ephemeral) public key is on the given - * curve. Intended to prevent an "Invalid Curve Attack", independent - * from any JCA provider checks (the SUN provider in Java 1.8.0_51+ and - * BouncyCastle have them, other / older provider do not). - * - *

See https://www.cs.bris.ac.uk/Research/CryptographySecurity/RWC/2017/nguyen.quan.pdf - * - * @param publicKey The public EC key. Must not be {@code null}. - * @param ecParameterSpec The EC spec. Must not be {@code null}. - * - * @return {@code true} if public key passed the curve check. - */ - public static boolean isPointOnCurve(final ECPublicKey publicKey, final ECParameterSpec ecParameterSpec) { - - ECPoint point = publicKey.getW(); - return isPointOnCurve(point.getAffineX(), point.getAffineY(), ecParameterSpec); - } - - - /** - * Checks if the specified (ephemeral) public key is on the given - * curve. Intended to prevent an "Invalid Curve Attack", independent - * from any JCA provider checks (the SUN provider in Java 1.8.0_51+ and - * BouncyCastle have them, other / older provider do not). - * - *

See https://www.cs.bris.ac.uk/Research/CryptographySecurity/RWC/2017/nguyen.quan.pdf - * - * @param x The public EC x coordinate. Must not be - * {@code null}. - * @param y The public EC y coordinate. Must not be - * {@code null}. - * @param ecParameterSpec The EC spec. Must not be {@code null}. - * - * @return {@code true} if public key passed the curve check. - */ - public static boolean isPointOnCurve(final BigInteger x, final BigInteger y, final ECParameterSpec ecParameterSpec) { - - // Ensure the following condition is met: - // (y^2) mod p = (x^3 + ax + b) mod p - EllipticCurve curve = ecParameterSpec.getCurve(); - BigInteger a = curve.getA(); - BigInteger b = curve.getB(); - BigInteger p = ((ECFieldFp) curve.getField()).getP(); - BigInteger leftSide = (y.pow(2)).mod(p); - BigInteger rightSide = (x.pow(3).add(a.multiply(x)).add(b)).mod(p); - - return leftSide.equals(rightSide); - } - - - /** - * Prevents public instantiation. - */ - private ECChecks() {} -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/utils/package-info.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/utils/package-info.java deleted file mode 100644 index d5b3ec66b..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/crypto/utils/package-info.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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. - */ - -/** - * Cryptographic utilities. - */ -package com.nimbusds.jose.crypto.utils; \ No newline at end of file diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jca/JCAAware.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jca/JCAAware.java deleted file mode 100644 index f2970f513..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jca/JCAAware.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * 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.jca; - - -/** - * Interface for a Java Cryptography Architecture (JCA) aware object, intended - * for setting a JCA {@link java.security.Provider provider} and - * {@link java.security.SecureRandom secure random generator}. - * - * @version 2015-06-30 - */ -public interface JCAAware { - - - /** - * Returns the Java Cryptography Architecture (JCA) context. May be - * used to set a specific JCA security provider or secure random - * generator. - * - * @return The JCA context. Not {@code null}. - */ - T getJCAContext(); -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jca/JCAContext.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jca/JCAContext.java deleted file mode 100644 index e0722460c..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jca/JCAContext.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * 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.jca; - - -import java.security.Provider; -import java.security.SecureRandom; - - -/** - * Java Cryptography Architecture (JCA) context, consisting of a JCA - * {@link java.security.Provider provider} and - * {@link java.security.SecureRandom secure random generator}. - * - * @author Vladimir Dzhuvinov - * @version 2015-06-08 - */ -public class JCAContext { - - - /** - * The JCA provider. - */ - private Provider provider; - - - /** - * The secure random generator. - */ - private SecureRandom randomGen; - - - /** - * Creates a new default JCA context. - */ - public JCAContext() { - - this(null, null); - } - - - /** - * Creates a new JCA context. - * - * @param provider The JCA provider, {@code null} to use the default - * system one. - * @param randomGen The specific secure random generator, {@code null} - * to use the default system one. - */ - public JCAContext(final Provider provider, final SecureRandom randomGen) { - - this.provider = provider; - this.randomGen = randomGen; - } - - - /** - * Gets the JCA provider to be used for all operations. - * - * @return The JCA provider to be used for all operations where a more - * specific one is absent, {@code null} implies the default - * system provider. - */ - public Provider getProvider() { - - return provider; - } - - - /** - * Sets the JCA provider to be used for all operations. - * - * @param provider The JCA provider to be used for all operations where - * a more specific one is absent, {@code null} to use - * the default system provider. - */ - public void setProvider(final Provider provider) { - - this.provider = provider; - } - - - /** - * Gets the secure random generator. Intended for generation of - * initialisation vectors and other purposes that require a secure - * random generator. - * - * @return The specific secure random generator (if available), else - * the default system one. - */ - public SecureRandom getSecureRandom() { - - return randomGen != null ? randomGen : new SecureRandom(); - } - - - /** - * Sets a specific secure random generator for the initialisation - * vector and other purposes requiring a random number. - * - * @param randomGen The secure random generator, {@code null} to use - * the default system one. - */ - public void setSecureRandom(final SecureRandom randomGen) { - - this.randomGen = randomGen; - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jca/JCASupport.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jca/JCASupport.java deleted file mode 100644 index 8c91b003c..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jca/JCASupport.java +++ /dev/null @@ -1,375 +0,0 @@ -/* - * 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.jca; - - -import java.security.NoSuchAlgorithmException; -import java.security.Provider; -import java.security.Security; -import javax.crypto.Cipher; -import javax.crypto.NoSuchPaddingException; - -import com.nimbusds.jose.Algorithm; -import com.nimbusds.jose.EncryptionMethod; -import com.nimbusds.jose.JWEAlgorithm; -import com.nimbusds.jose.JWSAlgorithm; - - -/** - * Java Cryptography Architecture (JCA) support helper. - */ -public final class JCASupport { - - - /** - * Checks if unlimited cryptographic strength is supported. If not - * download the appropriate jurisdiction policy files for your Java - * edition: - * - *

JCE Unlimited Strength Jurisdiction Policy Files for Java 7 - * - *

JCE Unlimited Strength Jurisdiction Policy Files for Java 8 - * - * @return {@code true} if unlimited cryptographic strength is - * supported, {@code false} if not. - */ - public static boolean isUnlimitedStrength() { - - try { - return Cipher.getMaxAllowedKeyLength("AES") >= 256; - } catch (NoSuchAlgorithmException e) { - return false; - } - } - - - /** - * Checks if the specified JOSE algorithm is supported by the default - * system JCA provider(s). - * - * @param alg The JOSE algorithm. Must not be {@code null}. - * - * @return {@code true} if the JOSE algorithm is supported, else - * {@code false}. - */ - public static boolean isSupported(final Algorithm alg) { - - if (alg instanceof JWSAlgorithm) { - return isSupported((JWSAlgorithm)alg); - } - if (alg instanceof JWEAlgorithm) { - return isSupported((JWEAlgorithm)alg); - } - if (alg instanceof EncryptionMethod) { - return isSupported((EncryptionMethod)alg); - } - throw new IllegalArgumentException("Unexpected algorithm class: " + alg.getClass().getCanonicalName()); - } - - - /** - * Checks if a JOSE algorithm is supported by the the specified JCA - * provider. - * - * @param alg The JOSE algorithm. Must not be {@code null}. - * @param provider The JCA provider. Must not be {@code null}. - * - * @return {@code true} if the JOSE algorithm is supported, else - * {@code false}. - */ - public static boolean isSupported(final Algorithm alg, final Provider provider) { - - if (alg instanceof JWSAlgorithm) { - return isSupported((JWSAlgorithm)alg, provider); - } - if (alg instanceof JWEAlgorithm) { - return isSupported((JWEAlgorithm)alg, provider); - } - if (alg instanceof EncryptionMethod) { - return isSupported((EncryptionMethod)alg, provider); - } - throw new IllegalArgumentException("Unexpected algorithm class: " + alg.getClass().getCanonicalName()); - } - - - /** - * Checks if the specified JWS algorithm is supported by the default - * system JCA provider(s). - * - * @param alg The JWS algorithm. Must not be {@code null}. - * - * @return {@code true} if the JWS algorithm is supported, else - * {@code false}. - */ - public static boolean isSupported(final JWSAlgorithm alg) { - - if (alg.getName().equals(Algorithm.NONE.getName())) { - return true; - } - - for (Provider p: Security.getProviders()) { - - if (isSupported(alg, p)) { - return true; - } - } - - return false; - } - - - /** - * Checks if a JWS algorithm is supported by the the specified JCA - * provider. - * - * @param alg The JWS algorithm. Must not be {@code null}. - * @param provider The JCA provider. Must not be {@code null}. - * - * @return {@code true} if the JWS algorithm is supported, else - * {@code false}. - */ - public static boolean isSupported(final JWSAlgorithm alg, final Provider provider) { - - if (JWSAlgorithm.Family.HMAC_SHA.contains(alg)) { - String jcaName; - if (alg.equals(JWSAlgorithm.HS256)) { - jcaName = "HMACSHA256"; - } else if (alg.equals(JWSAlgorithm.HS384)) { - jcaName = "HMACSHA384"; - } else if (alg.equals(JWSAlgorithm.HS512)) { - jcaName = "HMACSHA512"; - } else { - return false; - } - return provider.getService("KeyGenerator", jcaName) != null; - } - - if (JWSAlgorithm.Family.RSA.contains(alg)) { - String jcaName; - if (alg.equals(JWSAlgorithm.RS256)) { - jcaName = "SHA256withRSA"; - } else if (alg.equals(JWSAlgorithm.RS384)) { - jcaName = "SHA384withRSA"; - } else if (alg.equals(JWSAlgorithm.RS512)) { - jcaName = "SHA512withRSA"; - } else if (alg.equals(JWSAlgorithm.PS256)) { - jcaName = "SHA256withRSAandMGF1"; - } else if (alg.equals(JWSAlgorithm.PS384)) { - jcaName = "SHA384withRSAandMGF1"; - } else if (alg.equals(JWSAlgorithm.PS512)) { - jcaName = "SHA512withRSAandMGF1"; - } else { - return false; - } - return provider.getService("Signature", jcaName) != null; - } - - if (JWSAlgorithm.Family.EC.contains(alg)) { - String jcaName; - if (alg.equals(JWSAlgorithm.ES256)) { - jcaName = "SHA256withECDSA"; - } else if (alg.equals(JWSAlgorithm.ES384)) { - jcaName = "SHA384withECDSA"; - } else if (alg.equals(JWSAlgorithm.ES512)) { - jcaName = "SHA512withECDSA"; - } else { - return false; - } - return provider.getService("Signature", jcaName) != null; - } - - return false; - } - - - /** - * Checks if the specified JWE algorithm is supported by the default - * system JCA provider(s). - * - * @param alg The JWE algorithm. Must not be {@code null}. - * - * @return {@code true} if the JWE algorithm is supported, else - * {@code false}. - */ - public static boolean isSupported(final JWEAlgorithm alg) { - - for (Provider p: Security.getProviders()) { - - if (isSupported(alg, p)) { - return true; - } - } - - return false; - } - - - /** - * Checks if a JWE algorithm is supported by the the specified JCA - * provider. - * - * @param alg The JWE algorithm. Must not be {@code null}. - * @param provider The JCA provider. Must not be {@code null}. - * - * @return {@code true} if the JWE algorithm is supported, else - * {@code false}. - */ - public static boolean isSupported(final JWEAlgorithm alg, final Provider provider) { - - String jcaName; - - if (JWEAlgorithm.Family.RSA.contains(alg)) { - if (alg.equals(JWEAlgorithm.RSA1_5)) { - jcaName = "RSA/ECB/PKCS1Padding"; - } else if (alg.equals(JWEAlgorithm.RSA_OAEP)) { - jcaName = "RSA/ECB/OAEPWithSHA-1AndMGF1Padding"; - } else if (alg.equals(JWEAlgorithm.RSA_OAEP_256)) { - jcaName = "RSA/ECB/OAEPWithSHA-256AndMGF1Padding"; - } else { - return false; - } - - // Do direct test - try { - Cipher.getInstance(jcaName, provider); - } catch (NoSuchAlgorithmException e) { - return false; - } catch (NoSuchPaddingException e) { - return false; - } - return true; - } - - if (JWEAlgorithm.Family.AES_KW.contains(alg)) { - return provider.getService("Cipher", "AESWrap") != null; - } - - if (JWEAlgorithm.Family.ECDH_ES.contains(alg)) { - return provider.getService("KeyAgreement", "ECDH") != null; - } - - if (JWEAlgorithm.Family.AES_GCM_KW.contains(alg)) { - // Do direct test - try { - Cipher.getInstance("AES/GCM/NoPadding", provider); - } catch (NoSuchAlgorithmException e) { - return false; - } catch (NoSuchPaddingException e) { - return false; - } - return true; - } - - if (JWEAlgorithm.Family.PBES2.contains(alg)) { - String hmac; - if (alg.equals(JWEAlgorithm.PBES2_HS256_A128KW)) { - hmac = "HmacSHA256"; - } else if (alg.equals(JWEAlgorithm.PBES2_HS384_A192KW)) { - hmac = "HmacSHA384"; - } else { - hmac = "HmacSHA512"; - } - return provider.getService("KeyGenerator", hmac) != null; - } - - if (JWEAlgorithm.DIR.equals(alg)) { - return true; // Always supported - } - - return false; - } - - - /** - * Checks if the specified JWE encryption method is supported by the - * default system JCA provider(s). - * - * @param enc The JWE encryption method. Must not be {@code null}. - * - * @return {@code true} if the JWE algorithm is supported, else - * {@code false}. - */ - public static boolean isSupported(final EncryptionMethod enc) { - - for (Provider p: Security.getProviders()) { - - if (isSupported(enc, p)) { - return true; - } - } - - return false; - } - - - /** - * Checks if a JWE encryption method is supported by the specified - * JCA provider. - * - * @param enc The JWE encryption method. Must not be {@code null}. - * @param provider The JCA provider. Must not be {@code null}. - * - * @return {@code true} if the JWE encryption method is supported, else - * {@code false}. - */ - public static boolean isSupported(final EncryptionMethod enc, final Provider provider) { - - if (EncryptionMethod.Family.AES_CBC_HMAC_SHA.contains(enc)) { - // Do direct test - try { - Cipher.getInstance("AES/CBC/PKCS5Padding", provider); - } catch (NoSuchAlgorithmException e) { - return false; - } catch (NoSuchPaddingException e) { - return false; - } - // Check hmac - String hmac; - if (enc.equals(EncryptionMethod.A128CBC_HS256)) { - hmac = "HmacSHA256"; - } else if (enc.equals(EncryptionMethod.A192CBC_HS384)) { - hmac = "HmacSHA384"; - } else { - hmac = "HmacSHA512"; - } - return provider.getService("KeyGenerator", hmac) != null; - } - - if (EncryptionMethod.Family.AES_GCM.contains(enc)) { - // Do direct test - try { - Cipher.getInstance("AES/GCM/NoPadding", provider); - } catch (NoSuchAlgorithmException e) { - return false; - } catch (NoSuchPaddingException e) { - return false; - } - return true; - } - - return false; - } - - - /** - * Prevents public instantiation. - */ - private JCASupport() { - - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jca/JWEJCAContext.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jca/JWEJCAContext.java deleted file mode 100644 index 737c67755..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jca/JWEJCAContext.java +++ /dev/null @@ -1,182 +0,0 @@ -/* - * 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.jca; - - -import java.security.Provider; -import java.security.SecureRandom; - - -/** - * Java Cryptography Architecture (JCA) context intended specifically for - * JSON Web Encryption (JWE) providers. Allows setting of more specific JCA - * providers for key encryption, content encryption and MAC computation. - * - * @author Vladimir Dzhuvinov - * @version 2015-06-08 - */ -public final class JWEJCAContext extends JCAContext { - - - /** - * The key encryption provider. - */ - private Provider keProvider; - - - /** - * The content encryption provider. - */ - private Provider ceProvider; - - - /** - * The MAC provider. - */ - private Provider macProvider; - - - /** - * Creates a new default JCA context for JWE. - */ - public JWEJCAContext() { - - this(null, null, null, null, null); - } - - - /** - * Creates a new JCA context for JWE with the specified JCA providers - * and secure random generator. - * - * @param generalProvider The general JCA provider to be used for all - * operations where a more specific one is - * absent, {@code null} to use the default - * system provider. - * @param keProvider The specific JCA provider to be used for the - * key encryption, {@code null} to fall back to - * the general one, and if that is not specified - * to the default system provider. - * @param ceProvider The specific JCA provider to be used for the - * content encryption, {@code null} to fall back - * to the general one, and if that is not - * specified to the default system provider. - * @param macProvider The specific JCA provider to be used for the - * MAC computation (where required by the JWE - * encryption method), {@code null} to fall back - * to the general one, and if that is not - * specified to the default system provider. - * @param randomGen The specific secure random generator for the - * initialisation vector and other purposes - * requiring a random number, {@code null} to - * use the default system one. - */ - public JWEJCAContext(final Provider generalProvider, - final Provider keProvider, - final Provider ceProvider, - final Provider macProvider, - final SecureRandom randomGen) { - - super(generalProvider, randomGen); - this.keProvider = keProvider; - this.ceProvider = ceProvider; - this.macProvider = macProvider; - } - - - - /** - * Sets a specific JCA provider for the key encryption. - * - * @param keProvider The specific JCA provider to be used for the key - * encryption, {@code null} to fall back to the - * general one, and if that is not specified to the - * default system provider. - */ - public void setKeyEncryptionProvider(final Provider keProvider) { - - this.keProvider = keProvider; - } - - - /** - * Gets the specific JCA provider for the key encryption. - * - * @return The applicable JCA provider, {@code null} implies the - * default system provider. - */ - public Provider getKeyEncryptionProvider() { - - return keProvider != null ? keProvider : getProvider(); - } - - - /** - * Sets a specific JCA provider for the content encryption. - * - * @param ceProvider The specific JCA provider to be used for the - * content encryption, {@code null} to fall back to - * the general one, and if that is not specified to - * the default system provider. - */ - public void setContentEncryptionProvider(final Provider ceProvider) { - - this.ceProvider = ceProvider; - } - - - /** - * Gets the specific JCA provider for the content encryption. - * - * @return The applicable JCA provider, {@code null} implies the - * default system provider. - */ - public Provider getContentEncryptionProvider() { - - return ceProvider != null ? ceProvider : getProvider(); - } - - - /** - * Sets a specific JCA provider for the MAC computation (where required - * by the JWE encryption method). - * - * @param macProvider The specific JCA provider to be used for the MAC - * computation (where required by the JWE encryption - * method), {@code null} to fall back to the general - * one, and if that is not specified to the default - * system provider. - */ - public void setMACProvider(final Provider macProvider) { - - this.macProvider = macProvider; - } - - - /** - * Gets the specific JCA provider for the MAC computation (where - * required by the JWE encryption method). - * - * @return The applicable JCA provider, {@code null} implies the - * default system provider. - */ - public Provider getMACProvider() { - - return macProvider != null ? macProvider : getProvider(); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jca/package-info.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jca/package-info.java deleted file mode 100644 index 57ff3a934..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jca/package-info.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * 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. - */ - -/** - * Java Cryptography Architecture (JCA) context interfaces and classes. - * - *

References: - * - *

- */ -package com.nimbusds.jose.jca; \ No newline at end of file diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/AsymmetricJWK.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/AsymmetricJWK.java deleted file mode 100644 index 04cc15194..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/AsymmetricJWK.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * 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.jwk; - - -import java.security.KeyPair; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.cert.X509Certificate; - -import com.nimbusds.jose.JOSEException; - - -/** - * Asymmetric (pair) JSON Web Key (JWK). - * - * @author Vladimir Dzhuvinov - * @version 2018-02-27 - */ -public interface AsymmetricJWK { - - - /** - * Returns a Java public key representation of the JWK. - * - * @return The Java public key. - * - * @throws JOSEException If conversion failed or is not supported. - */ - PublicKey toPublicKey() - throws JOSEException; - - - /** - * Returns a Java private key representation of this JWK. - * - * @return The Java private key, {@code null} if not specified. - * - * @throws JOSEException If conversion failed or is not supported. - */ - PrivateKey toPrivateKey() - throws JOSEException; - - - /** - * Returns a Java key pair representation of this JWK. - * - * @return The Java key pair. The private key will be {@code null} if - * not specified. - * - * @throws JOSEException If conversion failed or is not supported. - */ - KeyPair toKeyPair() - throws JOSEException; - - - /** - * Returns {@code true} if the public key material of this JWK matches - * the public subject key info of the specified X.509 certificate. - * - * @param cert The X.509 certificate. Must not be {@code null}. - * - * @return {@code true} if the public key material of this JWK matches - * the public subject key info of the specified X.509 - * certificate, else {@code false}. - */ - boolean matches(X509Certificate cert); -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/Curve.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/Curve.java deleted file mode 100644 index 211521ceb..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/Curve.java +++ /dev/null @@ -1,371 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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.jwk; - - -import java.io.Serializable; -import java.security.spec.ECParameterSpec; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; -import java.util.Set; - -import com.nimbusds.jose.JWSAlgorithm; -import net.jcip.annotations.Immutable; - - -/** - * Cryptographic curve. This class is immutable. - * - *

Includes constants for the following standard cryptographic curves: - * - *

    - *
  • {@link #P_256} - *
  • {@link #P_256K} - *
  • {@link #P_384} - *
  • {@link #P_521} - *
  • {@link #Ed25519} - *
  • {@link #Ed448} - *
  • {@link #X25519} - *
  • {@link #X448} - *
- * - *

See - * - *

    - *
  • "Digital Signature Standard (DSS)", FIPS PUB 186-3, June 2009, - * National Institute of Standards and Technology (NIST). - *
  • CFRG Elliptic Curve Diffie-Hellman (ECDH) and Signatures in JSON - * Object Signing and Encryption (JOSE) (RFC 8037). - *
- * - * @author Vladimir Dzhuvinov - * @author Aleksei Doroganov - * @version 2013-03-28 - */ -@Immutable -public final class Curve implements Serializable { - - - private static final long serialVersionUID = 1L; - - - /** - * P-256 curve (secp256r1, also called prime256v1, OID = - * 1.2.840.10045.3.1.7). - */ - public static final Curve P_256 = new Curve("P-256", "secp256r1", "1.2.840.10045.3.1.7"); - - - /** - * P-256K curve (secp256k1, OID = 1.3.132.0.10). - */ - public static final Curve P_256K = new Curve("P-256K", "secp256k1", "1.3.132.0.10"); - - - /** - * P-384 curve (secp384r1, OID = 1.3.132.0.34). - */ - public static final Curve P_384 = new Curve("P-384", "secp384r1", "1.3.132.0.34"); - - - /** - * P-521 curve (secp521r1). - */ - public static final Curve P_521 = new Curve("P-521", "secp521r1", "1.3.132.0.35"); - - - /** - * Ed25519 signature algorithm key pairs. - */ - public static final Curve Ed25519 = new Curve("Ed25519", "Ed25519", null); - - - /** - * Ed448 signature algorithm key pairs. - */ - public static final Curve Ed448 = new Curve("Ed448", "Ed448", null); - - - /** - * X25519 function key pairs. - */ - public static final Curve X25519 = new Curve("X25519", "X25519", null); - - - /** - * X448 function key pairs. - */ - public static final Curve X448 = new Curve("X448", "X448", null); - - - /** - * The JOSE curve name. - */ - private final String name; - - - /** - * The standard curve name, {@code null} if not specified. - */ - private final String stdName; - - - /** - * The standard object identifier for the curve, {@code null} - * if not specified. - */ - private final String oid; - - - /** - * Creates a new cryptographic curve with the specified JOSE name. A - * standard curve name and object identifier (OID) are not unspecified. - * - * @param name The JOSE name of the cryptographic curve. Must not be - * {@code null}. - */ - public Curve(final String name) { - - this(name, null, null); - } - - - /** - * Creates a new cryptographic curve with the specified JOSE name, - * standard name and object identifier (OID). - * - * @param name The JOSE name of the cryptographic curve. Must not - * be {@code null}. - * @param stdName The standard name of the cryptographic curve, - * {@code null} if not specified. - * @param oid The object identifier (OID) of the cryptographic - * curve, {@code null} if not specified. - */ - public Curve(final String name, final String stdName, final String oid) { - - if (name == null) { - throw new IllegalArgumentException("The JOSE cryptographic curve name must not be null"); - } - - this.name = name; - - this.stdName = stdName; - - this.oid = oid; - } - - - /** - * Returns the JOSE name of this cryptographic curve. - * - * @return The JOSE name. - */ - public String getName() { - - return name; - } - - - /** - * Returns the standard name of this cryptographic curve. - * - * @return The standard name, {@code null} if not specified. - */ - public String getStdName() { - - return stdName; - } - - - /** - * Returns the standard object identifier (OID) of this cryptographic - * curve. - * - * @return The OID, {@code null} if not specified. - */ - public String getOID() { - - return oid; - } - - - /** - * Returns the parameter specification for this cryptographic curve. - * - * @return The EC parameter specification, {@code null} if it cannot be - * determined. - */ - public ECParameterSpec toECParameterSpec() { - - return ECParameterTable.get(this); - } - - - /** - * @see #getName - */ - @Override - public String toString() { - - return getName(); - } - - - @Override - public boolean equals(final Object object) { - - return object instanceof Curve && - this.toString().equals(object.toString()); - } - - - /** - * Parses a cryptographic curve from the specified string. - * - * @param s The string to parse. Must not be {@code null} or empty. - * - * @return The cryptographic curve. - */ - public static Curve parse(final String s) { - - if (s == null || s.trim().isEmpty()) { - throw new IllegalArgumentException("The cryptographic curve string must not be null or empty"); - } - - if (s.equals(P_256.getName())) { - return P_256; - } else if (s.equals(P_256K.getName())) { - return P_256K; - } else if (s.equals(P_384.getName())) { - return P_384; - } else if (s.equals(P_521.getName())) { - return P_521; - } else if (s.equals(Ed25519.getName())) { - return Ed25519; - } else if (s.equals(Ed448.getName())) { - return Ed448; - } else if (s.equals(X25519.getName())) { - return X25519; - } else if (s.equals(X448.getName())) { - return X448; - } else { - return new Curve(s); - } - } - - - /** - * Gets the cryptographic curve for the specified standard - * name. - * - * @param stdName The standard curve name. May be {@code null}. - * - * @return The curve, {@code null} if it cannot be determined. - */ - public static Curve forStdName(final String stdName) { - if( "secp256r1".equals(stdName) || "prime256v1".equals(stdName)) { - return P_256; - } else if("secp256k1".equals(stdName)) { - return P_256K; - } else if("secp384r1".equals(stdName)) { - return P_384; - } else if("secp521r1".equals(stdName)) { - return P_521; - } else if (Ed25519.getStdName().equals(stdName)) { - return Ed25519; - } else if (Ed448.getStdName().equals(stdName)) { - return Ed448; - } else if (X25519.getStdName().equals(stdName)) { - return X25519; - } else if (X448.getStdName().equals(stdName)) { - return X448; - } else { - return null; - } - } - - - /** - * Gets the cryptographic curve for the specified object identifier - * (OID). - * - * @param oid The object OID. May be {@code null}. - * - * @return The curve, {@code null} if it cannot be determined. - */ - public static Curve forOID(final String oid) { - - if (P_256.getOID().equals(oid)) { - return P_256; - } else if (P_256K.getOID().equals(oid)) { - return P_256K; - } else if (P_384.getOID().equals(oid)) { - return P_384; - } else if (P_521.getOID().equals(oid)) { - return P_521; - } else { - return null; - } - } - - - /** - * Gets the cryptographic curve(s) for the specified JWS algorithm. - * - * @param alg The JWS algorithm. May be {@code null}. - * - * @return The curve(s), {@code null} if the JWS algorithm is not curve - * based, or the JWS algorithm is not supported. - */ - public static Set forJWSAlgorithm(final JWSAlgorithm alg) { - - if (JWSAlgorithm.ES256.equals(alg)) { - return Collections.singleton(P_256); - } else if (JWSAlgorithm.ES256K.equals(alg)) { - return Collections.singleton(P_256K); - } else if (JWSAlgorithm.ES384.equals(alg)) { - return Collections.singleton(P_384); - } else if (JWSAlgorithm.ES512.equals(alg)) { - return Collections.singleton(P_521); - } else if (JWSAlgorithm.EdDSA.equals(alg)) { - return Collections.unmodifiableSet( - new HashSet<>(Arrays.asList( - Ed25519, - Ed448 - )) - ); - } else { - return null; - } - } - - - /** - * Gets the cryptographic curve for the specified parameter - * specification. - * - * @param spec The EC parameter spec. May be {@code null}. - * - * @return The curve, {@code null} if it cannot be determined. - */ - public static Curve forECParameterSpec(final ECParameterSpec spec) { - - return ECParameterTable.get(spec); - } -} \ No newline at end of file diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/CurveBasedJWK.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/CurveBasedJWK.java deleted file mode 100644 index 22c739568..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/CurveBasedJWK.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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.jwk; - - -/** - * Curve based JSON Web Key (JWK). - * - * @author Vladimir Dzhuvinov - * @version 2018-08-23 - */ -public interface CurveBasedJWK { - - - /** - * Returns the cryptographic curve. - * - * @return The cryptographic curve. - */ - Curve getCurve(); -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/ECKey.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/ECKey.java deleted file mode 100644 index 84f626f4e..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/ECKey.java +++ /dev/null @@ -1,1582 +0,0 @@ -/* - * 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.jwk; - - -import java.math.BigInteger; -import java.net.URI; -import java.security.*; -import java.security.cert.Certificate; -import java.security.cert.CertificateEncodingException; -import java.security.cert.X509Certificate; -import java.security.interfaces.ECPrivateKey; -import java.security.interfaces.ECPublicKey; -import java.security.spec.*; -import java.text.ParseException; -import java.util.*; - -import net.jcip.annotations.Immutable; -import net.minidev.json.JSONObject; -import org.bouncycastle.cert.jcajce.JcaX509CertificateHolder; - -import com.nimbusds.jose.Algorithm; -import com.nimbusds.jose.JOSEException; -import com.nimbusds.jose.crypto.utils.ECChecks; -import com.nimbusds.jose.util.Base64; -import com.nimbusds.jose.util.Base64URL; -import com.nimbusds.jose.util.BigIntegerUtils; -import com.nimbusds.jose.util.JSONObjectUtils; - - -/** - * Public and private {@link KeyType#EC Elliptic Curve} JSON Web Key (JWK). - * This class is immutable. - * - *

Supported curves: - * - *

    - *
  • {@link Curve#P_256 P-256} - *
  • {@link Curve#P_256K P-256K} - *
  • {@link Curve#P_384 P-384} - *
  • {@link Curve#P_521 P-512} - *
- * - *

Provides EC JWK import from / export to the following standard Java - * interfaces and classes: - * - *

    - *
  • {@link java.security.interfaces.ECPublicKey} - *
  • {@link java.security.interfaces.ECPrivateKey} - *
  • {@link java.security.PrivateKey} for an EC key in a PKCS#11 store - *
  • {@link java.security.KeyPair} - *
- * - *

Example JSON object representation of a public EC JWK: - * - *

- * {
- *   "kty" : "EC",
- *   "crv" : "P-256",
- *   "x"   : "MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4",
- *   "y"   : "4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM",
- *   "use" : "enc",
- *   "kid" : "1"
- * }
- * 
- * - *

Example JSON object representation of a private EC JWK: - * - *

- * {
- *   "kty" : "EC",
- *   "crv" : "P-256",
- *   "x"   : "MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4",
- *   "y"   : "4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM",
- *   "d"   : "870MB6gfuTJ4HtUnUvYMyJpr5eUZNP4Bk43bVdj3eAE",
- *   "use" : "enc",
- *   "kid" : "1"
- * }
- * 
- * - *

Use the builder to create a new EC JWK: - * - *

- * ECKey key = new ECKey.Builder(Curve.P_256, x, y)
- * 	.keyUse(KeyUse.SIGNATURE)
- * 	.keyID("1")
- * 	.build();
- * 
- * - *

See http://en.wikipedia.org/wiki/Elliptic_curve_cryptography - * - * @author Vladimir Dzhuvinov - * @author Justin Richer - * @version 2019-04-15 - */ -@Immutable -public final class ECKey extends JWK implements AsymmetricJWK, CurveBasedJWK { - - - private static final long serialVersionUID = 1L; - - - /** - * Supported EC curves. - */ - public static final Set SUPPORTED_CURVES = Collections.unmodifiableSet( - new HashSet<>(Arrays.asList(Curve.P_256, Curve.P_256K, Curve.P_384, Curve.P_521)) - ); - - - /** - * Builder for constructing Elliptic Curve JWKs. - * - *

Example usage: - * - *

-	 * ECKey key = new ECKey.Builder(Curve.P521, x, y)
-	 *     .d(d)
-	 *     .algorithm(JWSAlgorithm.ES512)
-	 *     .keyID("1")
-	 *     .build();
-	 * 
- */ - public static class Builder { - - - /** - * The curve name. - */ - private final Curve crv; - - - /** - * The public 'x' EC coordinate. - */ - private final Base64URL x; - - - /** - * The public 'y' EC coordinate. - */ - private final Base64URL y; - - - /** - * The private 'd' EC coordinate, optional. - */ - private Base64URL d; - - - /** - * The private EC key, as PKCS#11 handle, optional. - */ - private PrivateKey priv; - - - /** - * The key use, optional. - */ - private KeyUse use; - - - /** - * The key operations, optional. - */ - private Set ops; - - - /** - * The intended JOSE algorithm for the key, optional. - */ - private Algorithm alg; - - - /** - * The key ID, optional. - */ - private String kid; - - - /** - * X.509 certificate URL, optional. - */ - private URI x5u; - - - /** - * X.509 certificate SHA-1 thumbprint, optional. - */ - @Deprecated - private Base64URL x5t; - - - /** - * X.509 certificate SHA-256 thumbprint, optional. - */ - private Base64URL x5t256; - - - /** - * The X.509 certificate chain, optional. - */ - private List x5c; - - - /** - * Reference to the underlying key store, {@code null} if none. - */ - private KeyStore ks; - - - /** - * Creates a new Elliptic Curve JWK builder. - * - * @param crv The cryptographic curve. Must not be - * {@code null}. - * @param x The public 'x' coordinate for the elliptic curve - * point. It is represented as the Base64URL - * encoding of the coordinate's big endian - * representation. Must not be {@code null}. - * @param y The public 'y' coordinate for the elliptic curve - * point. It is represented as the Base64URL - * encoding of the coordinate's big endian - * representation. Must not be {@code null}. - */ - public Builder(final Curve crv, final Base64URL x, final Base64URL y) { - - if (crv == null) { - throw new IllegalArgumentException("The curve must not be null"); - } - - this.crv = crv; - - if (x == null) { - throw new IllegalArgumentException("The 'x' coordinate must not be null"); - } - - this.x = x; - - if (y == null) { - throw new IllegalArgumentException("The 'y' coordinate must not be null"); - } - - this.y = y; - } - - - /** - * Creates a new Elliptic Curve JWK builder. - * - * @param crv The cryptographic curve. Must not be - * {@code null}. - * @param pub The public EC key to represent. Must not be - * {@code null}. - */ - public Builder(final Curve crv, final ECPublicKey pub) { - - this(crv, - encodeCoordinate(pub.getParams().getCurve().getField().getFieldSize(), pub.getW().getAffineX()), - encodeCoordinate(pub.getParams().getCurve().getField().getFieldSize(), pub.getW().getAffineY())); - } - - - /** - * Creates a new Elliptic Curve JWK builder. - * - * @param ecJWK The EC JWK to start with. Must not be - * {@code null}. - */ - public Builder(final ECKey ecJWK) { - - crv = ecJWK.crv; - x = ecJWK.x; - y = ecJWK.y; - d = ecJWK.d; - priv = ecJWK.privateKey; - use = ecJWK.getKeyUse(); - ops = ecJWK.getKeyOperations(); - alg = ecJWK.getAlgorithm(); - kid = ecJWK.getKeyID(); - x5u = ecJWK.getX509CertURL(); - x5t = ecJWK.getX509CertThumbprint(); - x5t256 = ecJWK.getX509CertSHA256Thumbprint(); - x5c = ecJWK.getX509CertChain(); - ks = ecJWK.getKeyStore(); - } - - - /** - * Sets the private 'd' coordinate for the elliptic curve - * point. The alternative method is {@link #privateKey}. - * - * @param d The private 'd' coordinate. It is represented as - * the Base64URL encoding of the coordinate's big - * endian representation. {@code null} if not - * specified (for a public key). - * - * @return This builder. - */ - public Builder d(final Base64URL d) { - - this.d = d; - return this; - } - - - /** - * Sets the private Elliptic Curve key. The alternative method - * is {@link #d}. - * - * @param priv The private EC key, used to obtain the private - * 'd' coordinate for the elliptic curve point. - * {@code null} if not specified (for a public - * key). - * - * @return This builder. - */ - public Builder privateKey(final ECPrivateKey priv) { - - if (priv != null) { - this.d = encodeCoordinate(priv.getParams().getCurve().getField().getFieldSize(), priv.getS()); - } - - return this; - } - - - /** - * Sets the private EC key, typically for a key located in a - * PKCS#11 store that doesn't expose the private key parameters - * (such as a smart card or HSM). - * - * @param priv The private EC key reference. Its algorithm must - * be "EC". Must not be {@code null}. - * - * @return This builder. - */ - public Builder privateKey(final PrivateKey priv) { - - if (priv instanceof ECPrivateKey) { - return privateKey((ECPrivateKey) priv); - } - - if (! "EC".equalsIgnoreCase(priv.getAlgorithm())) { - throw new IllegalArgumentException("The private key algorithm must be EC"); - } - - this.priv = priv; - return this; - } - - - /** - * Sets the use ({@code use}) of the JWK. - * - * @param use The key use, {@code null} if not specified or if - * the key is intended for signing as well as - * encryption. - * - * @return This builder. - */ - public Builder keyUse(final KeyUse use) { - - this.use = use; - return this; - } - - - /** - * Sets the operations ({@code key_ops}) of the JWK. - * - * @param ops The key operations, {@code null} if not - * specified. - * - * @return This builder. - */ - public Builder keyOperations(final Set ops) { - - this.ops = ops; - return this; - } - - - /** - * Sets the intended JOSE algorithm ({@code alg}) for the JWK. - * - * @param alg The intended JOSE algorithm, {@code null} if not - * specified. - * - * @return This builder. - */ - public Builder algorithm(final Algorithm alg) { - - this.alg = alg; - return this; - } - - /** - * Sets the ID ({@code kid}) of the JWK. The key ID can be used - * to match a specific key. This can be used, for instance, to - * choose a key within a {@link JWKSet} during key rollover. - * The key ID may also correspond to a JWS/JWE {@code kid} - * header parameter value. - * - * @param kid The key ID, {@code null} if not specified. - * - * @return This builder. - */ - public Builder keyID(final String kid) { - - this.kid = kid; - return this; - } - - - /** - * Sets the ID ({@code kid}) of the JWK to its SHA-256 JWK - * thumbprint (RFC 7638). The key ID can be used to match a - * specific key. This can be used, for instance, to choose a - * key within a {@link JWKSet} during key rollover. The key ID - * may also correspond to a JWS/JWE {@code kid} header - * parameter value. - * - * @return This builder. - * - * @throws JOSEException If the SHA-256 hash algorithm is not - * supported. - */ - public Builder keyIDFromThumbprint() - throws JOSEException { - - return keyIDFromThumbprint("SHA-256"); - } - - - /** - * Sets the ID ({@code kid}) of the JWK to its JWK thumbprint - * (RFC 7638). The key ID can be used to match a specific key. - * This can be used, for instance, to choose a key within a - * {@link JWKSet} during key rollover. The key ID may also - * correspond to a JWS/JWE {@code kid} header parameter value. - * - * @param hashAlg The hash algorithm for the JWK thumbprint - * computation. Must not be {@code null}. - * - * @return This builder. - * - * @throws JOSEException If the hash algorithm is not - * supported. - */ - public Builder keyIDFromThumbprint(final String hashAlg) - throws JOSEException { - - // Put mandatory params in sorted order - LinkedHashMap requiredParams = new LinkedHashMap<>(); - requiredParams.put("crv", crv.toString()); - requiredParams.put("kty", KeyType.EC.getValue()); - requiredParams.put("x", x.toString()); - requiredParams.put("y", y.toString()); - this.kid = ThumbprintUtils.compute(hashAlg, requiredParams).toString(); - return this; - } - - - /** - * Sets the X.509 certificate URL ({@code x5u}) of the JWK. - * - * @param x5u The X.509 certificate URL, {@code null} if not - * specified. - * - * @return This builder. - */ - public Builder x509CertURL(final URI x5u) { - - this.x5u = x5u; - return this; - } - - - /** - * Sets the X.509 certificate SHA-1 thumbprint ({@code x5t}) of - * the JWK. - * - * @param x5t The X.509 certificate SHA-1 thumbprint, - * {@code null} if not specified. - * - * @return This builder. - */ - @Deprecated - public Builder x509CertThumbprint(final Base64URL x5t) { - - this.x5t = x5t; - return this; - } - - - /** - * Sets the X.509 certificate SHA-256 thumbprint - * ({@code x5t#S256}) of the JWK. - * - * @param x5t256 The X.509 certificate SHA-256 thumbprint, - * {@code null} if not specified. - * - * @return This builder. - */ - public Builder x509CertSHA256Thumbprint(final Base64URL x5t256) { - - this.x5t256 = x5t256; - return this; - } - - - /** - * Sets the X.509 certificate chain ({@code x5c}) of the JWK. - * - * @param x5c The X.509 certificate chain as a unmodifiable - * list, {@code null} if not specified. - * - * @return This builder. - */ - public Builder x509CertChain(final List x5c) { - - this.x5c = x5c; - return this; - } - - - /** - * Sets the underlying key store. - * - * @param keyStore Reference to the underlying key store, - * {@code null} if none. - * - * @return This builder. - */ - public Builder keyStore(final KeyStore keyStore) { - - this.ks = keyStore; - return this; - } - - - /** - * Builds a new Elliptic Curve JWK. - * - * @return The Elliptic Curve JWK. - * - * @throws IllegalStateException If the JWK parameters were - * inconsistently specified. - */ - public ECKey build() { - - try { - if (d == null && priv == null) { - // Public key - return new ECKey(crv, x, y, use, ops, alg, kid, x5u, x5t, x5t256, x5c, ks); - } - - if (priv != null) { - // PKCS#11 reference to private key - return new ECKey(crv, x, y, priv, use, ops, alg, kid, x5u, x5t, x5t256, x5c, ks); - } - - // Public / private key pair with 'd' - return new ECKey(crv, x, y, d, use, ops, alg, kid, x5u, x5t, x5t256, x5c, ks); - - } catch (IllegalArgumentException e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - } - - - /** - * Returns the Base64URL encoding of the specified elliptic curve 'x', - * 'y' or 'd' coordinate, with leading zero padding up to the specified - * field size in bits. - * - * @param fieldSize The field size in bits. - * @param coordinate The elliptic curve coordinate. Must not be - * {@code null}. - * - * @return The Base64URL-encoded coordinate, with leading zero padding - * up to the curve's field size. - */ - public static Base64URL encodeCoordinate(final int fieldSize, final BigInteger coordinate) { - - final byte[] notPadded = BigIntegerUtils.toBytesUnsigned(coordinate); - - int bytesToOutput = (fieldSize + 7)/8; - - if (notPadded.length >= bytesToOutput) { - // Greater-than check to prevent exception on malformed - // key below - return Base64URL.encode(notPadded); - } - - final byte[] padded = new byte[bytesToOutput]; - - System.arraycopy(notPadded, 0, padded, bytesToOutput - notPadded.length, notPadded.length); - - return Base64URL.encode(padded); - } - - - /** - * The curve name. - */ - private final Curve crv; - - - /** - * The public 'x' EC coordinate. - */ - private final Base64URL x; - - - /** - * The public 'y' EC coordinate. - */ - private final Base64URL y; - - - /** - * The private 'd' EC coordinate. - */ - private final Base64URL d; - - - /** - * Private PKCS#11 key handle. - */ - private final PrivateKey privateKey; - - - /** - * Ensures the specified 'x' and 'y' public coordinates are on the - * given curve. - * - * @param crv The curve. Must not be {@code null}. - * @param x The public 'x' coordinate. Must not be {@code null}. - * @param y The public 'y' coordinate. Must not be {@code null}. - */ - private static void ensurePublicCoordinatesOnCurve(final Curve crv, final Base64URL x, final Base64URL y) { - - if (! SUPPORTED_CURVES.contains(crv)) { - throw new IllegalArgumentException("Unknown / unsupported curve: " + crv); - } - - if (! ECChecks.isPointOnCurve(x.decodeToBigInteger(), y.decodeToBigInteger(), crv.toECParameterSpec())) { - throw new IllegalArgumentException("Invalid EC JWK: The 'x' and 'y' public coordinates are not on the " + crv + " curve"); - } - } - - - /** - * Creates a new public Elliptic Curve JSON Web Key (JWK) with the - * specified parameters. - * - * @param crv The cryptographic curve. Must not be {@code null}. - * @param x The public 'x' coordinate for the elliptic curve - * point. It is represented as the Base64URL encoding of - * the coordinate's big endian representation. Must not - * be {@code null}. - * @param y The public 'y' coordinate for the elliptic curve - * point. It is represented as the Base64URL encoding of - * the coordinate's big endian representation. Must not - * be {@code null}. - * @param use The key use, {@code null} if not specified or if the - * key is intended for signing as well as encryption. - * @param ops The key operations, {@code null} if not specified. - * @param alg The intended JOSE algorithm for the key, {@code null} - * if not specified. - * @param kid The key ID, {@code null} if not specified. - * @param x5u The X.509 certificate URL, {@code null} if not - * specified. - * @param x5t The X.509 certificate SHA-1 thumbprint, {@code null} - * if not specified. - * @param x5t256 The X.509 certificate SHA-256 thumbprint, {@code null} - * if not specified. - * @param x5c The X.509 certificate chain, {@code null} if not - * specified. - * @param ks Reference to the underlying key store, {@code null} if - * not specified. - */ - public ECKey(final Curve crv, final Base64URL x, final Base64URL y, - final KeyUse use, final Set ops, final Algorithm alg, final String kid, - final URI x5u, final Base64URL x5t, final Base64URL x5t256, final List x5c, - final KeyStore ks) { - - super(KeyType.EC, use, ops, alg, kid, x5u, x5t, x5t256, x5c, ks); - - if (crv == null) { - throw new IllegalArgumentException("The curve must not be null"); - } - - this.crv = crv; - - if (x == null) { - throw new IllegalArgumentException("The 'x' coordinate must not be null"); - } - - this.x = x; - - if (y == null) { - throw new IllegalArgumentException("The 'y' coordinate must not be null"); - } - - this.y = y; - - ensurePublicCoordinatesOnCurve(crv, x, y); - - ensureMatches(getParsedX509CertChain()); - - this.d = null; - - this.privateKey = null; - } - - - /** - * Creates a new public / private Elliptic Curve JSON Web Key (JWK) - * with the specified parameters. - * - * @param crv The cryptographic curve. Must not be {@code null}. - * @param x The public 'x' coordinate for the elliptic curve - * point. It is represented as the Base64URL encoding of - * the coordinate's big endian representation. Must not - * be {@code null}. - * @param y The public 'y' coordinate for the elliptic curve - * point. It is represented as the Base64URL encoding of - * the coordinate's big endian representation. Must not - * be {@code null}. - * @param d The private 'd' coordinate for the elliptic curve - * point. It is represented as the Base64URL encoding of - * the coordinate's big endian representation. Must not - * be {@code null}. - * @param use The key use, {@code null} if not specified or if the - * key is intended for signing as well as encryption. - * @param ops The key operations, {@code null} if not specified. - * @param alg The intended JOSE algorithm for the key, {@code null} - * if not specified. - * @param kid The key ID, {@code null} if not specified. - * @param x5u The X.509 certificate URL, {@code null} if not - * specified. - * @param x5t The X.509 certificate SHA-1 thumbprint, {@code null} - * if not specified. - * @param x5t256 The X.509 certificate SHA-256 thumbprint, {@code null} - * if not specified. - * @param x5c The X.509 certificate chain, {@code null} if not - * specified. - * @param ks Reference to the underlying key store, {@code null} if - * not specified. - */ - public ECKey(final Curve crv, final Base64URL x, final Base64URL y, final Base64URL d, - final KeyUse use, final Set ops, final Algorithm alg, final String kid, - final URI x5u, final Base64URL x5t, final Base64URL x5t256, final List x5c, - final KeyStore ks) { - - super(KeyType.EC, use, ops, alg, kid, x5u, x5t, x5t256, x5c, ks); - - if (crv == null) { - throw new IllegalArgumentException("The curve must not be null"); - } - - this.crv = crv; - - if (x == null) { - throw new IllegalArgumentException("The 'x' coordinate must not be null"); - } - - this.x = x; - - if (y == null) { - throw new IllegalArgumentException("The 'y' coordinate must not be null"); - } - - this.y = y; - - ensurePublicCoordinatesOnCurve(crv, x, y); - - ensureMatches(getParsedX509CertChain()); - - if (d == null) { - throw new IllegalArgumentException("The 'd' coordinate must not be null"); - } - - this.d = d; - - this.privateKey = null; - } - - - /** - * Creates a new public / private Elliptic Curve JSON Web Key (JWK) - * with the specified parameters. The private key is specified by its - * PKCS#11 handle. - * - * @param crv The cryptographic curve. Must not be {@code null}. - * @param x The public 'x' coordinate for the elliptic curve - * point. It is represented as the Base64URL encoding of - * the coordinate's big endian representation. Must not - * be {@code null}. - * @param y The public 'y' coordinate for the elliptic curve - * point. It is represented as the Base64URL encoding of - * the coordinate's big endian representation. Must not - * be {@code null}. - * @param priv The private key as a PKCS#11 handle, {@code null} if - * not specified. - * @param use The key use, {@code null} if not specified or if the - * key is intended for signing as well as encryption. - * @param ops The key operations, {@code null} if not specified. - * @param alg The intended JOSE algorithm for the key, {@code null} - * if not specified. - * @param kid The key ID, {@code null} if not specified. - * @param x5u The X.509 certificate URL, {@code null} if not - * specified. - * @param x5t The X.509 certificate SHA-1 thumbprint, {@code null} - * if not specified. - * @param x5t256 The X.509 certificate SHA-256 thumbprint, {@code null} - * if not specified. - * @param x5c The X.509 certificate chain, {@code null} if not - * specified. - */ - public ECKey(final Curve crv, final Base64URL x, final Base64URL y, final PrivateKey priv, - final KeyUse use, final Set ops, final Algorithm alg, final String kid, - final URI x5u, final Base64URL x5t, final Base64URL x5t256, final List x5c, - final KeyStore ks) { - - super(KeyType.EC, use, ops, alg, kid, x5u, x5t, x5t256, x5c, ks); - - if (crv == null) { - throw new IllegalArgumentException("The curve must not be null"); - } - - this.crv = crv; - - if (x == null) { - throw new IllegalArgumentException("The 'x' coordinate must not be null"); - } - - this.x = x; - - if (y == null) { - throw new IllegalArgumentException("The 'y' coordinate must not be null"); - } - - this.y = y; - - ensurePublicCoordinatesOnCurve(crv, x, y); - - ensureMatches(getParsedX509CertChain()); - - d = null; - - this.privateKey = priv; - } - - - /** - * Creates a new public Elliptic Curve JSON Web Key (JWK) with the - * specified parameters. - * - * @param crv The cryptographic curve. Must not be {@code null}. - * @param pub The public EC key to represent. Must not be - * {@code null}. - * @param use The key use, {@code null} if not specified or if the - * key is intended for signing as well as encryption. - * @param ops The key operations, {@code null} if not specified. - * @param alg The intended JOSE algorithm for the key, {@code null} - * if not specified. - * @param kid The key ID, {@code null} if not specified. - * @param x5u The X.509 certificate URL, {@code null} if not - * specified. - * @param x5t The X.509 certificate SHA-1 thumbprint, {@code null} - * if not specified. - * @param x5t256 The X.509 certificate SHA-256 thumbprint, {@code null} - * if not specified. - * @param x5c The X.509 certificate chain, {@code null} if not - * specified. - * @param ks Reference to the underlying key store, {@code null} if - * not specified. - */ - public ECKey(final Curve crv, final ECPublicKey pub, - final KeyUse use, final Set ops, final Algorithm alg, final String kid, - final URI x5u, final Base64URL x5t, final Base64URL x5t256, final List x5c, - final KeyStore ks) { - - this(crv, - encodeCoordinate(pub.getParams().getCurve().getField().getFieldSize(), pub.getW().getAffineX()), - encodeCoordinate(pub.getParams().getCurve().getField().getFieldSize(), pub.getW().getAffineY()), - use, ops, alg, kid, - x5u, x5t, x5t256, x5c, - ks); - } - - - /** - * Creates a new public / private Elliptic Curve JSON Web Key (JWK) - * with the specified parameters. - * - * @param crv The cryptographic curve. Must not be {@code null}. - * @param pub The public EC key to represent. Must not be - * {@code null}. - * @param priv The private EC key to represent. Must not be - * {@code null}. - * @param use The key use, {@code null} if not specified or if the - * key is intended for signing as well as encryption. - * @param ops The key operations, {@code null} if not specified. - * @param alg The intended JOSE algorithm for the key, {@code null} - * if not specified. - * @param kid The key ID, {@code null} if not specified. - * @param x5u The X.509 certificate URL, {@code null} if not - * specified. - * @param x5t The X.509 certificate SHA-1 thumbprint, {@code null} - * if not specified. - * @param x5t256 The X.509 certificate SHA-256 thumbprint, {@code null} - * if not specified. - * @param x5c The X.509 certificate chain, {@code null} if not - * specified. - * @param ks Reference to the underlying key store, {@code null} if - * not specified. - */ - public ECKey(final Curve crv, final ECPublicKey pub, final ECPrivateKey priv, - final KeyUse use, final Set ops, final Algorithm alg, final String kid, - final URI x5u, final Base64URL x5t, final Base64URL x5t256, final List x5c, - final KeyStore ks) { - - this(crv, - encodeCoordinate(pub.getParams().getCurve().getField().getFieldSize(), pub.getW().getAffineX()), - encodeCoordinate(pub.getParams().getCurve().getField().getFieldSize(), pub.getW().getAffineY()), - encodeCoordinate(priv.getParams().getCurve().getField().getFieldSize(), priv.getS()), - use, ops, alg, kid, - x5u, x5t, x5t256, x5c, - ks); - } - - - /** - * Creates a new public / private Elliptic Curve JSON Web Key (JWK) - * with the specified parameters. The private key is specified by its - * PKCS#11 handle. - * - * @param crv The cryptographic curve. Must not be {@code null}. - * @param pub The public EC key to represent. Must not be - * {@code null}. - * @param priv The private key as a PKCS#11 handle, {@code null} if - * not specified. - * @param use The key use, {@code null} if not specified or if the - * key is intended for signing as well as encryption. - * @param ops The key operations, {@code null} if not specified. - * @param alg The intended JOSE algorithm for the key, {@code null} - * if not specified. - * @param kid The key ID, {@code null} if not specified. - * @param x5u The X.509 certificate URL, {@code null} if not - * specified. - * @param x5t The X.509 certificate SHA-1 thumbprint, {@code null} - * if not specified. - * @param x5t256 The X.509 certificate SHA-256 thumbprint, {@code null} - * if not specified. - * @param x5c The X.509 certificate chain, {@code null} if not - * specified. - * @param ks Reference to the underlying key store, {@code null} if - * not specified. - */ - public ECKey(final Curve crv, final ECPublicKey pub, final PrivateKey priv, - final KeyUse use, final Set ops, final Algorithm alg, final String kid, - final URI x5u, final Base64URL x5t, final Base64URL x5t256, final List x5c, - final KeyStore ks) { - - this( - crv, - encodeCoordinate(pub.getParams().getCurve().getField().getFieldSize(), pub.getW().getAffineX()), - encodeCoordinate(pub.getParams().getCurve().getField().getFieldSize(), pub.getW().getAffineY()), - priv, - use, ops, alg, kid, x5u, x5t, x5t256, x5c, - ks); - } - - - @Override - public Curve getCurve() { - - return crv; - } - - - /** - * Gets the public 'x' coordinate for the elliptic curve point. - * - * @return The 'x' coordinate. It is represented as the Base64URL - * encoding of the coordinate's big endian representation. - */ - public Base64URL getX() { - - return x; - } - - - /** - * Gets the public 'y' coordinate for the elliptic curve point. - * - * @return The 'y' coordinate. It is represented as the Base64URL - * encoding of the coordinate's big endian representation. - */ - public Base64URL getY() { - - return y; - } - - - /** - * Gets the private 'd' coordinate for the elliptic curve point. It is - * represented as the Base64URL encoding of the coordinate's big endian - * representation. - * - * @return The 'd' coordinate. It is represented as the Base64URL - * encoding of the coordinate's big endian representation. - * {@code null} if not specified (for a public key). - */ - public Base64URL getD() { - - return d; - } - - - /** - * Returns a standard {@code java.security.interfaces.ECPublicKey} - * representation of this Elliptic Curve JWK. Uses the default JCA - * provider. - * - * @return The public Elliptic Curve key. - * - * @throws JOSEException If EC is not supported by the underlying Java - * Cryptography (JCA) provider or if the JWK - * parameters are invalid for a public EC key. - */ - public ECPublicKey toECPublicKey() - throws JOSEException { - - return toECPublicKey(null); - } - - - /** - * Returns a standard {@code java.security.interfaces.ECPublicKey} - * representation of this Elliptic Curve JWK. - * - * @param provider The specific JCA provider to use, {@code null} - * implies the default one. - * - * @return The public Elliptic Curve key. - * - * @throws JOSEException If EC is not supported by the underlying Java - * Cryptography (JCA) provider or if the JWK - * parameters are invalid for a public EC key. - */ - public ECPublicKey toECPublicKey(final Provider provider) - throws JOSEException { - - ECParameterSpec spec = crv.toECParameterSpec(); - - if (spec == null) { - throw new JOSEException("Couldn't get EC parameter spec for curve " + crv); - } - - ECPoint w = new ECPoint(x.decodeToBigInteger(), y.decodeToBigInteger()); - - ECPublicKeySpec publicKeySpec = new ECPublicKeySpec(w, spec); - - try { - KeyFactory keyFactory; - - if (provider == null) { - keyFactory = KeyFactory.getInstance("EC"); - } else { - keyFactory = KeyFactory.getInstance("EC", provider); - } - - return (ECPublicKey) keyFactory.generatePublic(publicKeySpec); - - } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { - - throw new JOSEException(e.getMessage(), e); - } - } - - - /** - * Returns a standard {@code java.security.interfaces.ECPrivateKey} - * representation of this Elliptic Curve JWK. Uses the default JCA - * provider. - * - * @return The private Elliptic Curve key, {@code null} if not - * specified by this JWK. - * - * @throws JOSEException If EC is not supported by the underlying Java - * Cryptography (JCA) provider or if the JWK - * parameters are invalid for a private EC key. - */ - public ECPrivateKey toECPrivateKey() - throws JOSEException { - - return toECPrivateKey(null); - } - - - /** - * Returns a standard {@code java.security.interfaces.ECPrivateKey} - * representation of this Elliptic Curve JWK. - * - * @param provider The specific JCA provider to use, {@code null} - * implies the default one. - * - * @return The private Elliptic Curve key, {@code null} if not - * specified by this JWK. - * - * @throws JOSEException If EC is not supported by the underlying Java - * Cryptography (JCA) provider or if the JWK - * parameters are invalid for a private EC key. - */ - public ECPrivateKey toECPrivateKey(final Provider provider) - throws JOSEException { - - if (d == null) { - // No private 'd' param - return null; - } - - ECParameterSpec spec = crv.toECParameterSpec(); - - if (spec == null) { - throw new JOSEException("Couldn't get EC parameter spec for curve " + crv); - } - - ECPrivateKeySpec privateKeySpec = new ECPrivateKeySpec(d.decodeToBigInteger(), spec); - - try { - KeyFactory keyFactory; - - if (provider == null) { - keyFactory = KeyFactory.getInstance("EC"); - } else { - keyFactory = KeyFactory.getInstance("EC", provider); - } - - return (ECPrivateKey) keyFactory.generatePrivate(privateKeySpec); - - } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { - - throw new JOSEException(e.getMessage(), e); - } - } - - - @Override - public PublicKey toPublicKey() - throws JOSEException { - - return toECPublicKey(); - } - - - @Override - public PrivateKey toPrivateKey() - throws JOSEException { - - PrivateKey prv = toECPrivateKey(); - - if (prv != null) { - // Return private EC key with key material - return prv; - } - - // Return private EC key as PKCS#11 handle, or null - return privateKey; - } - - - /** - * Returns a standard {@code java.security.KeyPair} representation of - * this Elliptic Curve JWK. Uses the default JCA provider. - * - * @return The Elliptic Curve key pair. The private Elliptic Curve key - * will be {@code null} if not specified. - * - * @throws JOSEException If EC is not supported by the underlying Java - * Cryptography (JCA) provider or if the JWK - * parameters are invalid for a public and / or - * private EC key. - */ - @Override - public KeyPair toKeyPair() - throws JOSEException { - - return toKeyPair(null); - } - - - /** - * Returns a standard {@code java.security.KeyPair} representation of - * this Elliptic Curve JWK. - * - * @param provider The specific JCA provider to use, {@code null} - * implies the default one. - * - * @return The Elliptic Curve key pair. The private Elliptic Curve key - * will be {@code null} if not specified. - * - * @throws JOSEException If EC is not supported by the underlying Java - * Cryptography (JCA) provider or if the JWK - * parameters are invalid for a public and / or - * private EC key. - */ - public KeyPair toKeyPair(final Provider provider) - throws JOSEException { - - if (privateKey != null) { - // Private key as PKCS#11 handle - return new KeyPair(toECPublicKey(provider), privateKey); - } else { - return new KeyPair(toECPublicKey(provider), toECPrivateKey(provider)); - } - } - - - @Override - public boolean matches(final X509Certificate cert) { - - ECPublicKey certECKey; - try { - certECKey = (ECPublicKey) getParsedX509CertChain().get(0).getPublicKey(); - } catch (ClassCastException ex) { - return false; - } - // Compare Big Ints, base64url encoding may have padding! - // https://tools.ietf.org/html/rfc7518#section-6.2.1.2 - if (! getX().decodeToBigInteger().equals(certECKey.getW().getAffineX())) { - return false; - } - if (! getY().decodeToBigInteger().equals(certECKey.getW().getAffineY())) { - return false; - } - return true; - } - - - /** - * Calls {@link #matches(X509Certificate)} for the first X.509 - * certificate in the specified chain. - * - * @param chain The X.509 certificate chain, {@code null} if not - * specified. - * - * @throws IllegalArgumentException If a certificate chain is specified - * and the first certificate in it - * doesn't match. - */ - private void ensureMatches(final List chain) { - - if (chain == null) - return; - - if (! matches(chain.get(0))) - throw new IllegalArgumentException("The public subject key info of the first X.509 certificate in the chain must match the JWK type and public parameters"); - } - - - @Override - public LinkedHashMap getRequiredParams() { - - // Put mandatory params in sorted order - LinkedHashMap requiredParams = new LinkedHashMap<>(); - requiredParams.put("crv", crv.toString()); - requiredParams.put("kty", getKeyType().getValue()); - requiredParams.put("x", x.toString()); - requiredParams.put("y", y.toString()); - return requiredParams; - } - - - @Override - public boolean isPrivate() { - - return d != null || privateKey != null; - } - - - @Override - public int size() { - - ECParameterSpec ecParameterSpec = crv.toECParameterSpec(); - - if (ecParameterSpec == null) { - throw new UnsupportedOperationException("Couldn't determine field size for curve " + crv.getName()); - } - - return ecParameterSpec.getCurve().getField().getFieldSize(); - } - - - /** - * Returns a copy of this Elliptic Curve JWK with any private values - * removed. - * - * @return The copied public Elliptic Curve JWK. - */ - @Override - public ECKey toPublicJWK() { - - return new ECKey( - getCurve(), getX(), getY(), - getKeyUse(), getKeyOperations(), getAlgorithm(), getKeyID(), - getX509CertURL(), getX509CertThumbprint(), getX509CertSHA256Thumbprint(), getX509CertChain(), - getKeyStore()); - } - - - @Override - public JSONObject toJSONObject() { - - JSONObject o = super.toJSONObject(); - - // Append EC specific attributes - o.put("crv", crv.toString()); - o.put("x", x.toString()); - o.put("y", y.toString()); - - if (d != null) { - o.put("d", d.toString()); - } - - return o; - } - - - /** - * Parses a public / private Elliptic Curve JWK from the specified JSON - * object string representation. - * - * @param s The JSON object string to parse. Must not be {@code null}. - * - * @return The public / private Elliptic Curve JWK. - * - * @throws ParseException If the string couldn't be parsed to an - * Elliptic Curve JWK. - */ - public static ECKey parse(final String s) - throws ParseException { - - return parse(JSONObjectUtils.parse(s)); - } - - - /** - * Parses a public / private Elliptic Curve JWK from the specified JSON - * object representation. - * - * @param jsonObject The JSON object to parse. Must not be - * {@code null}. - * - * @return The public / private Elliptic Curve JWK. - * - * @throws ParseException If the JSON object couldn't be parsed to an - * Elliptic Curve JWK. - */ - public static ECKey parse(final JSONObject jsonObject) - throws ParseException { - - // Parse the mandatory parameters first - Curve crv = Curve.parse(JSONObjectUtils.getString(jsonObject, "crv")); - Base64URL x = new Base64URL(JSONObjectUtils.getString(jsonObject, "x")); - Base64URL y = new Base64URL(JSONObjectUtils.getString(jsonObject, "y")); - - // Check key type - KeyType kty = JWKMetadata.parseKeyType(jsonObject); - - if (kty != KeyType.EC) { - throw new ParseException("The key type \"kty\" must be EC", 0); - } - - // Get optional private key - Base64URL d = null; - if (jsonObject.get("d") != null) { - d = new Base64URL(JSONObjectUtils.getString(jsonObject, "d")); - } - - - try { - if (d == null) { - // Public key - return new ECKey(crv, x, y, - JWKMetadata.parseKeyUse(jsonObject), - JWKMetadata.parseKeyOperations(jsonObject), - JWKMetadata.parseAlgorithm(jsonObject), - JWKMetadata.parseKeyID(jsonObject), - JWKMetadata.parseX509CertURL(jsonObject), - JWKMetadata.parseX509CertThumbprint(jsonObject), - JWKMetadata.parseX509CertSHA256Thumbprint(jsonObject), - JWKMetadata.parseX509CertChain(jsonObject), - null); - - } else { - // Key pair - return new ECKey(crv, x, y, d, - JWKMetadata.parseKeyUse(jsonObject), - JWKMetadata.parseKeyOperations(jsonObject), - JWKMetadata.parseAlgorithm(jsonObject), - JWKMetadata.parseKeyID(jsonObject), - JWKMetadata.parseX509CertURL(jsonObject), - JWKMetadata.parseX509CertThumbprint(jsonObject), - JWKMetadata.parseX509CertSHA256Thumbprint(jsonObject), - JWKMetadata.parseX509CertChain(jsonObject), - null); - } - - } catch (IllegalArgumentException ex) { - - // Conflicting 'use' and 'key_ops' - throw new ParseException(ex.getMessage(), 0); - } - } - - - /** - * Parses a public Elliptic Curve JWK from the specified X.509 - * certificate. Requires BouncyCastle. - * - *

Important: The X.509 certificate is not - * validated! - * - *

Sets the following JWK parameters: - * - *

    - *
  • The curve is obtained from the subject public key info - * algorithm parameters. - *
  • The JWK use inferred by {@link KeyUse#from}. - *
  • The JWK ID from the X.509 serial number (in base 10). - *
  • The JWK X.509 certificate chain (this certificate only). - *
  • The JWK X.509 certificate SHA-256 thumbprint. - *
- * - * @param cert The X.509 certificate. Must not be {@code null}. - * - * @return The public Elliptic Curve JWK. - * - * @throws JOSEException If parsing failed. - */ - public static ECKey parse(final X509Certificate cert) - throws JOSEException { - - if (! (cert.getPublicKey() instanceof ECPublicKey)) { - throw new JOSEException("The public key of the X.509 certificate is not EC"); - } - - ECPublicKey publicKey = (ECPublicKey) cert.getPublicKey(); - - try { - JcaX509CertificateHolder certHolder = new JcaX509CertificateHolder(cert); - - String oid = certHolder.getSubjectPublicKeyInfo().getAlgorithm().getParameters().toString(); - - Curve crv = Curve.forOID(oid); - - if (crv == null) { - throw new JOSEException("Couldn't determine EC JWK curve for OID " + oid); - } - - MessageDigest sha256 = MessageDigest.getInstance("SHA-256"); - - return new ECKey.Builder(crv, publicKey) - .keyUse(KeyUse.from(cert)) - .keyID(cert.getSerialNumber().toString(10)) - .x509CertChain(Collections.singletonList(Base64.encode(cert.getEncoded()))) - .x509CertSHA256Thumbprint(Base64URL.encode(sha256.digest(cert.getEncoded()))) - .build(); - } catch (NoSuchAlgorithmException e) { - throw new JOSEException("Couldn't encode x5t parameter: " + e.getMessage(), e); - } catch (CertificateEncodingException e) { - throw new JOSEException("Couldn't encode x5c parameter: " + e.getMessage(), e); - } - } - - - /** - * Loads a public / private Elliptic Curve JWK from the specified JCA - * key store. Requires BouncyCastle. - * - *

Important: The X.509 certificate is not - * validated! - * - * @param keyStore The key store. Must not be {@code null}. - * @param alias The alias. Must not be {@code null}. - * @param pin The pin to unlock the private key if any, empty or - * {@code null} if not required. - * - * @return The public / private Elliptic Curve JWK., {@code null} if no - * key with the specified alias was found. - * - * @throws KeyStoreException On a key store exception. - * @throws JOSEException If EC key loading failed. - */ - public static ECKey load(final KeyStore keyStore, - final String alias, - final char[] pin) - throws KeyStoreException, JOSEException { - - Certificate cert = keyStore.getCertificate(alias); - - if (cert == null || ! (cert instanceof X509Certificate)) { - return null; - } - - X509Certificate x509Cert = (X509Certificate)cert; - - if (! (x509Cert.getPublicKey() instanceof ECPublicKey)) { - throw new JOSEException("Couldn't load EC JWK: The key algorithm is not EC"); - } - - ECKey ecJWK = ECKey.parse(x509Cert); - - // Let kid=alias - ecJWK = new ECKey.Builder(ecJWK).keyID(alias).keyStore(keyStore).build(); - - // Check for private counterpart - Key key; - try { - key = keyStore.getKey(alias, pin); - } catch (UnrecoverableKeyException | NoSuchAlgorithmException e) { - throw new JOSEException("Couldn't retrieve private EC key (bad pin?): " + e.getMessage(), e); - } - - if (key instanceof ECPrivateKey) { - // Simple file based key store - return new ECKey.Builder(ecJWK) - .privateKey((ECPrivateKey)key) - .build(); - } else if (key instanceof PrivateKey && "EC".equalsIgnoreCase(key.getAlgorithm())) { - // PKCS#11 store - return new ECKey.Builder(ecJWK) - .privateKey((PrivateKey)key) - .build(); - } else { - return ecJWK; - } - } - - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ECKey)) return false; - if (!super.equals(o)) return false; - ECKey ecKey = (ECKey) o; - return Objects.equals(crv, ecKey.crv) && - Objects.equals(x, ecKey.x) && - Objects.equals(y, ecKey.y) && - Objects.equals(d, ecKey.d) && - Objects.equals(privateKey, ecKey.privateKey); - } - - - @Override - public int hashCode() { - return Objects.hash(super.hashCode(), crv, x, y, d, privateKey); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/ECParameterTable.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/ECParameterTable.java deleted file mode 100644 index 33a77845d..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/ECParameterTable.java +++ /dev/null @@ -1,242 +0,0 @@ -/* - * 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.jwk; - - -import java.math.BigInteger; -import java.security.spec.*; - - -/** - * Elliptic curve parameter table. - * - *

Supports the following standard EC JWK curves: - * - *

    - *
  • {@link com.nimbusds.jose.jwk.Curve#P_256} - *
  • {@link com.nimbusds.jose.jwk.Curve#P_256K} - *
  • {@link com.nimbusds.jose.jwk.Curve#P_384} - *
  • {@link com.nimbusds.jose.jwk.Curve#P_521} - *
- * - * @author Vladimir Dzhuvinov - * @author Aleksei Doroganov - * @version 2018-03-28 - */ -class ECParameterTable { - - - /** - * The parameter spec for a - * {@link com.nimbusds.jose.jwk.Curve#P_256} curve. - */ - private static final ECParameterSpec P_256_SPEC; - - - /** - * The parameter spec for a - * {@link com.nimbusds.jose.jwk.Curve#P_256K} curve. - */ - private static final ECParameterSpec P_256K_SPEC; - - - /** - * The parameter spec for a - * {@link com.nimbusds.jose.jwk.Curve#P_384} curve. - */ - private static final ECParameterSpec P_384_SPEC; - - - /** - * The parameter spec for a - * {@link com.nimbusds.jose.jwk.Curve#P_521} curve. - */ - private static final ECParameterSpec P_521_SPEC; - - - /** - * Simple EC field implementation. - */ - private static class ECFieldImpl implements ECField { - - - /** - * The field size. - */ - private int size; - - - /** - * Creates a new EC field with the specified size. - * - * @param size The EC field size. - */ - public ECFieldImpl(final int size) { - - this.size = size; - } - - - @Override - public int getFieldSize() { - return size; - } - } - - - static { - // Values obtained from org.bouncycastle.jce.ECNamedCurveTable - - P_256_SPEC = new ECParameterSpec( - new EllipticCurve( - new ECFieldFp(new BigInteger("115792089210356248762697446949407573530086143415290314195533631308867097853951")), - new BigInteger("115792089210356248762697446949407573530086143415290314195533631308867097853948"), - new BigInteger("41058363725152142129326129780047268409114441015993725554835256314039467401291")), - new ECPoint( - new BigInteger("48439561293906451759052585252797914202762949526041747995844080717082404635286"), - new BigInteger("36134250956749795798585127919587881956611106672985015071877198253568414405109")), - new BigInteger("115792089210356248762697446949407573529996955224135760342422259061068512044369"), - 1); - - P_256K_SPEC = new ECParameterSpec( - new EllipticCurve( - new ECFieldFp(new BigInteger("115792089237316195423570985008687907853269984665640564039457584007908834671663")), - new BigInteger("0"), - new BigInteger("7")), - new ECPoint( - new BigInteger("55066263022277343669578718895168534326250603453777594175500187360389116729240"), - new BigInteger("32670510020758816978083085130507043184471273380659243275938904335757337482424")), - new BigInteger("115792089237316195423570985008687907852837564279074904382605163141518161494337"), - 1); - - P_384_SPEC = new ECParameterSpec( - new EllipticCurve( - new ECFieldFp(new BigInteger("39402006196394479212279040100143613805079739270465446667948293404245721771496870329047266088258938001861606973112319")), - new BigInteger("39402006196394479212279040100143613805079739270465446667948293404245721771496870329047266088258938001861606973112316"), - new BigInteger("27580193559959705877849011840389048093056905856361568521428707301988689241309860865136260764883745107765439761230575")), - new ECPoint( - new BigInteger("26247035095799689268623156744566981891852923491109213387815615900925518854738050089022388053975719786650872476732087"), - new BigInteger("8325710961489029985546751289520108179287853048861315594709205902480503199884419224438643760392947333078086511627871")), - new BigInteger("39402006196394479212279040100143613805079739270465446667946905279627659399113263569398956308152294913554433653942643"), - 1); - - P_521_SPEC = new ECParameterSpec( - new EllipticCurve( - new ECFieldFp(new BigInteger("6864797660130609714981900799081393217269435300143305409394463459185543183397656052122559640661454554977296311391480858037121987999716643812574028291115057151")), - new BigInteger("6864797660130609714981900799081393217269435300143305409394463459185543183397656052122559640661454554977296311391480858037121987999716643812574028291115057148"), - new BigInteger("1093849038073734274511112390766805569936207598951683748994586394495953116150735016013708737573759623248592132296706313309438452531591012912142327488478985984")), - new ECPoint( - new BigInteger("2661740802050217063228768716723360960729859168756973147706671368418802944996427808491545080627771902352094241225065558662157113545570916814161637315895999846"), - new BigInteger("3757180025770020463545507224491183603594455134769762486694567779615544477440556316691234405012945539562144444537289428522585666729196580810124344277578376784")), - new BigInteger("6864797660130609714981900799081393217269435300143305409394463459185543183397655394245057746333217197532963996371363321113864768612440380340372808892707005449"), - 1); - } - - - /** - * Gets the parameter specification for the specified elliptic curve. - * - * @param curve The JWK elliptic curve. May be {@code null}. - * - * @return The EC parameter spec, {@code null} if it cannot be - * determined. - */ - public static ECParameterSpec get(final Curve curve) { - - if (Curve.P_256.equals(curve)) { - return P_256_SPEC; - } else if (Curve.P_256K.equals(curve)) { - return P_256K_SPEC; - } else if (Curve.P_384.equals(curve)) { - return P_384_SPEC; - } else if (Curve.P_521.equals(curve)) { - return P_521_SPEC; - } else { - return null; - } - } - - - /** - * Gets the JWK elliptic curve for the specified parameter - * specification. - * - * @param spec The EC parameter spec. May be {@code null}. - * - * @return The JWK elliptic curve, {@code null} if it cannot be - * determined. - */ - public static Curve get(final ECParameterSpec spec) { - - if (spec == null) { - return null; - } - - if (spec.getCurve().getField().getFieldSize() == P_256_SPEC.getCurve().getField().getFieldSize() && - spec.getCurve().getA().equals(P_256_SPEC.getCurve().getA()) && - spec.getCurve().getB().equals(P_256_SPEC.getCurve().getB()) && - spec.getGenerator().getAffineX().equals(P_256_SPEC.getGenerator().getAffineX()) && - spec.getGenerator().getAffineY().equals(P_256_SPEC.getGenerator().getAffineY()) && - spec.getOrder().equals(P_256_SPEC.getOrder()) && - spec.getCofactor() == P_256_SPEC.getCofactor()) { - - return Curve.P_256; - - } else if (spec.getCurve().getField().getFieldSize() == P_256K_SPEC.getCurve().getField().getFieldSize() && - spec.getCurve().getA().equals(P_256K_SPEC.getCurve().getA()) && - spec.getCurve().getB().equals(P_256K_SPEC.getCurve().getB()) && - spec.getGenerator().getAffineX().equals(P_256K_SPEC.getGenerator().getAffineX()) && - spec.getGenerator().getAffineY().equals(P_256K_SPEC.getGenerator().getAffineY()) && - spec.getOrder().equals(P_256K_SPEC.getOrder()) && - spec.getCofactor() == P_256K_SPEC.getCofactor()) { - - return Curve.P_256K; - - } else if (spec.getCurve().getField().getFieldSize() == P_384_SPEC.getCurve().getField().getFieldSize() && - spec.getCurve().getA().equals(P_384_SPEC.getCurve().getA()) && - spec.getCurve().getB().equals(P_384_SPEC.getCurve().getB()) && - spec.getGenerator().getAffineX().equals(P_384_SPEC.getGenerator().getAffineX()) && - spec.getGenerator().getAffineY().equals(P_384_SPEC.getGenerator().getAffineY()) && - spec.getOrder().equals(P_384_SPEC.getOrder()) && - spec.getCofactor() == P_384_SPEC.getCofactor()) { - - return Curve.P_384; - - } else if (spec.getCurve().getField().getFieldSize() == P_521_SPEC.getCurve().getField().getFieldSize() && - spec.getCurve().getA().equals(P_521_SPEC.getCurve().getA()) && - spec.getCurve().getB().equals(P_521_SPEC.getCurve().getB()) && - spec.getGenerator().getAffineX().equals(P_521_SPEC.getGenerator().getAffineX()) && - spec.getGenerator().getAffineY().equals(P_521_SPEC.getGenerator().getAffineY()) && - spec.getOrder().equals(P_521_SPEC.getOrder()) && - spec.getCofactor() == P_521_SPEC.getCofactor()) { - - return Curve.P_521; - - } else { - return null; - } - } - - - /** - * Prevents public instantiation. - */ - private ECParameterTable() { - - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/JWK.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/JWK.java deleted file mode 100644 index a64b579b8..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/JWK.java +++ /dev/null @@ -1,845 +0,0 @@ -/* - * 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.jwk; - - -import java.io.Serializable; -import java.net.URI; -import java.security.*; -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.security.spec.ECParameterSpec; -import java.text.ParseException; -import java.util.*; - -import net.minidev.json.JSONAware; -import net.minidev.json.JSONObject; - -import com.nimbusds.jose.Algorithm; -import com.nimbusds.jose.JOSEException; -import com.nimbusds.jose.util.Base64; -import com.nimbusds.jose.util.*; - - -/** - * The base abstract class for JSON Web Keys (JWKs). It serialises to a JSON - * object. - * - *

The following JSON object members are common to all JWK types: - * - *

    - *
  • {@link #getKeyType kty} (required) - *
  • {@link #getKeyUse use} (optional) - *
  • {@link #getKeyOperations key_ops} (optional) - *
  • {@link #getKeyID kid} (optional) - *
  • {@link #getX509CertURL() x5u} (optional) - *
  • {@link #getX509CertThumbprint() x5t} (optional) - *
  • {@link #getX509CertSHA256Thumbprint() x5t#S256} (optional) - *
  • {@link #getX509CertChain() x5c} (optional) - *
  • {@link #getKeyStore()} - *
- * - *

Example JWK (of the Elliptic Curve type): - * - *

- * {
- *   "kty" : "EC",
- *   "crv" : "P-256",
- *   "x"   : "MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4",
- *   "y"   : "4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM",
- *   "use" : "enc",
- *   "kid" : "1"
- * }
- * 
- * - * @author Vladimir Dzhuvinov - * @author Justin Richer - * @author Stefan Larsson - * @version 2019-04-15 - */ -public abstract class JWK implements JSONAware, Serializable { - - - private static final long serialVersionUID = 1L; - - - /** - * The MIME type of JWK objects: - * {@code application/jwk+json; charset=UTF-8} - */ - public static final String MIME_TYPE = "application/jwk+json; charset=UTF-8"; - - - /** - * The key type, required. - */ - private final KeyType kty; - - - /** - * The key use, optional. - */ - private final KeyUse use; - - - /** - * The key operations, optional. - */ - private final Set ops; - - - /** - * The intended JOSE algorithm for the key, optional. - */ - private final Algorithm alg; - - - /** - * The key ID, optional. - */ - private final String kid; - - - /** - * X.509 certificate URL, optional. - */ - private final URI x5u; - - - /** - * X.509 certificate SHA-1 thumbprint, optional. - */ - @Deprecated - private final Base64URL x5t; - - - /** - * X.509 certificate SHA-256 thumbprint, optional. - */ - private Base64URL x5t256; - - - /** - * The X.509 certificate chain, optional. - */ - private final List x5c; - - - /** - * The parsed X.509 certificate chain, optional. - */ - private final List parsedX5c; - - - /** - * Reference to the underlying key store, {@code null} if none. - */ - private final KeyStore keyStore; - - - /** - * Creates a new JSON Web Key (JWK). - * - * @param kty The key type. Must not be {@code null}. - * @param use The key use, {@code null} if not specified or if the - * key is intended for signing as well as encryption. - * @param ops The key operations, {@code null} if not specified. - * @param alg The intended JOSE algorithm for the key, {@code null} - * if not specified. - * @param kid The key ID, {@code null} if not specified. - * @param x5u The X.509 certificate URL, {@code null} if not - * specified. - * @param x5t The X.509 certificate thumbprint, {@code null} if not - * specified. - * @param x5t256 The X.509 certificate SHA-256 thumbprint, {@code null} - * if not specified. - * @param x5c The X.509 certificate chain, {@code null} if not - * specified. - * @param ks Reference to the underlying key store, {@code null} if - * none. - */ - protected JWK(final KeyType kty, - final KeyUse use, - final Set ops, - final Algorithm alg, - final String kid, - final URI x5u, - final Base64URL x5t, - final Base64URL x5t256, - final List x5c, - final KeyStore ks) { - - if (kty == null) { - throw new IllegalArgumentException("The key type \"kty\" parameter must not be null"); - } - - this.kty = kty; - - if (! KeyUseAndOpsConsistency.areConsistent(use, ops)) { - throw new IllegalArgumentException("The key use \"use\" and key options \"key_opts\" parameters are not consistent, " + - "see RFC 7517, section 4.3"); - } - - this.use = use; - this.ops = ops; - - this.alg = alg; - this.kid = kid; - - this.x5u = x5u; - this.x5t = x5t; - this.x5t256 = x5t256; - - if (x5c != null && x5c.isEmpty()) { - throw new IllegalArgumentException("The X.509 certificate chain \"x5c\" must not be empty"); - } - this.x5c = x5c; - - try { - parsedX5c = X509CertChainUtils.parse(x5c); - } catch (ParseException e) { - throw new IllegalArgumentException("Invalid X.509 certificate chain \"x5c\": " + e.getMessage(), e); - } - - this.keyStore = ks; - } - - - /** - * Gets the type ({@code kty}) of this JWK. - * - * @return The key type. - */ - public KeyType getKeyType() { - - return kty; - } - - - /** - * Gets the use ({@code use}) of this JWK. - * - * @return The key use, {@code null} if not specified or if the key is - * intended for signing as well as encryption. - */ - public KeyUse getKeyUse() { - - return use; - } - - - /** - * Gets the operations ({@code key_ops}) for this JWK. - * - * @return The key operations, {@code null} if not specified. - */ - public Set getKeyOperations() { - - return ops; - } - - - /** - * Gets the intended JOSE algorithm ({@code alg}) for this JWK. - * - * @return The intended JOSE algorithm, {@code null} if not specified. - */ - public Algorithm getAlgorithm() { - - return alg; - } - - - /** - * Gets the ID ({@code kid}) of this JWK. The key ID can be used to - * match a specific key. This can be used, for instance, to choose a - * key within a {@link JWKSet} during key rollover. The key ID may also - * correspond to a JWS/JWE {@code kid} header parameter value. - * - * @return The key ID, {@code null} if not specified. - */ - public String getKeyID() { - - return kid; - } - - - /** - * Gets the X.509 certificate URL ({@code x5u}) of this JWK. - * - * @return The X.509 certificate URL, {@code null} if not specified. - */ - public URI getX509CertURL() { - - return x5u; - } - - - /** - * Gets the X.509 certificate SHA-1 thumbprint ({@code x5t}) of this - * JWK. - * - * @return The X.509 certificate SHA-1 thumbprint, {@code null} if not - * specified. - */ - @Deprecated - public Base64URL getX509CertThumbprint() { - - return x5t; - } - - - /** - * Gets the X.509 certificate SHA-256 thumbprint ({@code x5t#S256}) of - * this JWK. - * - * @return The X.509 certificate SHA-256 thumbprint, {@code null} if - * not specified. - */ - public Base64URL getX509CertSHA256Thumbprint() { - - return x5t256; - } - - - /** - * Gets the X.509 certificate chain ({@code x5c}) of this JWK. - * - * @return The X.509 certificate chain as a unmodifiable list, - * {@code null} if not specified. - */ - public List getX509CertChain() { - - if (x5c == null) { - return null; - } - - return Collections.unmodifiableList(x5c); - } - - - /** - * Gets the parsed X.509 certificate chain ({@code x5c}) of this JWK. - * - * @return The X.509 certificate chain as a unmodifiable list, - * {@code null} if not specified. - */ - public List getParsedX509CertChain() { - - if (parsedX5c == null) { - return null; - } - - return Collections.unmodifiableList(parsedX5c); - } - - - /** - * Returns a reference to the underlying key store. - * - * @return The underlying key store, {@code null} if none. - */ - public KeyStore getKeyStore() { - - return keyStore; - } - - - /** - * Returns the required JWK parameters. Intended as input for JWK - * thumbprint computation. See RFC 7638 for more information. - * - * @return The required JWK parameters, sorted alphanumerically by key - * name and ready for JSON serialisation. - */ - public abstract LinkedHashMap getRequiredParams(); - - - /** - * Computes the SHA-256 thumbprint of this JWK. See RFC 7638 for more - * information. - * - * @return The SHA-256 thumbprint. - * - * @throws JOSEException If the SHA-256 hash algorithm is not - * supported. - */ - public Base64URL computeThumbprint() - throws JOSEException { - - return computeThumbprint("SHA-256"); - } - - - /** - * Computes the thumbprint of this JWK using the specified hash - * algorithm. See RFC 7638 for more information. - * - * @param hashAlg The hash algorithm. Must not be {@code null}. - * - * @return The SHA-256 thumbprint. - * - * @throws JOSEException If the hash algorithm is not supported. - */ - public Base64URL computeThumbprint(final String hashAlg) - throws JOSEException { - - return ThumbprintUtils.compute(hashAlg, this); - } - - - /** - * Returns {@code true} if this JWK contains private or sensitive - * (non-public) parameters. - * - * @return {@code true} if this JWK contains private parameters, else - * {@code false}. - */ - public abstract boolean isPrivate(); - - - /** - * Creates a copy of this JWK with all private or sensitive parameters - * removed. - * - * @return The newly created public JWK, or {@code null} if none can be - * created. - */ - public abstract JWK toPublicJWK(); - - - /** - * Returns the size of this JWK. - * - * @return The JWK size, in bits. - */ - public abstract int size(); - - - /** - * Returns a JSON object representation of this JWK. This method is - * intended to be called from extending classes. - * - *

Example: - * - *

-	 * {
-	 *   "kty" : "RSA",
-	 *   "use" : "sig",
-	 *   "kid" : "fd28e025-8d24-48bc-a51a-e2ffc8bc274b"
-	 * }
-	 * 
- * - * @return The JSON object representation. - */ - public JSONObject toJSONObject() { - - JSONObject o = new JSONObject(); - - o.put("kty", kty.getValue()); - - if (use != null) { - o.put("use", use.identifier()); - } - - if (ops != null) { - - List sl = new ArrayList<>(ops.size()); - - for (KeyOperation op: ops) { - sl.add(op.identifier()); - } - - o.put("key_ops", sl); - } - - if (alg != null) { - o.put("alg", alg.getName()); - } - - if (kid != null) { - o.put("kid", kid); - } - - 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) { - o.put("x5c", x5c); - } - - return o; - } - - - /** - * Returns the JSON object string representation of this JWK. - * - * @return The JSON object string representation. - */ - @Override - public String toJSONString() { - - return toJSONObject().toString(); - } - - - /** - * @see #toJSONString - */ - @Override - public String toString() { - - return toJSONObject().toString(); - } - - - /** - * Parses a JWK from the specified JSON object string representation. - * The JWK must be an {@link ECKey}, an {@link RSAKey}, or a - * {@link OctetSequenceKey}. - * - * @param s The JSON object string to parse. Must not be {@code null}. - * - * @return The JWK. - * - * @throws ParseException If the string couldn't be parsed to a - * supported JWK. - */ - public static JWK parse(final String s) - throws ParseException { - - return parse(JSONObjectUtils.parse(s)); - } - - - /** - * Parses a JWK from the specified JSON object representation. The JWK - * must be an {@link ECKey}, an {@link RSAKey}, or a - * {@link OctetSequenceKey}. - * - * @param jsonObject The JSON object to parse. Must not be - * {@code null}. - * - * @return The JWK. - * - * @throws ParseException If the JSON object couldn't be parsed to a - * supported JWK. - */ - public static JWK parse(final JSONObject jsonObject) - throws ParseException { - - KeyType kty = KeyType.parse(JSONObjectUtils.getString(jsonObject, "kty")); - - if (kty == KeyType.EC) { - - return ECKey.parse(jsonObject); - - } else if (kty == KeyType.RSA) { - - return RSAKey.parse(jsonObject); - - } else if (kty == KeyType.OCT) { - - return OctetSequenceKey.parse(jsonObject); - - } else if (kty == KeyType.OKP) { - - return OctetKeyPair.parse(jsonObject); - - } else { - - throw new ParseException("Unsupported key type \"kty\" parameter: " + kty, 0); - } - } - - - /** - * Parses a public {@link RSAKey RSA} or {@link ECKey EC JWK} from the - * specified X.509 certificate. Requires BouncyCastle. - * - *

Important: The X.509 certificate is not - * validated! - * - *

Sets the following JWK parameters: - * - *

    - *
  • For an EC key the curve is obtained from the subject public - * key info algorithm parameters. - *
  • The JWK use inferred by {@link KeyUse#from}. - *
  • The JWK ID from the X.509 serial number (in base 10). - *
  • The JWK X.509 certificate chain (this certificate only). - *
  • The JWK X.509 certificate SHA-256 thumbprint. - *
- * - * @param cert The X.509 certificate. Must not be {@code null}. - * - * @return The public RSA or EC JWK. - * - * @throws JOSEException If parsing failed. - */ - public static JWK parse(final X509Certificate cert) - throws JOSEException { - - if (cert.getPublicKey() instanceof RSAPublicKey) { - return RSAKey.parse(cert); - } else if (cert.getPublicKey() instanceof ECPublicKey) { - return ECKey.parse(cert); - } else { - throw new JOSEException("Unsupported public key algorithm: " + cert.getPublicKey().getAlgorithm()); - } - } - - - /** - * Parses a public {@link RSAKey RSA} or {@link ECKey EC JWK} from the - * specified PEM-encoded X.509 certificate. Requires BouncyCastle. - * - *

Important: The X.509 certificate is not - * validated! - * - *

Sets the following JWK parameters: - * - *

    - *
  • For an EC key the curve is obtained from the subject public - * key info algorithm parameters. - *
  • The JWK use inferred by {@link KeyUse#from}. - *
  • The JWK ID from the X.509 serial number (in base 10). - *
  • The JWK X.509 certificate chain (this certificate only). - *
  • The JWK X.509 certificate SHA-256 thumbprint. - *
- * - * @param pemEncodedCert The PEM-encoded X.509 certificate. Must not be - * {@code null}. - * - * @return The public RSA or EC JWK. - * - * @throws JOSEException If parsing failed. - */ - public static JWK parseFromPEMEncodedX509Cert(final String pemEncodedCert) - throws JOSEException { - - X509Certificate cert = X509CertUtils.parse(pemEncodedCert); - - if (cert == null) { - throw new JOSEException("Couldn't parse PEM-encoded X.509 certificate"); - } - - return parse(cert); - } - - - /** - * Loads a JWK from the specified JCE key store. The JWK can be a - * public / private {@link RSAKey RSA key}, a public / private - * {@link ECKey EC key}, or a {@link OctetSequenceKey secret key}. - * Requires BouncyCastle. - * - *

Important: The X.509 certificate is not - * validated! - * - * @param keyStore The key store. Must not be {@code null}. - * @param alias The alias. Must not be {@code null}. - * @param pin The pin to unlock the private key if any, empty or - * {@code null} if not required. - * - * @return The public / private RSA or EC JWK, or secret JWK, or - * {@code null} if no key with the specified alias was found. - * - * @throws KeyStoreException On a key store exception. - * @throws JOSEException If RSA or EC key loading failed. - */ - public static JWK load(final KeyStore keyStore, final String alias, final char[] pin) - throws KeyStoreException, JOSEException { - - java.security.cert.Certificate cert = keyStore.getCertificate(alias); - - if (cert == null) { - // Try secret key - return OctetSequenceKey.load(keyStore, alias, pin); - } - - if (cert.getPublicKey() instanceof RSAPublicKey) { - return RSAKey.load(keyStore, alias, pin); - } else if (cert.getPublicKey() instanceof ECPublicKey) { - return ECKey.load(keyStore, alias, pin); - } else { - throw new JOSEException("Unsupported public key algorithm: " + cert.getPublicKey().getAlgorithm()); - } - } - - /** - * Parses an RSA or EC JWK from the specified string of one or more - * PEM-encoded object(s): - * - *

    - *
  • X.509 certificate (PEM header: BEGIN CERTIFICATE) - *
  • PKCS#1 RSAPublicKey (PEM header: BEGIN RSA PUBLIC KEY) - *
  • X.509 SubjectPublicKeyInfo (PEM header: BEGIN PUBLIC KEY) - *
  • PKCS#1 RSAPrivateKey (PEM header: BEGIN RSA PRIVATE KEY) - *
  • PKCS#8 PrivateKeyInfo (PEM header: BEGIN PRIVATE KEY) - *
  • matching pair of the above - *
- * - *

Requires BouncyCastle. - * - * @param pemEncodedObjects The string of PEM-encoded object(s). - * - * @return The public / (private) RSA or EC JWK. - * - * @throws JOSEException If RSA or EC key parsing failed. - */ - public static JWK parseFromPEMEncodedObjects(final String pemEncodedObjects) - throws JOSEException { - - final List keys = PEMEncodedKeyParser.parseKeys(pemEncodedObjects); - if (keys.isEmpty()) { - throw new JOSEException("No PEM-encoded keys found"); - } - - final KeyPair pair = mergeKeyPairs(toKeyPairList(pemEncodedObjects)); - - final PublicKey publicKey = pair.getPublic(); - final PrivateKey privateKey = pair.getPrivate(); - - if (publicKey instanceof ECPublicKey) { - final ECPublicKey ecPubKey = (ECPublicKey) publicKey; - final ECParameterSpec pubParams = ecPubKey.getParams(); - - if (privateKey instanceof ECPrivateKey) { - validateEcCurves(ecPubKey, (ECPrivateKey) privateKey); - } - if (privateKey != null && !(privateKey instanceof ECPrivateKey)) { - throw new JOSEException("Unsupported EC private key type: " + privateKey); - } - - final Curve curve = Curve.forECParameterSpec(pubParams); - final ECKey.Builder builder = new ECKey.Builder(curve, (ECPublicKey) publicKey); - - if (privateKey != null) { - builder.privateKey((ECPrivateKey) privateKey); - } - return builder.build(); - } - - if (publicKey instanceof RSAPublicKey) { - final RSAKey.Builder builder = new RSAKey.Builder((RSAPublicKey) publicKey); - if (privateKey instanceof RSAPrivateKey) { - builder.privateKey((RSAPrivateKey) privateKey); - } else if (privateKey != null) { - throw new JOSEException("Unsupported RSA private key type: " + privateKey); - } - return builder.build(); - } - - throw new JOSEException("Unsupported algorithm of PEM-encoded key: " + publicKey.getAlgorithm()); - } - - - private static void validateEcCurves(ECPublicKey publicKey, ECPrivateKey privateKey) throws JOSEException { - final ECParameterSpec pubParams = publicKey.getParams(); - final ECParameterSpec privParams = privateKey.getParams(); - if (!pubParams.getCurve().equals(privParams.getCurve())) { - throw new JOSEException("Public/private EC key curve mismatch: " + publicKey); - } - if (pubParams.getCofactor() != privParams.getCofactor()) { - throw new JOSEException("Public/private EC key cofactor mismatch: " + publicKey); - } - if (!pubParams.getGenerator().equals(privParams.getGenerator())) { - throw new JOSEException("Public/private EC key generator mismatch: " + publicKey); - } - if (!pubParams.getOrder().equals(privParams.getOrder())) { - throw new JOSEException("Public/private EC key order mismatch: " + publicKey); - } - } - - - private static KeyPair mergeKeyPairs(final List keys) throws JOSEException { - final KeyPair pair; - if (keys.size() == 1) { - // Assume public key, or private key easy to convert to public, - // otherwise not representable as a JWK - pair = keys.get(0); - } else if (keys.size() == 2) { - // If two keys, assume public + private keys separated - pair = twoKeysToKeyPair(keys); - } else { - throw new JOSEException("Expected key or pair of PEM-encoded keys"); - } - return pair; - } - - - private static List toKeyPairList(final String pem) throws JOSEException { - final List keys = PEMEncodedKeyParser.parseKeys(pem); - if (keys.isEmpty()) { - throw new JOSEException("No PEM-encoded keys found"); - } - return keys; - } - - - private static KeyPair twoKeysToKeyPair(final List keys) throws JOSEException { - final KeyPair key1 = keys.get(0); - final KeyPair key2 = keys.get(1); - if (key1.getPublic() != null && key2.getPrivate() != null) { - return new KeyPair(key1.getPublic(), key2.getPrivate()); - } else if (key1.getPrivate() != null && key2.getPublic() != null) { - return new KeyPair(key2.getPublic(), key1.getPrivate()); - } else { - throw new JOSEException("Not a public/private key pair"); - } - } - - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof JWK)) return false; - JWK jwk = (JWK) o; - return Objects.equals(kty, jwk.kty) && - Objects.equals(use, jwk.use) && - Objects.equals(ops, jwk.ops) && - Objects.equals(alg, jwk.alg) && - Objects.equals(kid, jwk.kid) && - Objects.equals(x5u, jwk.x5u) && - Objects.equals(x5t, jwk.x5t) && - Objects.equals(x5t256, jwk.x5t256) && - Objects.equals(x5c, jwk.x5c) && - Objects.equals(parsedX5c, jwk.parsedX5c) && - Objects.equals(keyStore, jwk.keyStore); - } - - - @Override - public int hashCode() { - return Objects.hash(kty, use, ops, alg, kid, x5u, x5t, x5t256, x5c, parsedX5c, keyStore); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/JWKMatcher.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/JWKMatcher.java deleted file mode 100644 index de8b79c0c..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/JWKMatcher.java +++ /dev/null @@ -1,1377 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2019, 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.jwk; - - -import java.util.*; - -import com.nimbusds.jose.Algorithm; -import com.nimbusds.jose.JWEHeader; -import com.nimbusds.jose.JWSAlgorithm; -import com.nimbusds.jose.JWSHeader; -import com.nimbusds.jose.util.Base64URL; -import net.jcip.annotations.Immutable; - - -/** - * JSON Web Key (JWK) matcher. May be used to ensure a JWK matches a set of - * application-specific criteria. - * - *

Supported key matching criteria: - * - *

    - *
  • Any, unspecified, one or more key types (typ). - *
  • Any, unspecified, one or more key uses (use). - *
  • Any, unspecified, one or more key operations (key_ops). - *
  • Any, unspecified, one or more key algorithms (alg). - *
  • Any, unspecified, one or more key identifiers (kid). - *
  • Private only key. - *
  • Public only key. - *
  • Minimum, maximum or exact key sizes. - *
  • Any, unspecified, one or more curves for EC and OKP keys (crv). - *
  • X.509 certificate SHA-256 thumbprint. - *
- * - *

Matching by JWK thumbprint (RFC 7638), X.509 certificate URL and X.509 - * certificate chain is not supported. - * - * @author Vladimir Dzhuvinov - * @author Josh Cummings - * @version 2018-06-13 - */ -@Immutable -public class JWKMatcher { - - - /** - * The key types to match. - */ - private final Set types; - - - /** - * The public key uses to match. - */ - private final Set uses; - - - /** - * The key operations to match. - */ - private final Set ops; - - - /** - * The algorithms to match. - */ - private final Set algs; - - - /** - * The key IDs to match. - */ - private final Set ids; - - - /** - * {@code true} to match a key with a set use. - */ - private final boolean hasUse; - - - /** - * {@code true} to match a key with a set ID. - */ - private final boolean hasID; - - - /** - * {@code true} to match a private key. - */ - private final boolean privateOnly; - - - /** - * {@code true} to match a public only key. - */ - private final boolean publicOnly; - - - /** - * The minimum key size in bits, zero implies no minimum size limit. - */ - private final int minSizeBits; - - - /** - * The maximum key size in bits, zero implies no maximum size limit. - */ - private final int maxSizeBits; - - - /** - * The key sizes in bits. - */ - private final Set sizesBits; - - - /** - * The curves to match (for EC and OKP keys). - */ - private final Set curves; - - - /** - * The X.509 certificate SHA-256 thumbprints to match. - */ - private final Set x5tS256s; - - - /** - * Builder for constructing JWK matchers. - * - *

Example usage: - * - *

-	 * JWKMatcher matcher = new JWKMatcher().keyID("123").build();
-	 * 
- */ - public static class Builder { - - - /** - * The key types to match. - */ - private Set types; - - - /** - * The public key uses to match. - */ - private Set uses; - - - /** - * The key operations to match. - */ - private Set ops; - - - /** - * The algorithms to match. - */ - private Set algs; - - - /** - * The key IDs to match. - */ - private Set ids; - - - /** - * {@code true} to match a key with a set use. - */ - private boolean hasUse = false; - - - /** - * {@code true} to match a key with a set ID. - */ - private boolean hasID = false; - - - /** - * {@code true} to match a private key. - */ - private boolean privateOnly = false; - - - /** - * {@code true} to match a public only key. - */ - private boolean publicOnly = false; - - - /** - * The minimum key size in bits, zero implies no minimum size - * limit. - */ - private int minSizeBits = 0; - - - /** - * The maximum key size in bits, zero implies no maximum size - * limit. - */ - private int maxSizeBits = 0; - - - /** - * The key sizes in bits. - */ - private Set sizesBits; - - - /** - * The curves to match (for EC and OKP keys). - */ - private Set curves; - - - /** - * The X.509 certificate SHA-256 thumbprints to match. - */ - private Set x5tS256s; - - - /** - * Sets a single key type to match. - * - * @param kty The key type, {@code null} if not specified. - * - * @return This builder. - */ - public Builder keyType(final KeyType kty) { - - if (kty == null) { - types = null; - } else { - types = new HashSet<>(Collections.singletonList(kty)); - } - - return this; - } - - - /** - * Sets multiple key types to match. - * - * @param types The key types. - * - * @return This builder. - */ - public Builder keyTypes(final KeyType ... types) { - - keyTypes(new LinkedHashSet<>(Arrays.asList(types))); - return this; - } - - - /** - * Sets multiple key types to match. - * - * @param types The key types, {@code null} if not specified. - * - * @return This builder. - */ - public Builder keyTypes(final Set types) { - - this.types = types; - return this; - } - - - /** - * Sets a single public key use to match. - * - * @param use The public key use, {@code null} if not - * specified. - * - * @return This builder. - */ - public Builder keyUse(final KeyUse use) { - - if (use == null) { - uses = null; - } else { - uses = new HashSet<>(Collections.singletonList(use)); - } - return this; - } - - - /** - * Sets multiple public key uses to match. - * - * @param uses The public key uses. - * - * @return This builder. - */ - public Builder keyUses(final KeyUse... uses) { - - keyUses(new LinkedHashSet<>(Arrays.asList(uses))); - return this; - } - - - /** - * Sets multiple public key uses to match. - * - * @param uses The public key uses, {@code null} if not - * specified. - * - * @return This builder. - */ - public Builder keyUses(final Set uses) { - - this.uses = uses; - return this; - } - - - /** - * Sets a single key operation to match. - * - * @param op The key operation, {@code null} if not specified. - * - * @return This builder. - */ - public Builder keyOperation(final KeyOperation op) { - - if (op == null) { - ops = null; - } else { - ops = new HashSet<>(Collections.singletonList(op)); - } - return this; - } - - - /** - * Sets multiple key operations to match. - * - * @param ops The key operations. - * - * @return This builder. - */ - public Builder keyOperations(final KeyOperation... ops) { - - keyOperations(new LinkedHashSet<>(Arrays.asList(ops))); - return this; - } - - - /** - * Sets multiple key operations to match. - * - * @param ops The key operations, {@code null} if not - * specified. - * - * @return This builder. - */ - public Builder keyOperations(final Set ops) { - - this.ops = ops; - return this; - } - - - /** - * Sets a single JOSE algorithm to match. - * - * @param alg The JOSE algorithm, {@code null} if not - * specified. - * - * @return This builder. - */ - public Builder algorithm(final Algorithm alg) { - - if (alg == null) { - algs = null; - } else { - algs = new HashSet<>(Collections.singletonList(alg)); - } - return this; - } - - - /** - * Sets multiple JOSE algorithms to match. - * - * @param algs The JOSE algorithms. - * - * @return This builder. - */ - public Builder algorithms(final Algorithm ... algs) { - - algorithms(new LinkedHashSet<>(Arrays.asList(algs))); - return this; - } - - - /** - * Sets multiple JOSE algorithms to match. - * - * @param algs The JOSE algorithms, {@code null} if not - * specified. - * - * @return This builder. - */ - public Builder algorithms(final Set algs) { - - this.algs = algs; - return this; - } - - - /** - * Sets a single key ID to match. - * - * @param id The key ID, {@code null} if not specified. - * - * @return This builder. - */ - public Builder keyID(final String id) { - - if (id == null) { - ids = null; - } else { - ids = new HashSet<>(Collections.singletonList(id)); - } - return this; - } - - - /** - * Sets multiple key IDs to match. - * - * @param ids The key IDs. - * - * @return This builder. - */ - public Builder keyIDs(final String ... ids) { - - keyIDs(new LinkedHashSet<>(Arrays.asList(ids))); - return this; - } - - - /** - * Sets multiple key IDs to match. - * - * @param ids The key IDs, {@code null} if not specified. - * - * @return This builder. - */ - public Builder keyIDs(final Set ids) { - - this.ids = ids; - return this; - } - - - /** - * Sets key use presence matching. - * - * @param hasUse {@code true} to match a key with a set use. - * - * @return This builder. - */ - public Builder hasKeyUse(final boolean hasUse) { - - this.hasUse = hasUse; - return this; - } - - - /** - * Sets key ID presence matching. - * - * @param hasID {@code true} to match a key with a set ID. - * - * @return This builder. - */ - public Builder hasKeyID(final boolean hasID) { - - this.hasID = hasID; - return this; - } - - - /** - * Sets the private key matching policy. - * - * @param privateOnly {@code true} to match a private key. - * - * @return This builder. - */ - public Builder privateOnly(final boolean privateOnly) { - - this.privateOnly = privateOnly; - return this; - } - - - /** - * Sets the public key matching policy. - * - * @param publicOnly {@code true} to match a public only key. - * - * @return This builder. - */ - public Builder publicOnly(final boolean publicOnly) { - - this.publicOnly = publicOnly; - return this; - } - - - /** - * Sets the minimal key size. - * - * @param minSizeBits The minimum key size in bits, zero - * implies no minimum key size limit. - * - * @return This builder. - */ - public Builder minKeySize(final int minSizeBits) { - - this.minSizeBits = minSizeBits; - return this; - } - - - /** - * Sets the maximum key size. - * - * @param maxSizeBits The maximum key size in bits, zero - * implies no maximum key size limit. - * - * @return This builder. - */ - public Builder maxKeySize(final int maxSizeBits) { - - this.maxSizeBits = maxSizeBits; - return this; - } - - - /** - * Sets the key size. - * - * @param keySizeBits The key size in bits, zero if not - * specified. - * - * @return This builder. - */ - public Builder keySize(final int keySizeBits) { - if (keySizeBits <= 0) { - sizesBits = null; - } else { - sizesBits = Collections.singleton(keySizeBits); - } - return this; - } - - - /** - * Sets the key sizes. - * - * @param keySizesBits The key sizes in bits. - * - * @return This builder. - */ - public Builder keySizes(final int... keySizesBits) { - Set sizesSet = new LinkedHashSet<>(); - for (int keySize: keySizesBits) { - sizesSet.add(keySize); - } - keySizes(sizesSet); - return this; - } - - - /** - * Sets the key sizes. - * - * @param keySizesBits The key sizes in bits. - * - * @return This builder. - */ - public Builder keySizes(final Set keySizesBits) { - - this.sizesBits = keySizesBits; - return this; - } - - - /** - * Sets a single curve to match (for EC and OKP keys). - * - * @param curve The curve, {@code null} if not specified. - * - * @return This builder. - */ - public Builder curve(final Curve curve) { - - if (curve == null) { - curves = null; - } else { - curves = new HashSet<>(Collections.singletonList(curve)); - } - return this; - } - - - /** - * Sets multiple curves to match (for EC and OKP keys). - * - * @param curves The curves. - * - * @return This builder. - */ - public Builder curves(final Curve... curves) { - - curves(new LinkedHashSet<>(Arrays.asList(curves))); - return this; - } - - - /** - * Sets multiple curves to match (for EC and OKP keys). - * - * @param curves The curves, {@code null} if not specified. - * - * @return This builder. - */ - public Builder curves(final Set curves) { - - this.curves = curves; - return this; - } - - - /** - * Sets a single X.509 certificate SHA-256 thumbprint to match. - * - * @param x5tS256 The thumbprint, {@code null} if not - * specified. - * - * @return This builder. - */ - public Builder x509CertSHA256Thumbprint(final Base64URL x5tS256) { - - if (x5tS256 == null) { - x5tS256s = null; - } else { - x5tS256s = Collections.singleton(x5tS256); - } - return this; - } - - /** - * Sets multiple X.509 certificate SHA-256 thumbprints to - * match. - * - * @param x5tS256s The thumbprints. - * - * @return This builder. - */ - public Builder x509CertSHA256Thumbprints(final Base64URL... x5tS256s) { - return x509CertSHA256Thumbprints(new LinkedHashSet<>(Arrays.asList(x5tS256s))); - } - - - /** - * Sets multiple X.509 certificate SHA-256 thumbprints to - * match. - * - * @param x5tS256s The thumbprints, {@code null} if not - * specified. - * - * @return This builder. - */ - public Builder x509CertSHA256Thumbprints(final Set x5tS256s) { - this.x5tS256s = x5tS256s; - return this; - } - - /** - * Builds a new JWK matcher. - * - * @return The JWK matcher. - */ - public JWKMatcher build() { - - return new JWKMatcher(types, uses, ops, algs, ids, hasUse, hasID, privateOnly, publicOnly, minSizeBits, maxSizeBits, sizesBits, curves, x5tS256s); - } - } - - - /** - * Creates a new JSON Web Key (JWK) matcher. - * - * @param types The key types to match, {@code null} if not - * specified. - * @param uses The public key uses to match, {@code null} if not - * specified. - * @param ops The key operations to match, {@code null} if not - * specified. - * @param algs The JOSE algorithms to match, {@code null} if not - * specified. - * @param ids The key IDs to match, {@code null} if not - * specified. - * @param privateOnly {@code true} to match a private key. - * @param publicOnly {@code true} to match a public only key. - */ - @Deprecated - public JWKMatcher(final Set types, - final Set uses, - final Set ops, - final Set algs, - final Set ids, - final boolean privateOnly, - final boolean publicOnly) { - - this(types, uses, ops, algs, ids, privateOnly, publicOnly, 0, 0); - } - - - /** - * Creates a new JSON Web Key (JWK) matcher. - * - * @param types The key types to match, {@code null} if not - * specified. - * @param uses The public key uses to match, {@code null} if not - * specified. - * @param ops The key operations to match, {@code null} if not - * specified. - * @param algs The JOSE algorithms to match, {@code null} if not - * specified. - * @param ids The key IDs to match, {@code null} if not - * specified. - * @param privateOnly {@code true} to match a private key. - * @param publicOnly {@code true} to match a public only key. - * @param minSizeBits The minimum key size in bits, zero implies no - * minimum size limit. - * @param maxSizeBits The maximum key size in bits, zero implies no - * maximum size limit. - */ - @Deprecated - public JWKMatcher(final Set types, - final Set uses, - final Set ops, - final Set algs, - final Set ids, - final boolean privateOnly, - final boolean publicOnly, - final int minSizeBits, - final int maxSizeBits) { - - this(types, uses, ops, algs, ids, privateOnly, publicOnly, minSizeBits, maxSizeBits, null); - } - - - /** - * Creates a new JSON Web Key (JWK) matcher. - * - * @param types The key types to match, {@code null} if not - * specified. - * @param uses The public key uses to match, {@code null} if not - * specified. - * @param ops The key operations to match, {@code null} if not - * specified. - * @param algs The JOSE algorithms to match, {@code null} if not - * specified. - * @param ids The key IDs to match, {@code null} if not - * specified. - * @param privateOnly {@code true} to match a private key. - * @param publicOnly {@code true} to match a public only key. - * @param minSizeBits The minimum key size in bits, zero implies no - * minimum size limit. - * @param maxSizeBits The maximum key size in bits, zero implies no - * maximum size limit. - * @param curves The curves to match (for EC keys), {@code null} - * if not specified. - */ - @Deprecated - public JWKMatcher(final Set types, - final Set uses, - final Set ops, - final Set algs, - final Set ids, - final boolean privateOnly, - final boolean publicOnly, - final int minSizeBits, - final int maxSizeBits, - final Set curves) { - - this(types, uses, ops, algs, ids, privateOnly, publicOnly, minSizeBits, maxSizeBits, null, curves); - } - - - /** - * Creates a new JSON Web Key (JWK) matcher. - * - * @param types The key types to match, {@code null} if not - * specified. - * @param uses The public key uses to match, {@code null} if not - * specified. - * @param ops The key operations to match, {@code null} if not - * specified. - * @param algs The JOSE algorithms to match, {@code null} if not - * specified. - * @param ids The key IDs to match, {@code null} if not - * specified. - * @param privateOnly {@code true} to match a private key. - * @param publicOnly {@code true} to match a public only key. - * @param minSizeBits The minimum key size in bits, zero implies no - * minimum size limit. - * @param maxSizeBits The maximum key size in bits, zero implies no - * maximum size limit. - * @param sizesBits The key sizes in bits, {@code null} if not - * specified. - * @param curves The curves to match (for EC and OKP keys), - * {@code null} if not specified. - */ - @Deprecated - public JWKMatcher(final Set types, - final Set uses, - final Set ops, - final Set algs, - final Set ids, - final boolean privateOnly, - final boolean publicOnly, - final int minSizeBits, - final int maxSizeBits, - final Set sizesBits, - final Set curves) { - - this(types, uses, ops, algs, ids, false, false, privateOnly, publicOnly, minSizeBits, maxSizeBits, sizesBits, curves); - } - - - /** - * Creates a new JSON Web Key (JWK) matcher. - * - * @param types The key types to match, {@code null} if not - * specified. - * @param uses The public key uses to match, {@code null} if not - * specified. - * @param ops The key operations to match, {@code null} if not - * specified. - * @param algs The JOSE algorithms to match, {@code null} if not - * specified. - * @param ids The key IDs to match, {@code null} if not - * specified. - * @param hasUse {@code true} to match a key with a set use. - * @param hasID {@code true} to match a key with a set ID. - * @param privateOnly {@code true} to match a private key. - * @param publicOnly {@code true} to match a public only key. - * @param minSizeBits The minimum key size in bits, zero implies no - * minimum size limit. - * @param maxSizeBits The maximum key size in bits, zero implies no - * maximum size limit. - * @param sizesBits The key sizes in bits, {@code null} if not - * specified. - * @param curves The curves to match (for EC and OKP keys), - * {@code null} if not specified. - */ - @Deprecated - public JWKMatcher(final Set types, - final Set uses, - final Set ops, - final Set algs, - final Set ids, - final boolean hasUse, - final boolean hasID, - final boolean privateOnly, - final boolean publicOnly, - final int minSizeBits, - final int maxSizeBits, - final Set sizesBits, - final Set curves) { - - this(types, uses, ops, algs, ids, hasUse, hasID, privateOnly, publicOnly, minSizeBits, maxSizeBits, sizesBits, curves, null); - } - - /** - * Creates a new JSON Web Key (JWK) matcher. - * - * @param types The key types to match, {@code null} if not - * specified. - * @param uses The public key uses to match, {@code null} if not - * specified. - * @param ops The key operations to match, {@code null} if not - * specified. - * @param algs The JOSE algorithms to match, {@code null} if not - * specified. - * @param ids The key IDs to match, {@code null} if not - * specified. - * @param hasUse {@code true} to match a key with a set use. - * @param hasID {@code true} to match a key with a set ID. - * @param privateOnly {@code true} to match a private key. - * @param publicOnly {@code true} to match a public only key. - * @param minSizeBits The minimum key size in bits, zero implies no - * minimum size limit. - * @param maxSizeBits The maximum key size in bits, zero implies no - * maximum size limit. - * @param sizesBits The key sizes in bits, {@code null} if not - * specified. - * @param curves The curves to match (for EC and OKP keys), - * {@code null} if not specified. - * @param x5tS256s The X.509 certificate thumbprints to match, - * {@code null} if not specified. - */ - public JWKMatcher(final Set types, - final Set uses, - final Set ops, - final Set algs, - final Set ids, - final boolean hasUse, - final boolean hasID, - final boolean privateOnly, - final boolean publicOnly, - final int minSizeBits, - final int maxSizeBits, - final Set sizesBits, - final Set curves, - final Set x5tS256s) { - - this.types = types; - this.uses = uses; - this.ops = ops; - this.algs = algs; - this.ids = ids; - this.hasUse = hasUse; - this.hasID = hasID; - this.privateOnly = privateOnly; - this.publicOnly = publicOnly; - this.minSizeBits = minSizeBits; - this.maxSizeBits = maxSizeBits; - this.sizesBits = sizesBits; - this.curves = curves; - this.x5tS256s = x5tS256s; - } - - /** - * Returns a {@link JWKMatcher} based on the given {@link JWEHeader}. - * - *

The {@link JWKMatcher} is configured as follows: - * - *

    - *
  • The key type to match is determined by the JWE algorithm - * (alg). - *
  • The key ID to match is set by the JWE header key ID (kid) - * parameter (if set). - *
  • The key uses to match are set to encryption or not - * specified. - *
  • The key algorithm to match is set to the JWE algorithm (alg) - * or not specified. - *
- * - *

Other JWE header parameters are not taken into account. - * - * @param jweHeader The header to use. - * - * @return A {@code JWKMatcher} based on the given header. - */ - public static JWKMatcher forJWEHeader(final JWEHeader jweHeader) { - - return new JWKMatcher.Builder() - .keyType(KeyType.forAlgorithm(jweHeader.getAlgorithm())) - .keyID(jweHeader.getKeyID()) - .keyUses(KeyUse.ENCRYPTION, null) - .algorithms(jweHeader.getAlgorithm(), null) - .build(); - } - - /** - * Returns a {@link JWKMatcher} based on the given {@link JWSHeader}. - * - *

The {@link JWKMatcher} is configured as follows: - * - *

    - *
  • The key type to match is determined by the JWS algorithm - * (alg). - *
  • The key ID to match is set by the JWS header key ID (kid) - * parameter (if set). - *
  • The key uses to match are set to signature or not specified. - *
  • The key algorithm to match is set to the JWS algorithm (alg) - * or not specified. - *
  • The X.509 certificate SHA-256 thumbprint to match is set to - * the x5t#S256 parameter (if set). - *
- * - *

Other JWS header parameters are not taken into account. - * - * @param jwsHeader The header to use. - * - * @return A {@code JWKMatcher} based on the given header, {@code null} - * if the JWS algorithm is not supported. - */ - public static JWKMatcher forJWSHeader(final JWSHeader jwsHeader) { - - JWSAlgorithm algorithm = jwsHeader.getAlgorithm(); - if (JWSAlgorithm.Family.RSA.contains(algorithm) || JWSAlgorithm.Family.EC.contains(algorithm)) { - // RSA or EC key matcher - return new JWKMatcher.Builder() - .keyType(KeyType.forAlgorithm(algorithm)) - .keyID(jwsHeader.getKeyID()) - .keyUses(KeyUse.SIGNATURE, null) - .algorithms(algorithm, null) - .x509CertSHA256Thumbprint(jwsHeader.getX509CertSHA256Thumbprint()) - .build(); - } else if (JWSAlgorithm.Family.HMAC_SHA.contains(algorithm)) { - // HMAC secret matcher - return new JWKMatcher.Builder() - .keyType(KeyType.forAlgorithm(algorithm)) - .keyID(jwsHeader.getKeyID()) - .privateOnly(true) - .algorithms(algorithm, null) - .build(); - } else { - return null; // Unsupported algorithm - } - } - - /** - * Returns the key types to match. - * - * @return The key types, {@code null} if not specified. - */ - public Set getKeyTypes() { - - return types; - } - - - /** - * Returns the public key uses to match. - * - * @return The public key uses, {@code null} if not specified. - */ - public Set getKeyUses() { - - return uses; - } - - - /** - * Returns the key operations to match. - * - * @return The key operations, {@code null} if not specified. - */ - public Set getKeyOperations() { - - return ops; - } - - - /** - * Returns the JOSE algorithms to match. - * - * @return The JOSE algorithms, {@code null} if not specified. - */ - public Set getAlgorithms() { - - return algs; - } - - - /** - * Returns the key IDs to match. - * - * @return The key IDs, {@code null} if not specified. - */ - public Set getKeyIDs() { - - return ids; - } - - - /** - * Returns {@code true} if keys with a set use are matched. - * - * @return {@code true} if keys with a set use are matched, else - * {@code false}. - */ - public boolean hasKeyUse() { - - return hasUse; - } - - - /** - * Returns {@code true} if keys with a set use are matched. - * - * @return {@code true} if keys with a set ID are matched, else - * {@code false}. - */ - public boolean hasKeyID() { - - return hasID; - } - - - /** - * Returns {@code true} if only private keys are matched. - * - * @return {@code true} if only private keys are matched, else - * {@code false}. - */ - public boolean isPrivateOnly() { - - return privateOnly; - } - - - /** - * Returns {@code true} if only public keys are matched. - * - * @return {@code true} if only public keys are selected, else - * {@code false}. - */ - public boolean isPublicOnly() { - - return publicOnly; - } - - - /** - * Returns the minimum key size. Use {@link #getMinKeySize()} instead. - * - * @return The minimum key size in bits, zero implies no minimum size - * limit. - */ - @Deprecated - public int getMinSize() { - - return getMinKeySize(); - } - - - /** - * Returns the minimum key size. - * - * @return The minimum key size in bits, zero implies no minimum size - * limit. - */ - public int getMinKeySize() { - - return minSizeBits; - } - - - /** - * Returns the maximum key size. Use {@link #getMaxKeySize()} instead. - * - * @return The maximum key size in bits, zero implies no maximum size - * limit. - */ - @Deprecated - public int getMaxSize() { - - return getMaxKeySize(); - } - - - /** - * Returns the maximum key size. - * - * @return The maximum key size in bits, zero implies no maximum size - * limit. - */ - public int getMaxKeySize() { - - return maxSizeBits; - } - - - /** - * Returns the key sizes. - * - * @return The key sizes in bits, {@code null} if not specified. - */ - public Set getKeySizes() { - - return sizesBits; - } - - - /** - * Returns the curves to match (for EC and OKP keys). - * - * @return The curves, {@code null} if not specified. - */ - public Set getCurves() { - - return curves; - } - - /** - * Returns the X.509 certificate SHA-256 thumbprints to match. - * - * @return The thumbprints, {@code null} if not specified. - */ - public Set getX509CertSHA256Thumbprints() { - - return x5tS256s; - } - - /** - * Returns {@code true} if the specified JWK matches. - * - * @param key The JSON Web Key (JWK). Must not be {@code null}. - * - * @return {@code true} if the JWK matches, else {@code false}. - */ - public boolean matches(final JWK key) { - - if (hasUse && key.getKeyUse() == null) - return false; - - if (hasID && (key.getKeyID() == null || key.getKeyID().trim().isEmpty())) - return false; - - if (privateOnly && ! key.isPrivate()) - return false; - - if (publicOnly && key.isPrivate()) - return false; - - if (types != null && ! types.contains(key.getKeyType())) - return false; - - if (uses != null && ! uses.contains(key.getKeyUse())) - return false; - - if (ops != null) { - - if (ops.contains(null) && key.getKeyOperations() == null) { - // pass - } else if (key.getKeyOperations() != null && ops.containsAll(key.getKeyOperations())) { - // pass - } else { - return false; - } - } - - if (algs != null && ! algs.contains(key.getAlgorithm())) - return false; - - if (ids != null && ! ids.contains(key.getKeyID())) - return false; - - if (minSizeBits > 0) { - - if (key.size() < minSizeBits) - return false; - } - - if (maxSizeBits > 0) { - - if (key.size() > maxSizeBits) - return false; - } - - if (sizesBits != null) { - if (! sizesBits.contains(key.size())) - return false; - } - - if (curves != null) { - - if (! (key instanceof CurveBasedJWK)) - return false; - - CurveBasedJWK curveBasedJWK = (CurveBasedJWK) key; - - if (! curves.contains(curveBasedJWK.getCurve())) - return false; - } - - if (x5tS256s != null) { - if (! x5tS256s.contains(key.getX509CertSHA256Thumbprint()) ) - return false; - } - - return true; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - - append(sb, "kty", types); - append(sb, "use", uses); - append(sb, "key_ops", ops); - append(sb, "alg", algs); - append(sb, "kid", ids); - - if (hasUse) { - sb.append("has_use=true "); - } - - if (hasID) { - sb.append("has_id=true "); - } - - if (privateOnly) { - sb.append("private_only=true "); - } - - if (publicOnly) { - sb.append("public_only=true "); - } - - if (minSizeBits > 0) { - sb.append("min_size=" + minSizeBits + " "); - } - - if (maxSizeBits > 0) { - sb.append("max_size=" + maxSizeBits + " "); - } - - append(sb, "size", sizesBits); - append(sb, "crv", curves); - append(sb, "x5t#S256", x5tS256s); - - return sb.toString().trim(); - } - - - /** - * Appends the specified JWK matcher parameter to a string builder. - * - * @param sb The string builder. Must not be {@code null}. - * @param key The parameter key. Must not be {@code null}. - * @param values The parameter value, {@code null} if not specified. - */ - private static void append(final StringBuilder sb, final String key, final Set values) { - - if (values != null) { - - sb.append(key); - sb.append('='); - if (values.size() == 1) { - Object value = values.iterator().next(); - if (value == null) { - sb.append("ANY"); - } else { - sb.append(value.toString().trim()); - } - } else { - sb.append(values.toString().trim()); - } - - sb.append(' '); - } - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/JWKMetadata.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/JWKMetadata.java deleted file mode 100644 index 3b06328c5..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/JWKMetadata.java +++ /dev/null @@ -1,229 +0,0 @@ -/* - * 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.jwk; - - -import java.net.URI; -import java.text.ParseException; -import java.util.List; -import java.util.Set; - -import com.nimbusds.jose.Algorithm; -import com.nimbusds.jose.util.Base64; -import com.nimbusds.jose.util.Base64URL; -import com.nimbusds.jose.util.JSONObjectUtils; -import com.nimbusds.jose.util.X509CertChainUtils; -import net.minidev.json.JSONObject; - - -/** - * JSON Web Key (JWK) metadata. - * - * @author Vladimir Dzhuvinov - * @version 2018-02-26 - */ -final class JWKMetadata { - - - /** - * Parses the JWK type. - * - * @param o The JSON object to parse. Must not be {@code null}. - * - * @return The key type. - * - * @throws ParseException If parsing failed. - */ - static KeyType parseKeyType(final JSONObject o) - throws ParseException { - - return KeyType.parse(JSONObjectUtils.getString(o, "kty")); - } - - - /** - * Parses the optional public key use. - * - * @param o The JSON object to parse. Must not be {@code null}. - * - * @return The key use, {@code null} if not specified or if the key is - * intended for signing as well as encryption. - * - * @throws ParseException If parsing failed. - */ - static KeyUse parseKeyUse(final JSONObject o) - throws ParseException { - - if (o.containsKey("use")) { - return KeyUse.parse(JSONObjectUtils.getString(o, "use")); - } else { - return null; - } - } - - - /** - * Parses the optional key operations. - * - * @param o The JSON object to parse. Must not be {@code null}. - * - * @return The key operations, {@code null} if not specified. - * - * @throws ParseException If parsing failed. - */ - static Set parseKeyOperations(final JSONObject o) - throws ParseException { - - if(o.containsKey("key_ops")) { - return KeyOperation.parse(JSONObjectUtils.getStringList(o, "key_ops")); - } else { - return null; - } - } - - - /** - * Parses the optional algorithm. - * - * @param o The JSON object to parse. Must not be {@code null}. - * - * @return The intended JOSE algorithm, {@code null} if not specified. - * - * @throws ParseException If parsing failed. - */ - static Algorithm parseAlgorithm(final JSONObject o) - throws ParseException { - - if (o.containsKey("alg")) { - return new Algorithm(JSONObjectUtils.getString(o, "alg")); - } else { - return null; - } - } - - - /** - * Parses the optional key ID. - * - * @param o The JSON object to parse. Must not be {@code null}. - * - * @return The key ID, {@code null} if not specified. - * - * @throws ParseException If parsing failed. - */ - static String parseKeyID(final JSONObject o) - throws ParseException { - - if (o.containsKey("kid")) { - return JSONObjectUtils.getString(o, "kid"); - } else { - return null; - } - } - - - /** - * Parses the optional X.509 certificate URL. - * - * @param o The JSON object to parse. Must not be {@code null}. - * - * @return The X.509 certificate URL, {@code null} if not specified. - * - * @throws ParseException If parsing failed. - */ - static URI parseX509CertURL(final JSONObject o) - throws ParseException { - - if (o.containsKey("x5u")) { - return JSONObjectUtils.getURI(o, "x5u"); - } else { - return null; - } - } - - - /** - * Parses the optional X.509 certificate thumbprint. - * - * @param o The JSON object to parse. Must not be {@code null}. - * - * @return The X.509 certificate thumbprint, {@code null} if not - * specified. - * - * @throws ParseException If parsing failed. - */ - static Base64URL parseX509CertThumbprint(final JSONObject o) - throws ParseException { - - if (o.containsKey("x5t")) { - return new Base64URL(JSONObjectUtils.getString(o, "x5t")); - } else { - return null; - } - } - - - /** - * Parses the optional X.509 certificate SHA-256 thumbprint. - * - * @param o The JSON object to parse. Must not be {@code null}. - * - * @return The X.509 certificate SHA-256 thumbprint, {@code null} if - * not specified. - * - * @throws ParseException If parsing failed. - */ - static Base64URL parseX509CertSHA256Thumbprint(final JSONObject o) - throws ParseException { - - if (o.containsKey("x5t#S256")) { - return new Base64URL(JSONObjectUtils.getString(o, "x5t#S256")); - } else { - return null; - } - } - - - /** - * Parses the optional X.509 certificate chain. - * - * @param o The JSON object to parse. Must not be {@code null}. - * - * @return The X.509 certificate chain (containing at least one - * certificate) as a unmodifiable list, {@code null} if not - * specified. - * - * @throws ParseException If parsing failed. - */ - static List parseX509CertChain(final JSONObject o) - throws ParseException { - - if (o.containsKey("x5c")) { - List chain = X509CertChainUtils.toBase64List(JSONObjectUtils.getJSONArray(o, "x5c")); - - if (chain.isEmpty()) { - throw new ParseException("The X.509 certificate chain \"x5c\" must not be empty", 0); - } - - return chain; - - } else { - return null; - } - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/JWKSelector.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/JWKSelector.java deleted file mode 100644 index 4582b50e2..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/JWKSelector.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * 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.jwk; - - -import java.util.*; - -import net.jcip.annotations.Immutable; - - -/** - * Selects (filters) one or more JSON Web Keys (JWKs) from a JWK set. - * - * @author Vladimir Dzhuvinov - * @version 2015-04-15 - */ -@Immutable -public final class JWKSelector { - - - /** - * The JWK matcher. - */ - private final JWKMatcher matcher; - - - /** - * Creates a new JWK selector (filter). - * - * @param matcher Specifies the JWK matching criteria. Must not be - * {@code null}. - */ - public JWKSelector(final JWKMatcher matcher) { - - if (matcher == null) { - throw new IllegalArgumentException("The JWK matcher must not be null"); - } - - this.matcher = matcher; - } - - - /** - * Returns the JWK matcher. - * - * @return The JWK matcher. - */ - public JWKMatcher getMatcher() { - - return matcher; - } - - - /** - * Selects the keys from the specified JWK set according to the - * matcher's criteria. - * - * @param jwkSet The JWK set. May be {@code null}. - * - * @return The selected keys, ordered by their position in the JWK set, - * empty list if none were matched or the JWK is {@code null}. - */ - public List select(final JWKSet jwkSet) { - - List selectedKeys = new LinkedList<>(); - - if (jwkSet == null) - return selectedKeys; - - for (JWK key: jwkSet.getKeys()) { - - if (matcher.matches(key)) { - selectedKeys.add(key); - } - } - - return selectedKeys; - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/JWKSet.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/JWKSet.java deleted file mode 100644 index ada6a00d9..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/JWKSet.java +++ /dev/null @@ -1,534 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2018, 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.jwk; - - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.nio.charset.Charset; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.cert.Certificate; -import java.security.interfaces.ECPublicKey; -import java.security.interfaces.RSAPublicKey; -import java.text.ParseException; -import java.util.*; - -import com.nimbusds.jose.JOSEException; -import com.nimbusds.jose.util.*; -import net.jcip.annotations.Immutable; -import net.minidev.json.JSONArray; -import net.minidev.json.JSONObject; - - -/** - * JSON Web Key (JWK) set. Represented by a JSON object that contains an array - * of {@link JWK JSON Web Keys} (JWKs) as the value of its "keys" member. - * Additional (custom) members of the JWK Set JSON object are also supported. - * - *

Example JSON Web Key (JWK) set: - * - *

- * {
- *   "keys" : [ { "kty" : "EC",
- *                "crv" : "P-256",
- *                "x"   : "MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4",
- *                "y"   : "4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM",
- *                "use" : "enc",
- *                "kid" : "1" },
- *
- *              { "kty" : "RSA",
- *                "n"   : "0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx
- *                         4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMs
- *                         tn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2
- *                         QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbI
- *                         SD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqb
- *                         w0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw",
- *                "e"   : "AQAB",
- *                "alg" : "RS256",
- *                "kid" : "2011-04-29" } ]
- * }
- * 
- * - * @author Vladimir Dzhuvinov - * @author Vedran Pavic - * @version 2018-04-26 - */ -@Immutable -public class JWKSet { - - - /** - * The MIME type of JWK set objects: - * {@code application/jwk-set+json; charset=UTF-8} - */ - public static final String MIME_TYPE = "application/jwk-set+json; charset=UTF-8"; - - - /** - * The JWK list. - */ - private final List keys; - - - /** - * Additional custom members. - */ - private final Map customMembers; - - - /** - * Creates a new empty JSON Web Key (JWK) set. - */ - public JWKSet() { - - this(Collections.emptyList()); - } - - - /** - * Creates a new JSON Web Key (JWK) set with a single key. - * - * @param key The JWK. Must not be {@code null}. - */ - public JWKSet(final JWK key) { - - this(Collections.singletonList(key)); - - if (key == null) { - throw new IllegalArgumentException("The JWK must not be null"); - } - } - - - /** - * Creates a new JSON Web Key (JWK) set with the specified keys. - * - * @param keys The JWK list. Must not be {@code null}. - */ - public JWKSet(final List keys) { - - this(keys, Collections.emptyMap()); - } - - - /** - * Creates a new JSON Web Key (JWK) set with the specified keys and - * additional custom members. - * - * @param keys The JWK list. Must not be {@code null}. - * @param customMembers The additional custom members. Must not be - * {@code null}. - */ - public JWKSet(final List keys, final Map customMembers) { - - if (keys == null) { - throw new IllegalArgumentException("The JWK list must not be null"); - } - - this.keys = Collections.unmodifiableList(keys); - - this.customMembers = Collections.unmodifiableMap(customMembers); - } - - - /** - * Gets the keys (ordered) of this JSON Web Key (JWK) set. - * - * @return The keys, empty list if none. - */ - public List getKeys() { - - return keys; - } - - - /** - * Gets the key from this JSON Web Key (JWK) set as identified by its - * Key ID (kid) member. - * - *

If more than one key exists in the JWK Set with the same - * identifier, this function returns only the first one in the set. - * - * @param kid They key identifier. - * - * @return The key identified by {@code kid} or {@code null} if no key - * exists. - */ - public JWK getKeyByKeyId(String kid) { - - for (JWK key : getKeys()) { - - if (key.getKeyID() != null && key.getKeyID().equals(kid)) { - return key; - } - } - - // no key found - return null; - } - - - /** - * Gets the additional custom members of this JSON Web Key (JWK) set. - * - * @return The additional custom members, empty map if none. - */ - public Map getAdditionalMembers() { - - return customMembers; - } - - - /** - * Returns a copy of this JSON Web Key (JWK) set with all private keys - * and parameters removed. - * - * @return A copy of this JWK set with all private keys and parameters - * removed. - */ - public JWKSet toPublicJWKSet() { - - List publicKeyList = new LinkedList<>(); - - for (JWK key: keys) { - - JWK publicKey = key.toPublicJWK(); - - if (publicKey != null) { - publicKeyList.add(publicKey); - } - } - - return new JWKSet(publicKeyList, customMembers); - } - - - /** - * Returns the JSON object representation of this JSON Web Key (JWK) - * set. Private keys and parameters will be omitted from the output. - * Use the alternative {@link #toJSONObject(boolean)} method if you - * wish to include them. - * - * @return The JSON object representation. - */ - public JSONObject toJSONObject() { - - return toJSONObject(true); - } - - - /** - * Returns the JSON object representation of this JSON Web Key (JWK) - * set. - * - * @param publicKeysOnly Controls the inclusion of private keys and - * parameters into the output JWK members. If - * {@code true} private keys and parameters will - * be omitted. If {@code false} all available key - * parameters will be included. - * - * @return The JSON object representation. - */ - public JSONObject toJSONObject(final boolean publicKeysOnly) { - - JSONObject o = new JSONObject(customMembers); - - JSONArray a = new JSONArray(); - - for (JWK key: keys) { - - if (publicKeysOnly) { - - // Try to get public key, then serialise - JWK publicKey = key.toPublicJWK(); - - if (publicKey != null) { - a.add(publicKey.toJSONObject()); - } - } else { - - a.add(key.toJSONObject()); - } - } - - o.put("keys", a); - - return o; - } - - - /** - * Returns the JSON object string representation of this JSON Web Key - * (JWK) set. - * - * @return The JSON object string representation. - */ - @Override - public String toString() { - - return toJSONObject().toString(); - } - - - /** - * Parses the specified string representing a JSON Web Key (JWK) set. - * - * @param s The string to parse. Must not be {@code null}. - * - * @return The JWK set. - * - * @throws ParseException If the string couldn't be parsed to a valid - * JSON Web Key (JWK) set. - */ - public static JWKSet parse(final String s) - throws ParseException { - - return parse(JSONObjectUtils.parse(s)); - } - - - /** - * Parses the specified JSON object representing a JSON Web Key (JWK) - * set. - * - * @param json The JSON object to parse. Must not be {@code null}. - * - * @return The JWK set. - * - * @throws ParseException If the string couldn't be parsed to a valid - * JSON Web Key (JWK) set. - */ - public static JWKSet parse(final JSONObject json) - throws ParseException { - - JSONArray keyArray = JSONObjectUtils.getJSONArray(json, "keys"); - - if (keyArray == null) { - throw new ParseException("Missing required \"keys\" member", 0); - } - - List keys = new LinkedList<>(); - - for (int i=0; i < keyArray.size(); i++) { - - if (! (keyArray.get(i) instanceof JSONObject)) { - throw new ParseException("The \"keys\" JSON array must contain JSON objects only", 0); - } - - JSONObject keyJSON = (JSONObject)keyArray.get(i); - - try { - keys.add(JWK.parse(keyJSON)); - - } catch (ParseException e) { - - throw new ParseException("Invalid JWK at position " + i + ": " + e.getMessage(), 0); - } - } - - // Parse additional custom members - Map additionalMembers = new HashMap<>(); - for (Map.Entry entry: json.entrySet()) { - - if (entry.getKey() == null || entry.getKey().equals("keys")) { - continue; - } - - additionalMembers.put(entry.getKey(), entry.getValue()); - } - - return new JWKSet(keys, additionalMembers); - } - - - /** - * Loads a JSON Web Key (JWK) set from the specified input stream. - * - * @param inputStream The JWK set input stream. Must not be {@code null}. - * - * @return The JWK set. - * - * @throws IOException If the input stream couldn't be read. - * @throws ParseException If the input stream couldn't be parsed to a valid - * JSON Web Key (JWK) set. - */ - public static JWKSet load(final InputStream inputStream) - throws IOException, ParseException { - - return parse(IOUtils.readInputStreamToString(inputStream, Charset.forName("UTF-8"))); - } - - - /** - * Loads a JSON Web Key (JWK) set from the specified file. - * - * @param file The JWK set file. Must not be {@code null}. - * - * @return The JWK set. - * - * @throws IOException If the file couldn't be read. - * @throws ParseException If the file couldn't be parsed to a valid - * JSON Web Key (JWK) set. - */ - public static JWKSet load(final File file) - throws IOException, ParseException { - - return parse(IOUtils.readFileToString(file, Charset.forName("UTF-8"))); - } - - - /** - * Loads a JSON Web Key (JWK) set from the specified URL. - * - * @param url The JWK set URL. Must not be {@code null}. - * @param connectTimeout The URL connection timeout, in milliseconds. - * If zero no (infinite) timeout. - * @param readTimeout The URL read timeout, in milliseconds. If zero - * no (infinite) timeout. - * @param sizeLimit The read size limit, in bytes. If zero no - * limit. - * - * @return The JWK set. - * - * @throws IOException If the file couldn't be read. - * @throws ParseException If the file couldn't be parsed to a valid - * JSON Web Key (JWK) set. - */ - public static JWKSet load(final URL url, - final int connectTimeout, - final int readTimeout, - final int sizeLimit) - throws IOException, ParseException { - - RestrictedResourceRetriever resourceRetriever = new DefaultResourceRetriever( - connectTimeout, - readTimeout, - sizeLimit); - Resource resource = resourceRetriever.retrieveResource(url); - return parse(resource.getContent()); - } - - - /** - * Loads a JSON Web Key (JWK) set from the specified URL. - * - * @param url The JWK set URL. Must not be {@code null}. - * - * @return The JWK set. - * - * @throws IOException If the file couldn't be read. - * @throws ParseException If the file couldn't be parsed to a valid - * JSON Web Key (JWK) set. - */ - public static JWKSet load(final URL url) - throws IOException, ParseException { - - return load(url, 0, 0, 0); - } - - - /** - * Loads a JSON Web Key (JWK) set from the specified JCA key store. Key - * conversion exceptions are silently swallowed. PKCS#11 stores are - * also supported. Requires BouncyCastle. - * - *

Important: The X.509 certificates are not - * validated! - * - * @param keyStore The key store. Must not be {@code null}. - * @param pwLookup The password lookup for password-protected keys, - * {@code null} if not specified. - * - * @return The JWK set, empty if no keys were loaded. - * - * @throws KeyStoreException On a key store exception. - */ - public static JWKSet load(final KeyStore keyStore, final PasswordLookup pwLookup) - throws KeyStoreException { - - List jwks = new LinkedList<>(); - - // Load RSA and EC keys - for (Enumeration keyAliases = keyStore.aliases(); keyAliases.hasMoreElements(); ) { - - final String keyAlias = keyAliases.nextElement(); - final char[] keyPassword = pwLookup == null ? "".toCharArray() : pwLookup.lookupPassword(keyAlias); - - Certificate cert = keyStore.getCertificate(keyAlias); - if (cert == null) { - continue; // skip - } - - if (cert.getPublicKey() instanceof RSAPublicKey) { - - RSAKey rsaJWK; - try { - rsaJWK = RSAKey.load(keyStore, keyAlias, keyPassword); - } catch (JOSEException e) { - continue; // skip cert - } - - if (rsaJWK == null) { - continue; // skip key - } - - jwks.add(rsaJWK); - - } else if (cert.getPublicKey() instanceof ECPublicKey) { - - ECKey ecJWK; - try { - ecJWK = ECKey.load(keyStore, keyAlias, keyPassword); - } catch (JOSEException e) { - continue; // skip cert - } - - if (ecJWK != null) { - jwks.add(ecJWK); - } - - } else { - continue; - } - } - - - // Load symmetric keys - for (Enumeration keyAliases = keyStore.aliases(); keyAliases.hasMoreElements(); ) { - - final String keyAlias = keyAliases.nextElement(); - final char[] keyPassword = pwLookup == null ? "".toCharArray() : pwLookup.lookupPassword(keyAlias); - - OctetSequenceKey octJWK; - try { - octJWK = OctetSequenceKey.load(keyStore, keyAlias, keyPassword); - } catch (JOSEException e) { - continue; // skip key - } - - if (octJWK != null) { - jwks.add(octJWK); - } - } - - return new JWKSet(jwks); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/KeyConverter.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/KeyConverter.java deleted file mode 100644 index b92165706..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/KeyConverter.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * 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.jwk; - - -import java.security.Key; -import java.security.KeyPair; -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; - -import com.nimbusds.jose.JOSEException; - - -/** - * Key converter. - */ -public class KeyConverter { - - - /** - * Converts the specified list of JSON Web Keys (JWK) their standard - * Java class representation. Asymmetric {@link RSAKey RSA} and - * {@link ECKey EC key} pairs are converted to - * {@link java.security.PublicKey} and {@link java.security.PrivateKey} - * (if specified) objects. {@link OctetSequenceKey secret JWKs} are - * converted to {@link javax.crypto.SecretKey} objects. Key conversion - * exceptions are silently ignored. - * - * @param jwkList The JWK list. May be {@code null}. - * - * @return The converted keys, empty set if none or {@code null}. - */ - public static List toJavaKeys(final List jwkList) { - - if (jwkList == null) { - return Collections.emptyList(); - } - - List out = new LinkedList<>(); - for (JWK jwk: jwkList) { - try { - if (jwk instanceof AsymmetricJWK) { - KeyPair keyPair = ((AsymmetricJWK)jwk).toKeyPair(); - out.add(keyPair.getPublic()); // add public - if (keyPair.getPrivate() != null) { - out.add(keyPair.getPrivate()); // add private if present - } - } else if (jwk instanceof SecretJWK) { - out.add(((SecretJWK)jwk).toSecretKey()); - } - } catch (JOSEException e) { - // ignore and continue - } - } - return out; - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/KeyOperation.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/KeyOperation.java deleted file mode 100644 index d8170e651..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/KeyOperation.java +++ /dev/null @@ -1,187 +0,0 @@ -/* - * 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.jwk; - - -import java.text.ParseException; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Set; - - -/** - * Enumeration of key operations. Represents the {@code key_ops} parameter in a - * JSON Web Key (JWK). - * - *

JWK operation values: - * - *

    - *
  • {@link #SIGN sign} - *
  • {@link #VERIFY verify} - *
  • {@link #ENCRYPT encrypt} - *
  • {@link #DECRYPT decrypt} - *
  • {@link #WRAP_KEY wrapKey} - *
  • {@link #UNWRAP_KEY unwrapKey} - *
  • {@link #DERIVE_KEY deriveKey} - *
  • {@link #DERIVE_BITS deriveBits} - *
- * - * @author Vladimir Dzhuvinov - * @version 2014-04-02 - */ -public enum KeyOperation { - - - /** - * Compute signature or MAC. - */ - SIGN("sign"), - - - /** - * Verify signature or MAC. - */ - VERIFY("verify"), - - - /** - * Encrypt content. - */ - ENCRYPT("encrypt"), - - - /** - * Decrypt content and validate decryption, if applicable. - */ - DECRYPT("decrypt"), - - - /** - * Encrypt key. - */ - WRAP_KEY("wrapKey"), - - - /** - * Decrypt key and validate decryption, if applicable. - */ - UNWRAP_KEY("unwrapKey"), - - - /** - * Derive key. - */ - DERIVE_KEY("deriveKey"), - - - /** - * Derive bits not to be used as a key. - */ - DERIVE_BITS("deriveBits"); - - - /** - * The key operation identifier. - */ - private final String identifier; - - - /** - * Creates a new key operation with the specified identifier. - * - * @param identifier The key operation identifier. Must not be - * {@code null}. - */ - KeyOperation(final String identifier) { - - if (identifier == null) - throw new IllegalArgumentException("The key operation identifier must not be null"); - - this.identifier = identifier; - } - - - /** - * Returns the identifier of this public key use. - * - * @return The identifier. - */ - public String identifier() { - - return identifier; - } - - - /** - * @see #identifier() - */ - @Override - public String toString() { - - return identifier(); - } - - - /** - * Parses a key operation set from the specified JWK {@code key_ops} - * parameter value. - * - * @param sl The string list to parse. May be {@code null}. - * - * @return The key operation set, {@code null} if none. - * - * @throws ParseException If the string list couldn't be parsed to a - * valid key operation list. - */ - public static Set parse(final List sl) - throws ParseException { - - if (sl == null) { - return null; - } - - Set keyOps = new LinkedHashSet<>(); - - for (String s: sl) { - - if (s == null) { - // skip - continue; - } - - KeyOperation parsedOp = null; - - for (KeyOperation op: KeyOperation.values()) { - - if (s.equals(op.identifier())) { - parsedOp = op; - break; - } - } - - if (parsedOp != null) { - keyOps.add(parsedOp); - } - else { - throw new ParseException("Invalid JWK operation: " + s, 0); - } - } - - return keyOps; - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/KeyType.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/KeyType.java deleted file mode 100644 index 11240661d..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/KeyType.java +++ /dev/null @@ -1,254 +0,0 @@ -/* - * 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.jwk; - - -import java.io.Serializable; - -import com.nimbusds.jose.Algorithm; -import com.nimbusds.jose.JWEAlgorithm; -import com.nimbusds.jose.JWSAlgorithm; -import com.nimbusds.jose.Requirement; -import net.jcip.annotations.Immutable; -import net.minidev.json.JSONAware; -import net.minidev.json.JSONObject; - - -/** - * Key type. Represents the {@code kty} parameter in a JSON Web Key (JWK). - * This class is immutable. - * - *

Includes constants for the following standard key types: - * - *

    - *
  • {@link #EC} - *
  • {@link #RSA} - *
  • {@link #OCT} - *
  • {@link #OKP} - *
- * - *

Additional key types can be defined using the constructor. - * - * @author Vladimir Dzhuvinov - * @author Justin Richer - * @version 2017-08-23 - */ -@Immutable -public final class KeyType implements JSONAware, Serializable { - - - private static final long serialVersionUID = 1L; - - - /** - * The key type value. - */ - private final String value; - - - /** - * The implementation requirement, {@code null} if not known. - */ - private final Requirement requirement; - - - /** - * Elliptic Curve (DSS) key type (recommended). - */ - public static final KeyType EC = new KeyType("EC", Requirement.RECOMMENDED); - - - /** - * RSA (RFC 3447) key type (required). - */ - public static final KeyType RSA = new KeyType("RSA", Requirement.REQUIRED); - - - /** - * Octet sequence key type (optional). - */ - public static final KeyType OCT = new KeyType("oct", Requirement.OPTIONAL); - - - /** - * Octet key pair (optional). - */ - public static final KeyType OKP = new KeyType("OKP", Requirement.OPTIONAL); - - - /** - * Creates a new key type with the specified value and implementation - * requirement. - * - * @param value The key type value. Values are case sensitive. Must not - * be {@code null}. - * @param req The implementation requirement, {@code null} if not - * known. - */ - public KeyType(final String value, final Requirement req) { - - if (value == null) { - - throw new IllegalArgumentException("The key type value must not be null"); - } - - this.value = value; - - requirement = req; - } - - - /** - * Gets the value of this key type. Values are case sensitive. - * - * @return The key type. - */ - public String getValue() { - - return value; - } - - - /** - * Gets the implementation requirement of this key type. - * - * @return The implementation requirement, {@code null} if not known. - */ - public Requirement getRequirement() { - - return requirement; - } - - - /** - * Overrides {@code Object.hashCode()}. - * - * @return The object hash code. - */ - @Override - public int hashCode() { - - return value.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 KeyType && - this.toString().equals(object.toString()); - } - - - /** - * Returns the string representation of this key type. - * - * @see #getValue - * - * @return The string representation. - */ - @Override - public String toString() { - - return value; - } - - - /** - * Returns the JSON string representation of this key type. - * - * @return The JSON string representation. - */ - @Override - public String toJSONString() { - - return "\"" + JSONObject.escape(value) + '"'; - } - - - /** - * Parses a key type from the specified {@code kty} parameter value. - * - * @param s The string to parse. Must not be {@code null}. - * - * @return The key type (matching standard key type constant, else a - * newly created one). - */ - public static KeyType parse(final String s) { - - if (s.equals(EC.getValue())) { - return EC; - } else if (s.equals(RSA.getValue())) { - return RSA; - } else if (s.equals(OCT.getValue())) { - return OCT; - } else if (s.equals(OKP.getValue())) { - return OKP; - } else { - return new KeyType(s, null); - } - } - - - /** - * Infers the key type for the specified JOSE algorithm. - * - * @param alg The JOSE algorithm. May be {@code null}. - * - * @return The key type, {@code null} if it couldn't be inferred. - */ - public static KeyType forAlgorithm(final Algorithm alg) { - - if (alg == null) { - return null; - } - - if (JWSAlgorithm.Family.RSA.contains(alg)) { - return KeyType.RSA; - } else if (JWSAlgorithm.Family.EC.contains(alg)) { - return KeyType.EC; - } else if (JWSAlgorithm.Family.HMAC_SHA.contains(alg)) { - return KeyType.OCT; - } else if (JWEAlgorithm.Family.RSA.contains(alg)) { - return KeyType.RSA; - } else if (JWEAlgorithm.Family.ECDH_ES.contains(alg)) { - return KeyType.EC; - } else if (JWEAlgorithm.DIR.equals(alg)) { - return KeyType.OCT; - } else if (JWEAlgorithm.Family.AES_GCM_KW.contains(alg)) { - return KeyType.OCT; - } else if (JWEAlgorithm.Family.AES_KW.contains(alg)) { - return KeyType.OCT; - } else if (JWEAlgorithm.Family.PBES2.contains(alg)) { - return KeyType.OCT; - } else if (JWSAlgorithm.Family.ED.contains(alg)) { - return KeyType.OKP; - } else { - return null; - } - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/KeyUse.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/KeyUse.java deleted file mode 100644 index e98dce393..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/KeyUse.java +++ /dev/null @@ -1,201 +0,0 @@ -/* - * 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.jwk; - - -import java.security.cert.X509Certificate; -import java.text.ParseException; -import java.util.Objects; - - -/** - * Enumeration of public key uses. Represents the {@code use} parameter in a - * JSON Web Key (JWK). - * - *

Public JWK use values: - * - *

    - *
  • {@link #SIGNATURE sig} - *
  • {@link #ENCRYPTION enc} - *
- * - * @author Vladimir Dzhuvinov - * @version 2019-02-06 - */ -public final class KeyUse { - - - /** - * Signature. - */ - public static final KeyUse SIGNATURE = new KeyUse("sig"); - - - /** - * Encryption. - */ - public static final KeyUse ENCRYPTION = new KeyUse("enc"); - - - /** - * The public key use identifier. - */ - private final String identifier; - - - /** - * Creates a new public key use with the specified identifier. - * - * @param identifier The public key use identifier. Must not be - * {@code null}. - */ - public KeyUse(final String identifier) { - - if (identifier == null) - throw new IllegalArgumentException("The key use identifier must not be null"); - - this.identifier = identifier; - } - - - /** - * Returns the identifier of this public key use. - * - * @return The identifier. - */ - public String identifier() { - - return identifier; - } - - - /** - * @see #identifier() - */ - public String getValue() { - - return identifier(); - } - - - /** - * @see #identifier() - */ - @Override - public String toString() { - - return identifier(); - } - - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof KeyUse)) return false; - KeyUse keyUse = (KeyUse) o; - return Objects.equals(identifier, keyUse.identifier); - } - - - @Override - public int hashCode() { - return Objects.hash(identifier); - } - - - /** - * Parses a public key use from the specified JWK {@code use} parameter - * value. - * - * @param s The string to parse. May be {@code null}. - * - * @return The public key use, {@code null} if none. - * - * @throws ParseException If the string couldn't be parsed to a valid - * public key use. - */ - public static KeyUse parse(final String s) - throws ParseException { - - if (s == null) { - return null; - } - - if (s.equals(SIGNATURE.identifier())) { - return SIGNATURE; - } - - if (s.equals(ENCRYPTION.identifier())) { - return ENCRYPTION; - } - - if (s.trim().isEmpty()) { - throw new ParseException("JWK use value must not be empty or blank", 0); - } - - return new KeyUse(s); - } - - - /** - * Infers the public key use of the specified X.509 certificate. Note - * that there is no standard algorithm for mapping PKIX key usage to - * JWK use. See RFC 2459, section 4.2.1.3, as well as the underlying - * code for the chosen algorithm to infer JWK use. - * - * @param cert The X.509 certificate. Must not be {@code null}. - * - * @return The public key use, {@code null} if the key use couldn't be - * reliably determined. - */ - public static KeyUse from(final X509Certificate cert) { - - if (cert.getKeyUsage() == null) { - return null; - } - - // nonRepudiation - if (cert.getKeyUsage()[1]) { - return SIGNATURE; - } - - // digitalSignature && keyEncipherment - // (e.g. RSA TLS certificate for authenticated encryption) - if (cert.getKeyUsage()[0] && cert.getKeyUsage()[2]) { - return KeyUse.ENCRYPTION; - } - - // digitalSignature && keyAgreement - // (e.g. EC TLS certificate for authenticated encryption) - if (cert.getKeyUsage()[0] && cert.getKeyUsage()[4]) { - return KeyUse.ENCRYPTION; - } - - // keyEncipherment || dataEncipherment || keyAgreement - if (cert.getKeyUsage()[2] || cert.getKeyUsage()[3] || cert.getKeyUsage()[4]) { - return ENCRYPTION; - } - - // keyCertSign || cRLSign - if (cert.getKeyUsage()[5] || cert.getKeyUsage()[6]) { - return SIGNATURE; - } - - return null; - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/KeyUseAndOpsConsistency.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/KeyUseAndOpsConsistency.java deleted file mode 100644 index 7558c4e9a..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/KeyUseAndOpsConsistency.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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.jwk; - - -import java.util.*; - - -/** - * JWK {@code use} and {@code key_ops} consistency rules. - * - *

See https://tools.ietf.org/html/rfc7517#section-4.3 - * - * @author Vladimir Dzhuvinov - * @version 2017-06-20 - */ -class KeyUseAndOpsConsistency { - - - /** - * Defines the consistent key use / key operations mappings. - */ - static Map> MAP; - - - static { - Map> map = new HashMap<>(); - map.put( - KeyUse.SIGNATURE, - new HashSet<>(Arrays.asList( - KeyOperation.SIGN, - KeyOperation.VERIFY))); - map.put( - KeyUse.ENCRYPTION, - new HashSet<>(Arrays.asList( - KeyOperation.ENCRYPT, - KeyOperation.DECRYPT, - KeyOperation.WRAP_KEY, - KeyOperation.UNWRAP_KEY - ))); - MAP = Collections.unmodifiableMap(map); - } - - - /** - * Checks if the specified key use and key operations are consistent. - * - * @param use The key use. May be {@code null}. - * @param ops The key operations. May be {@code null}. - * - * @return {@code true} if consistent, else {@code false}. - */ - static boolean areConsistent(final KeyUse use, final Set ops) { - - if (use == null || ops == null) { - return true; - } - - return MAP.get(use).containsAll(ops); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/OctetKeyPair.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/OctetKeyPair.java deleted file mode 100644 index 3f03db2f6..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/OctetKeyPair.java +++ /dev/null @@ -1,867 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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.jwk; - - -import java.net.URI; -import java.security.KeyPair; -import java.security.KeyStore; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.cert.X509Certificate; -import java.text.ParseException; -import java.util.*; - -import net.jcip.annotations.Immutable; -import net.minidev.json.JSONObject; - -import com.nimbusds.jose.Algorithm; -import com.nimbusds.jose.JOSEException; -import com.nimbusds.jose.util.Base64; -import com.nimbusds.jose.util.Base64URL; -import com.nimbusds.jose.util.ByteUtils; -import com.nimbusds.jose.util.JSONObjectUtils; - - -/** - * {@link KeyType#OKP Octet key pair} JSON Web Key (JWK), used to represent - * Edwards-curve keys. This class is immutable. - * - *

Supported curves: - * - *

    - *
  • {@link Curve#Ed25519 Ed25519} - *
  • {@link Curve#Ed448 Ed448} - *
  • {@link Curve#X25519 X25519} - *
  • {@link Curve#X448 X448} - *
- * - *

Example JSON object representation of a public OKP JWK: - * - *

- * {
- *   "kty" : "OKP",
- *   "crv" : "Ed25519",
- *   "x"   : "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo",
- *   "use" : "sig",
- *   "kid" : "1"
- * }
- * 
- * - *

Example JSON object representation of a private OKP JWK: - * - *

- * {
- *   "kty" : "OKP",
- *   "crv" : "Ed25519",
- *   "x"   : "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo",
- *   "d"   : "nWGxne_9WmC6hEr0kuwsxERJxWl7MmkZcDusAxyuf2A",
- *   "use" : "sig",
- *   "kid" : "1"
- * }
- * 
- * - *

Use the builder to create a new OKP JWK: - * - *

- * OctetKeyPair key = new OctetKeyPair.Builder(Curve.Ed25519, x)
- * 	.keyUse(KeyUse.SIGNATURE)
- * 	.keyID("1")
- * 	.build();
- * 
- * - * @author Vladimir Dzhuvinov - * @version 2019-04-15 - */ -@Immutable -public class OctetKeyPair extends JWK implements AsymmetricJWK, CurveBasedJWK { - - - private static final long serialVersionUID = 1L; - - - /** - * Supported Edwards curves. - */ - public static final Set SUPPORTED_CURVES = Collections.unmodifiableSet( - new HashSet<>(Arrays.asList(Curve.Ed25519, Curve.Ed448, Curve.X25519, Curve.X448)) - ); - - - /** - * Builder for constructing Octet Key Pair JWKs. - * - *

Example usage: - * - *

-	 * OctetKeyPair key = new OctetKeyPair.Builder(Curve.Ed25519, x)
-	 *     .d(d)
-	 *     .algorithm(JWSAlgorithm.EdDSA)
-	 *     .keyID("1")
-	 *     .build();
-	 * 
- */ - public static class Builder { - - - /** - * The curve name. - */ - private final Curve crv; - - - /** - * The public 'x' parameter. - */ - private final Base64URL x; - - - /** - * The private 'd' parameter, optional. - */ - private Base64URL d; - - - /** - * The key use, optional. - */ - private KeyUse use; - - - /** - * The key operations, optional. - */ - private Set ops; - - - /** - * The intended JOSE algorithm for the key, optional. - */ - private Algorithm alg; - - - /** - * The key ID, optional. - */ - private String kid; - - - /** - * X.509 certificate URL, optional. - */ - private URI x5u; - - - /** - * X.509 certificate SHA-1 thumbprint, optional. - */ - @Deprecated - private Base64URL x5t; - - - /** - * X.509 certificate SHA-256 thumbprint, optional. - */ - private Base64URL x5t256; - - - /** - * The X.509 certificate chain, optional. - */ - private List x5c; - - - /** - * Reference to the underlying key store, {@code null} if none. - */ - private KeyStore ks; - - - /** - * Creates a new Octet Key Pair JWK builder. - * - * @param crv The cryptographic curve. Must not be - * {@code null}. - * @param x The public 'x' parameter. Must not be - * {@code null}. - */ - public Builder(final Curve crv, final Base64URL x) { - - if (crv == null) { - throw new IllegalArgumentException("The curve must not be null"); - } - - this.crv = crv; - - if (x == null) { - throw new IllegalArgumentException("The 'x' coordinate must not be null"); - } - - this.x = x; - } - - - /** - * Creates a new Octet Key Pair JWK builder. - * - * @param okpJWK The Octet Key Pair to start with. Must not be - * {@code null}. - */ - public Builder(final OctetKeyPair okpJWK) { - - crv = okpJWK.crv; - x = okpJWK.x; - d = okpJWK.d; - use = okpJWK.getKeyUse(); - ops = okpJWK.getKeyOperations(); - alg = okpJWK.getAlgorithm(); - kid = okpJWK.getKeyID(); - x5u = okpJWK.getX509CertURL(); - x5t = okpJWK.getX509CertThumbprint(); - x5t256 = okpJWK.getX509CertSHA256Thumbprint(); - x5c = okpJWK.getX509CertChain(); - ks = okpJWK.getKeyStore(); - } - - - /** - * Sets the private 'd' parameter. - * - * @param d The private 'd' parameter, {@code null} if not - * specified (for a public key). - * - * @return This builder. - */ - public OctetKeyPair.Builder d(final Base64URL d) { - - this.d = d; - return this; - } - - - /** - * Sets the use ({@code use}) of the JWK. - * - * @param use The key use, {@code null} if not specified or if - * the key is intended for signing as well as - * encryption. - * - * @return This builder. - */ - public OctetKeyPair.Builder keyUse(final KeyUse use) { - - this.use = use; - return this; - } - - - /** - * Sets the operations ({@code key_ops}) of the JWK. - * - * @param ops The key operations, {@code null} if not - * specified. - * - * @return This builder. - */ - public OctetKeyPair.Builder keyOperations(final Set ops) { - - this.ops = ops; - return this; - } - - - /** - * Sets the intended JOSE algorithm ({@code alg}) for the JWK. - * - * @param alg The intended JOSE algorithm, {@code null} if not - * specified. - * - * @return This builder. - */ - public OctetKeyPair.Builder algorithm(final Algorithm alg) { - - this.alg = alg; - return this; - } - - /** - * Sets the ID ({@code kid}) of the JWK. The key ID can be used - * to match a specific key. This can be used, for instance, to - * choose a key within a {@link JWKSet} during key rollover. - * The key ID may also correspond to a JWS/JWE {@code kid} - * header parameter value. - * - * @param kid The key ID, {@code null} if not specified. - * - * @return This builder. - */ - public OctetKeyPair.Builder keyID(final String kid) { - - this.kid = kid; - return this; - } - - - /** - * Sets the ID ({@code kid}) of the JWK to its SHA-256 JWK - * thumbprint (RFC 7638). The key ID can be used to match a - * specific key. This can be used, for instance, to choose a - * key within a {@link JWKSet} during key rollover. The key ID - * may also correspond to a JWS/JWE {@code kid} header - * parameter value. - * - * @return This builder. - * - * @throws JOSEException If the SHA-256 hash algorithm is not - * supported. - */ - public OctetKeyPair.Builder keyIDFromThumbprint() - throws JOSEException { - - return keyIDFromThumbprint("SHA-256"); - } - - - /** - * Sets the ID ({@code kid}) of the JWK to its JWK thumbprint - * (RFC 7638). The key ID can be used to match a specific key. - * This can be used, for instance, to choose a key within a - * {@link JWKSet} during key rollover. The key ID may also - * correspond to a JWS/JWE {@code kid} header parameter value. - * - * @param hashAlg The hash algorithm for the JWK thumbprint - * computation. Must not be {@code null}. - * - * @return This builder. - * - * @throws JOSEException If the hash algorithm is not - * supported. - */ - public OctetKeyPair.Builder keyIDFromThumbprint(final String hashAlg) - throws JOSEException { - - // Put mandatory params in sorted order - LinkedHashMap requiredParams = new LinkedHashMap<>(); - requiredParams.put("crv", crv.toString()); - requiredParams.put("kty", KeyType.OKP.getValue()); - requiredParams.put("x", x.toString()); - this.kid = ThumbprintUtils.compute(hashAlg, requiredParams).toString(); - return this; - } - - - /** - * Sets the X.509 certificate URL ({@code x5u}) of the JWK. - * - * @param x5u The X.509 certificate URL, {@code null} if not - * specified. - * - * @return This builder. - */ - public OctetKeyPair.Builder x509CertURL(final URI x5u) { - - this.x5u = x5u; - return this; - } - - - /** - * Sets the X.509 certificate SHA-1 thumbprint ({@code x5t}) of - * the JWK. - * - * @param x5t The X.509 certificate SHA-1 thumbprint, - * {@code null} if not specified. - * - * @return This builder. - */ - @Deprecated - public OctetKeyPair.Builder x509CertThumbprint(final Base64URL x5t) { - - this.x5t = x5t; - return this; - } - - - /** - * Sets the X.509 certificate SHA-256 thumbprint - * ({@code x5t#S256}) of the JWK. - * - * @param x5t256 The X.509 certificate SHA-256 thumbprint, - * {@code null} if not specified. - * - * @return This builder. - */ - public OctetKeyPair.Builder x509CertSHA256Thumbprint(final Base64URL x5t256) { - - this.x5t256 = x5t256; - return this; - } - - - /** - * Sets the X.509 certificate chain ({@code x5c}) of the JWK. - * - * @param x5c The X.509 certificate chain as a unmodifiable - * list, {@code null} if not specified. - * - * @return This builder. - */ - public OctetKeyPair.Builder x509CertChain(final List x5c) { - - this.x5c = x5c; - return this; - } - - - /** - * Sets the underlying key store. - * - * @param keyStore Reference to the underlying key store, - * {@code null} if none. - * - * @return This builder. - */ - public OctetKeyPair.Builder keyStore(final KeyStore keyStore) { - - this.ks = keyStore; - return this; - } - - - /** - * Builds a new Octet Key Pair JWK. - * - * @return The Octet Key Pair JWK. - * - * @throws IllegalStateException If the JWK parameters were - * inconsistently specified. - */ - public OctetKeyPair build() { - - try { - if (d == null) { - // Public key - return new OctetKeyPair(crv, x, use, ops, alg, kid, x5u, x5t, x5t256, x5c, ks); - } - - // Public / private key pair with 'd' - return new OctetKeyPair(crv, x, d, use, ops, alg, kid, x5u, x5t, x5t256, x5c, ks); - - } catch (IllegalArgumentException e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - } - - - /** - * The curve name. - */ - private final Curve crv; - - - /** - * The public 'x' parameter. - */ - private final Base64URL x; - - - /** - * The public 'x' parameter, decoded from Base64. - * Cached for performance and to reduce the risk of side channel attacks - * against the Base64 decoding procedure. - */ - private final byte[] decodedX; - - - /** - * The private 'd' parameter. - */ - private final Base64URL d; - - - /** - * The private 'd' parameter, decoded from Base64. - * Cached for performance and to reduce the risk of side channel attacks - * against the Base64 decoding procedure. - */ - private final byte[] decodedD; - - - /** - * Creates a new public Octet Key Pair JSON Web Key (JWK) with the - * specified parameters. - * - * @param crv The cryptographic curve. Must not be {@code null}. - * @param x The public 'x' parameter. Must not be {@code null}. - * @param use The key use, {@code null} if not specified or if the - * key is intended for signing as well as encryption. - * @param ops The key operations, {@code null} if not specified. - * @param alg The intended JOSE algorithm for the key, {@code null} - * if not specified. - * @param kid The key ID, {@code null} if not specified. - * @param x5u The X.509 certificate URL, {@code null} if not - * specified. - * @param x5t The X.509 certificate SHA-1 thumbprint, {@code null} - * if not specified. - * @param x5t256 The X.509 certificate SHA-256 thumbprint, {@code null} - * if not specified. - * @param x5c The X.509 certificate chain, {@code null} if not - * specified. - * @param ks Reference to the underlying key store, {@code null} if - * not specified. - */ - public OctetKeyPair(final Curve crv, final Base64URL x, - final KeyUse use, final Set ops, final Algorithm alg, final String kid, - final URI x5u, final Base64URL x5t, final Base64URL x5t256, final List x5c, - final KeyStore ks) { - - super(KeyType.OKP, use, ops, alg, kid, x5u, x5t, x5t256, x5c, ks); - - if (crv == null) { - throw new IllegalArgumentException("The curve must not be null"); - } - - if (! SUPPORTED_CURVES.contains(crv)) { - throw new IllegalArgumentException("Unknown / unsupported curve: " + crv); - } - - this.crv = crv; - - if (x == null) { - throw new IllegalArgumentException("The 'x' parameter must not be null"); - } - - this.x = x; - decodedX = x.decode(); - - d = null; - decodedD = null; - } - - - /** - * Creates a new public / private Octet Key Pair JSON Web Key (JWK) - * with the specified parameters. - * - * @param crv The cryptographic curve. Must not be {@code null}. - * @param x The public 'x' parameter. Must not be {@code null}. - * @param d The private 'd' parameter. Must not be {@code null}. - * @param use The key use, {@code null} if not specified or if the - * key is intended for signing as well as encryption. - * @param ops The key operations, {@code null} if not specified. - * @param alg The intended JOSE algorithm for the key, {@code null} - * if not specified. - * @param kid The key ID, {@code null} if not specified. - * @param x5u The X.509 certificate URL, {@code null} if not - * specified. - * @param x5t The X.509 certificate SHA-1 thumbprint, {@code null} - * if not specified. - * @param x5t256 The X.509 certificate SHA-256 thumbprint, {@code null} - * if not specified. - * @param x5c The X.509 certificate chain, {@code null} if not - * specified. - * @param ks Reference to the underlying key store, {@code null} if - * not specified. - */ - public OctetKeyPair(final Curve crv, final Base64URL x, final Base64URL d, - final KeyUse use, final Set ops, final Algorithm alg, final String kid, - final URI x5u, final Base64URL x5t, final Base64URL x5t256, final List x5c, - final KeyStore ks) { - - super(KeyType.OKP, use, ops, alg, kid, x5u, x5t, x5t256, x5c, ks); - - if (crv == null) { - throw new IllegalArgumentException("The curve must not be null"); - } - - if (! SUPPORTED_CURVES.contains(crv)) { - throw new IllegalArgumentException("Unknown / unsupported curve: " + crv); - } - - this.crv = crv; - - if (x == null) { - throw new IllegalArgumentException("The 'x' parameter must not be null"); - } - - this.x = x; - decodedX = x.decode(); - - if (d == null) { - throw new IllegalArgumentException("The 'd' parameter must not be null"); - } - - this.d = d; - decodedD = d.decode(); - } - - - @Override - public Curve getCurve() { - - return crv; - } - - - /** - * Gets the public 'x' parameter. - * - * @return The public 'x' parameter. - */ - public Base64URL getX() { - - return x; - } - - - /** - * Gets the public 'x' parameter, decoded from Base64. - * - * @return The public 'x' parameter in bytes. - */ - public byte[] getDecodedX() { - - return decodedX.clone(); - } - - - /** - * Gets the private 'd' parameter. - * - * @return The private 'd' coordinate, {@code null} if not specified - * (for a public key). - */ - public Base64URL getD() { - - return d; - } - - - /** - * Gets the private 'd' parameter, decoded from Base64. - * - * @return The private 'd' coordinate in bytes, {@code null} if not specified - * (for a public key). - */ - public byte[] getDecodedD() { - - return decodedD == null ? null : decodedD.clone(); - } - - - @Override - public PublicKey toPublicKey() - throws JOSEException { - - throw new JOSEException("Export to java.security.PublicKey not supported"); - } - - - @Override - public PrivateKey toPrivateKey() - throws JOSEException { - - throw new JOSEException("Export to java.security.PrivateKey not supported"); - } - - - @Override - public KeyPair toKeyPair() - throws JOSEException { - - throw new JOSEException("Export to java.security.KeyPair not supported"); - } - - - @Override - public boolean matches(final X509Certificate cert) { - // X.509 certs don't support OKP yet - return false; - } - - - @Override - public LinkedHashMap getRequiredParams() { - - // Put mandatory params in sorted order - LinkedHashMap requiredParams = new LinkedHashMap<>(); - requiredParams.put("crv", crv.toString()); - requiredParams.put("kty", getKeyType().getValue()); - requiredParams.put("x", x.toString()); - return requiredParams; - } - - - @Override - public boolean isPrivate() { - - return d != null; - } - - - /** - * Returns a copy of this Octet Key Pair JWK with any private values - * removed. - * - * @return The copied public Octet Key Pair JWK. - */ - @Override - public OctetKeyPair toPublicJWK() { - - return new OctetKeyPair( - getCurve(), getX(), - getKeyUse(), getKeyOperations(), getAlgorithm(), getKeyID(), - getX509CertURL(), getX509CertThumbprint(), getX509CertSHA256Thumbprint(), getX509CertChain(), - getKeyStore()); - } - - - @Override - public JSONObject toJSONObject() { - - JSONObject o = super.toJSONObject(); - - // Append OKP specific attributes - o.put("crv", crv.toString()); - o.put("x", x.toString()); - - if (d != null) { - o.put("d", d.toString()); - } - - return o; - } - - - @Override - public int size() { - - return ByteUtils.bitLength(x.decode()); - } - - - /** - * Parses a public / private Octet Key Pair JWK from the specified JSON - * object string representation. - * - * @param s The JSON object string to parse. Must not be {@code null}. - * - * @return The public / private Octet Key Pair JWK. - * - * @throws ParseException If the string couldn't be parsed to an Octet - * Key Pair JWK. - */ - public static OctetKeyPair parse(final String s) - throws ParseException { - - return parse(JSONObjectUtils.parse(s)); - } - - - /** - * Parses a public / private Octet Key Pair JWK from the specified JSON - * object representation. - * - * @param jsonObject The JSON object to parse. Must not be - * {@code null}. - * - * @return The public / private Octet Key Pair JWK. - * - * @throws ParseException If the JSON object couldn't be parsed to an - * Octet Key Pair JWK. - */ - public static OctetKeyPair parse(final JSONObject jsonObject) - throws ParseException { - - // Parse the mandatory parameters first - Curve crv = Curve.parse(JSONObjectUtils.getString(jsonObject, "crv")); - Base64URL x = new Base64URL(JSONObjectUtils.getString(jsonObject, "x")); - - // Check key type - KeyType kty = JWKMetadata.parseKeyType(jsonObject); - - if (kty != KeyType.OKP) { - throw new ParseException("The key type \"kty\" must be OKP", 0); - } - - // Get optional private key - Base64URL d = null; - if (jsonObject.get("d") != null) { - d = new Base64URL(JSONObjectUtils.getString(jsonObject, "d")); - } - - - try { - if (d == null) { - // Public key - return new OctetKeyPair(crv, x, - JWKMetadata.parseKeyUse(jsonObject), - JWKMetadata.parseKeyOperations(jsonObject), - JWKMetadata.parseAlgorithm(jsonObject), - JWKMetadata.parseKeyID(jsonObject), - JWKMetadata.parseX509CertURL(jsonObject), - JWKMetadata.parseX509CertThumbprint(jsonObject), - JWKMetadata.parseX509CertSHA256Thumbprint(jsonObject), - JWKMetadata.parseX509CertChain(jsonObject), - null); - - } else { - // Key pair - return new OctetKeyPair(crv, x, d, - JWKMetadata.parseKeyUse(jsonObject), - JWKMetadata.parseKeyOperations(jsonObject), - JWKMetadata.parseAlgorithm(jsonObject), - JWKMetadata.parseKeyID(jsonObject), - JWKMetadata.parseX509CertURL(jsonObject), - JWKMetadata.parseX509CertThumbprint(jsonObject), - JWKMetadata.parseX509CertSHA256Thumbprint(jsonObject), - JWKMetadata.parseX509CertChain(jsonObject), - null); - } - - } catch (IllegalArgumentException ex) { - - // Conflicting 'use' and 'key_ops' - throw new ParseException(ex.getMessage(), 0); - } - } - - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof OctetKeyPair)) return false; - if (!super.equals(o)) return false; - OctetKeyPair that = (OctetKeyPair) o; - return Objects.equals(crv, that.crv) && - Objects.equals(x, that.x) && - Arrays.equals(decodedX, that.decodedX) && - Objects.equals(d, that.d) && - Arrays.equals(decodedD, that.decodedD); - } - - - @Override - public int hashCode() { - int result = Objects.hash(super.hashCode(), crv, x, d); - result = 31 * result + Arrays.hashCode(decodedX); - result = 31 * result + Arrays.hashCode(decodedD); - return result; - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/OctetSequenceKey.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/OctetSequenceKey.java deleted file mode 100644 index f1080adc0..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/OctetSequenceKey.java +++ /dev/null @@ -1,668 +0,0 @@ -/* - * 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.jwk; - - -import java.net.URI; -import java.security.*; -import java.text.ParseException; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Objects; -import java.util.Set; -import javax.crypto.SecretKey; -import javax.crypto.spec.SecretKeySpec; - -import net.jcip.annotations.Immutable; -import net.minidev.json.JSONObject; - -import com.nimbusds.jose.Algorithm; -import com.nimbusds.jose.JOSEException; -import com.nimbusds.jose.util.*; - - -/** - * {@link KeyType#OCT Octet sequence} JSON Web Key (JWK), used to represent - * symmetric keys. This class is immutable. - * - *

Octet sequence JWKs should specify the algorithm intended to be used with - * the key, unless the application uses other means or convention to determine - * the algorithm used. - * - *

Example JSON object representation of an octet sequence JWK: - * - *

- * {
- *   "kty" : "oct",
- *   "alg" : "A128KW",
- *   "k"   : "GawgguFyGrWKav7AX4VKUg"
- * }
- * 
- * - *

Use the builder to create a new octet JWK: - * - *

- * OctetSequenceKey key = new OctetSequenceKey.Builder(bytes)
- * 	.keyID("123")
- * 	.build();
- * 
- * - * @author Justin Richer - * @author Vladimir Dzhuvinov - * @version 2019-04-15 - */ -@Immutable -public final class OctetSequenceKey extends JWK implements SecretJWK { - - - private static final long serialVersionUID = 1L; - - - /** - * The key value. - */ - private final Base64URL k; - - - /** - * Builder for constructing octet sequence JWKs. - * - *

Example usage: - * - *

-	 * OctetSequenceKey key = new OctetSequenceKey.Builder(k)
-	 *     .algorithm(JWSAlgorithm.HS512)
-	 *     .keyID("123")
-	 *     .build();
-	 * 
- */ - public static class Builder { - - - /** - * The key value. - */ - private final Base64URL k; - - - /** - * The public key use, optional. - */ - private KeyUse use; - - - /** - * The key operations, optional. - */ - private Set ops; - - - /** - * The intended JOSE algorithm for the key, optional. - */ - private Algorithm alg; - - - /** - * The key ID, optional. - */ - private String kid; - - - /** - * X.509 certificate URL, optional. - */ - private URI x5u; - - - /** - * X.509 certificate SHA-1 thumbprint, optional. - */ - @Deprecated - private Base64URL x5t; - - - /** - * X.509 certificate SHA-256 thumbprint, optional. - */ - private Base64URL x5t256; - - - /** - * The X.509 certificate chain, optional. - */ - private List x5c; - - - /** - * Reference to the underlying key store, {@code null} if none. - */ - private KeyStore ks; - - - /** - * Creates a new octet sequence JWK builder. - * - * @param k The key value. It is represented as the Base64URL - * encoding of value's big endian representation. Must - * not be {@code null}. - */ - public Builder(final Base64URL k) { - - if (k == null) { - throw new IllegalArgumentException("The key value must not be null"); - } - - this.k = k; - } - - - /** - * Creates a new octet sequence JWK builder. - * - * @param key The key value. Must not be empty byte array or - * {@code null}. - */ - public Builder(final byte[] key) { - - this(Base64URL.encode(key)); - - if (key.length == 0) { - throw new IllegalArgumentException("The key must have a positive length"); - } - } - - - /** - * Creates a new octet sequence JWK builder. - * - * @param secretKey The secret key to represent. Must not be - * {@code null}. - */ - public Builder(final SecretKey secretKey) { - - this(secretKey.getEncoded()); - } - - - /** - * Sets the use ({@code use}) of the JWK. - * - * @param use The key use, {@code null} if not specified or if - * the key is intended for signing as well as - * encryption. - * - * @return This builder. - */ - public Builder keyUse(final KeyUse use) { - - this.use = use; - return this; - } - - - /** - * Sets the operations ({@code key_ops}) of the JWK (for a - * non-public key). - * - * @param ops The key operations, {@code null} if not - * specified. - * - * @return This builder. - */ - public Builder keyOperations(final Set ops) { - - this.ops = ops; - return this; - } - - - /** - * Sets the intended JOSE algorithm ({@code alg}) for the JWK. - * - * @param alg The intended JOSE algorithm, {@code null} if not - * specified. - * - * @return This builder. - */ - public Builder algorithm(final Algorithm alg) { - - this.alg = alg; - return this; - } - - /** - * Sets the ID ({@code kid}) of the JWK. The key ID can be used - * to match a specific key. This can be used, for instance, to - * choose a key within a {@link JWKSet} during key rollover. - * The key ID may also correspond to a JWS/JWE {@code kid} - * header parameter value. - * - * @param kid The key ID, {@code null} if not specified. - * - * @return This builder. - */ - public Builder keyID(final String kid) { - - this.kid = kid; - return this; - } - - - /** - * Sets the ID ({@code kid}) of the JWK to its SHA-256 JWK - * thumbprint (RFC 7638). The key ID can be used to match a - * specific key. This can be used, for instance, to choose a - * key within a {@link JWKSet} during key rollover. The key ID - * may also correspond to a JWS/JWE {@code kid} header - * parameter value. - * - * @return This builder. - * - * @throws JOSEException If the SHA-256 hash algorithm is not - * supported. - */ - public Builder keyIDFromThumbprint() - throws JOSEException { - - return keyIDFromThumbprint("SHA-256"); - } - - - /** - * Sets the ID ({@code kid}) of the JWK to its JWK thumbprint - * (RFC 7638). The key ID can be used to match a specific key. - * This can be used, for instance, to choose a key within a - * {@link JWKSet} during key rollover. The key ID may also - * correspond to a JWS/JWE {@code kid} header parameter value. - * - * @param hashAlg The hash algorithm for the JWK thumbprint - * computation. Must not be {@code null}. - * - * @return This builder. - * - * @throws JOSEException If the hash algorithm is not - * supported. - */ - public Builder keyIDFromThumbprint(final String hashAlg) - throws JOSEException { - - // Put mandatory params in sorted order - LinkedHashMap requiredParams = new LinkedHashMap<>(); - requiredParams.put("k", k.toString()); - requiredParams.put("kty", KeyType.OCT.getValue()); - this.kid = ThumbprintUtils.compute(hashAlg, requiredParams).toString(); - return this; - } - - - /** - * Sets the X.509 certificate URL ({@code x5u}) of the JWK. - * - * @param x5u The X.509 certificate URL, {@code null} if not - * specified. - * - * @return This builder. - */ - public Builder x509CertURL(final URI x5u) { - - this.x5u = x5u; - return this; - } - - - /** - * Sets the X.509 certificate SHA-1 thumbprint ({@code x5t}) of - * the JWK. - * - * @param x5t The X.509 certificate SHA-1 thumbprint, - * {@code null} if not specified. - * - * @return This builder. - */ - @Deprecated - public Builder x509CertThumbprint(final Base64URL x5t) { - - this.x5t = x5t; - return this; - } - - - /** - * Sets the X.509 certificate SHA-256 thumbprint - * ({@code x5t#S256}) of the JWK. - * - * @param x5t256 The X.509 certificate SHA-256 thumbprint, - * {@code null} if not specified. - * - * @return This builder. - */ - public Builder x509CertSHA256Thumbprint(final Base64URL x5t256) { - - this.x5t256 = x5t256; - return this; - } - - - /** - * Sets the X.509 certificate chain ({@code x5c}) of the JWK. - * - * @param x5c The X.509 certificate chain as a unmodifiable - * list, {@code null} if not specified. - * - * @return This builder. - */ - public Builder x509CertChain(final List x5c) { - - this.x5c = x5c; - return this; - } - - - /** - * Sets the underlying key store. - * - * @param keyStore Reference to the underlying key store, - * {@code null} if none. - * - * @return This builder. - */ - public Builder keyStore(final KeyStore keyStore) { - - this.ks = keyStore; - return this; - } - - - /** - * Builds a new octet sequence JWK. - * - * @return The octet sequence JWK. - * - * @throws IllegalStateException If the JWK parameters were - * inconsistently specified. - */ - public OctetSequenceKey build() { - - try { - return new OctetSequenceKey(k, use, ops, alg, kid, x5u, x5t, x5t256, x5c, ks); - - } catch (IllegalArgumentException e) { - - throw new IllegalStateException(e.getMessage(), e); - } - } - } - - - /** - * Creates a new octet sequence JSON Web Key (JWK) with the specified - * parameters. - * - * @param k The key value. It is represented as the Base64URL - * encoding of the value's big endian representation. - * Must not be {@code null}. - * @param use The key use, {@code null} if not specified or if the - * key is intended for signing as well as encryption. - * @param ops The key operations, {@code null} if not specified. - * @param alg The intended JOSE algorithm for the key, {@code null} - * if not specified. - * @param kid The key ID. {@code null} if not specified. - * @param x5u The X.509 certificate URL, {@code null} if not specified. - * @param x5t The X.509 certificate SHA-1 thumbprint, {@code null} - * if not specified. - * @param x5t256 The X.509 certificate SHA-256 thumbprint, {@code null} - * if not specified. - * @param x5c The X.509 certificate chain, {@code null} if not - * specified. - * @param ks Reference to the underlying key store, {@code null} if - * not specified. - */ - public OctetSequenceKey(final Base64URL k, - final KeyUse use, final Set ops, final Algorithm alg, final String kid, - final URI x5u, final Base64URL x5t, final Base64URL x5t256, final List x5c, - final KeyStore ks) { - - super(KeyType.OCT, use, ops, alg, kid, x5u, x5t, x5t256, x5c, ks); - - if (k == null) { - throw new IllegalArgumentException("The key value must not be null"); - } - - this.k = k; - } - - - /** - * Returns the value of this octet sequence key. - * - * @return The key value. It is represented as the Base64URL encoding - * of the value's big endian representation. - */ - public Base64URL getKeyValue() { - - return k; - } - - - /** - * Returns a copy of this octet sequence key value as a byte array. - * - * @return The key value as a byte array. - */ - public byte[] toByteArray() { - - return getKeyValue().decode(); - } - - - /** - * Returns a secret key representation of this octet sequence key. - * - * @return The secret key representation, with an algorithm set to - * {@code NONE}. - */ - @Override - public SecretKey toSecretKey() { - - return toSecretKey("NONE"); - } - - - /** - * Returns a secret key representation of this octet sequence key with - * the specified Java Cryptography Architecture (JCA) algorithm. - * - * @param jcaAlg The JCA algorithm. Must not be {@code null}. - * - * @return The secret key representation. - */ - public SecretKey toSecretKey(final String jcaAlg) { - - return new SecretKeySpec(toByteArray(), jcaAlg); - } - - - @Override - public LinkedHashMap getRequiredParams() { - - // Put mandatory params in sorted order - LinkedHashMap requiredParams = new LinkedHashMap<>(); - requiredParams.put("k", k.toString()); - requiredParams.put("kty", getKeyType().toString()); - return requiredParams; - } - - - /** - * Octet sequence (symmetric) keys are never considered public, this - * method always returns {@code true}. - * - * @return {@code true} - */ - @Override - public boolean isPrivate() { - - return true; - } - - - /** - * Octet sequence (symmetric) keys are never considered public, this - * method always returns {@code null}. - * - * @return {@code null} - */ - @Override - public OctetSequenceKey toPublicJWK() { - - return null; - } - - - @Override - public int size() { - - try { - return ByteUtils.safeBitLength(k.decode()); - } catch (IntegerOverflowException e) { - throw new ArithmeticException(e.getMessage()); - } - } - - - @Override - public JSONObject toJSONObject() { - - JSONObject o = super.toJSONObject(); - - // Append key value - o.put("k", k.toString()); - - return o; - } - - - /** - * Parses an octet sequence JWK from the specified JSON object string - * representation. - * - * @param s The JSON object string to parse. Must not be {@code null}. - * - * @return The octet sequence JWK. - * - * @throws ParseException If the string couldn't be parsed to an octet - * sequence JWK. - */ - public static OctetSequenceKey parse(final String s) - throws ParseException { - - return parse(JSONObjectUtils.parse(s)); - } - - - /** - * Parses an octet sequence JWK from the specified JSON object - * representation. - * - * @param jsonObject The JSON object to parse. Must not be - * {@code null}. - * - * @return The octet sequence JWK. - * - * @throws ParseException If the JSON object couldn't be parsed to an - * octet sequence JWK. - */ - public static OctetSequenceKey parse(final JSONObject jsonObject) - throws ParseException { - - // Parse the mandatory parameters first - Base64URL k = new Base64URL(JSONObjectUtils.getString(jsonObject, "k")); - - // Check key type - KeyType kty = JWKMetadata.parseKeyType(jsonObject); - - if (kty != KeyType.OCT) { - - throw new ParseException("The key type \"kty\" must be oct", 0); - } - - return new OctetSequenceKey(k, - JWKMetadata.parseKeyUse(jsonObject), - JWKMetadata.parseKeyOperations(jsonObject), - JWKMetadata.parseAlgorithm(jsonObject), - JWKMetadata.parseKeyID(jsonObject), - JWKMetadata.parseX509CertURL(jsonObject), - JWKMetadata.parseX509CertThumbprint(jsonObject), - JWKMetadata.parseX509CertSHA256Thumbprint(jsonObject), - JWKMetadata.parseX509CertChain(jsonObject), - null // key store - ); - } - - - /** - * Loads an octet sequence JWK from the specified JCA key store. - * - * @param keyStore The key store. Must not be {@code null}. - * @param alias The alias. Must not be {@code null}. - * @param pin The pin to unlock the private key if any, empty or - * {@code null} if not required. - * - * @return The octet sequence JWK, {@code null} if no key with the - * specified alias was found. - * - * @throws KeyStoreException On a key store exception. - * @throws JOSEException If octet sequence key loading failed. - */ - public static OctetSequenceKey load(final KeyStore keyStore, final String alias, final char[] pin) - throws KeyStoreException, JOSEException { - - Key key; - try { - key = keyStore.getKey(alias, pin); - } catch (UnrecoverableKeyException | NoSuchAlgorithmException e) { - throw new JOSEException("Couldn't retrieve secret key (bad pin?): " + e.getMessage(), e); - } - - if (! (key instanceof SecretKey)) { - return null; - } - - return new OctetSequenceKey.Builder((SecretKey)key) - .keyID(alias) - .keyStore(keyStore) - .build(); - } - - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof OctetSequenceKey)) return false; - if (!super.equals(o)) return false; - OctetSequenceKey that = (OctetSequenceKey) o; - return Objects.equals(k, that.k); - } - - - @Override - public int hashCode() { - return Objects.hash(super.hashCode(), k); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/PEMEncodedKeyParser.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/PEMEncodedKeyParser.java deleted file mode 100644 index 39337ab44..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/PEMEncodedKeyParser.java +++ /dev/null @@ -1,154 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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.jwk; - - -import java.io.Reader; -import java.io.StringReader; -import java.security.*; -import java.security.interfaces.RSAPrivateCrtKey; -import java.security.spec.InvalidKeySpecException; -import java.security.spec.RSAPublicKeySpec; -import java.util.ArrayList; -import java.util.List; - -import com.nimbusds.jose.JOSEException; -import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; -import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; -import org.bouncycastle.cert.X509CertificateHolder; -import org.bouncycastle.openssl.PEMException; -import org.bouncycastle.openssl.PEMKeyPair; -import org.bouncycastle.openssl.PEMParser; -import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter; - - -/** - * PEM-encoded public / private key parser. Requires Bouncy Castle. - * - * @author Stefan Larsson - */ -class PEMEncodedKeyParser { - - - // JcaPEMKeyConverter looks threadsafe - private static final JcaPEMKeyConverter pemConverter = new JcaPEMKeyConverter(); - - - private PEMEncodedKeyParser() { - // prevent construction of utility class - } - - - /** - * Parses one or more PEM-encoded certificates, public and / or private - * keys. The input is assumed to be not password-protected. - * - * @param pemEncodedKeys String of one or more PEM-encoded keys. - * - * @return The found keys. - * - * @throws JOSEException If parsing failed. - */ - static List parseKeys(final String pemEncodedKeys) - throws JOSEException { - - // Strips the "---- {BEGIN,END} {CERTIFICATE,PUBLIC/PRIVATE KEY} -----"-like header and footer lines, - // base64-decodes the body, - // then uses the proper key specification format to turn it into a JCA Key instance - final Reader pemReader = new StringReader(pemEncodedKeys); - final PEMParser parser = new PEMParser(pemReader); - final List keys = new ArrayList<>(); - - try { - Object pemObj; - do { - pemObj = parser.readObject(); - - // if public key, use as-is - if (pemObj instanceof SubjectPublicKeyInfo) { - keys.add(toKeyPair((SubjectPublicKeyInfo) pemObj)); - continue; - } - - // if certificate, use the public key which is signed - if (pemObj instanceof X509CertificateHolder) { - keys.add(toKeyPair((X509CertificateHolder) pemObj)); - continue; - } - - // if EC private key given, it arrives here as a keypair - if (pemObj instanceof PEMKeyPair) { - keys.add(toKeyPair((PEMKeyPair) pemObj)); - continue; - } - - // if (RSA) private key given, return it - if (pemObj instanceof PrivateKeyInfo) { - keys.add(toKeyPair((PrivateKeyInfo) pemObj)); - // continue implicitly - } - } while (pemObj != null); - - return keys; - } catch (Exception e) { - throw new JOSEException(e.getMessage(), e); - } - } - - - private static KeyPair toKeyPair(final SubjectPublicKeyInfo spki) - throws PEMException { - - return new KeyPair(pemConverter.getPublicKey(spki), null); - } - - - private static KeyPair toKeyPair(final X509CertificateHolder pemObj) - throws PEMException { - - final SubjectPublicKeyInfo spki = pemObj.getSubjectPublicKeyInfo(); - return new KeyPair(pemConverter.getPublicKey(spki), null); - } - - - private static KeyPair toKeyPair(final PEMKeyPair pair) - throws PEMException { - - return pemConverter.getKeyPair(pair); - } - - - private static KeyPair toKeyPair(final PrivateKeyInfo pki) - throws PEMException, NoSuchAlgorithmException, InvalidKeySpecException { - - final PrivateKey privateKey = pemConverter.getPrivateKey(pki); - - // If it's RSA, we can use the modulus and public exponents as BigIntegers to create a public key - if (privateKey instanceof RSAPrivateCrtKey) { - final RSAPublicKeySpec publicKeySpec = - new RSAPublicKeySpec(((RSAPrivateCrtKey) privateKey).getModulus(), - ((RSAPrivateCrtKey) privateKey).getPublicExponent()); - - final KeyFactory keyFactory = KeyFactory.getInstance("RSA"); - final PublicKey publicKey = keyFactory.generatePublic(publicKeySpec); - return new KeyPair(publicKey, privateKey); - } - - // If was a private EC key, it would already have been received as a PEMKeyPair - return new KeyPair(null, privateKey); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/PasswordLookup.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/PasswordLookup.java deleted file mode 100644 index a8e22e98b..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/PasswordLookup.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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.jwk; - - -/** - * Password lookup interface. - */ -public interface PasswordLookup { - - - /** - * Looks up the password for the specified name, e.g. key alias. - * - * @param name The name. May be {@code null}. - * - * @return The password, empty array if no password. - */ - char[] lookupPassword(final String name); -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/RSAKey.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/RSAKey.java deleted file mode 100644 index 11bf0eb35..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/RSAKey.java +++ /dev/null @@ -1,2276 +0,0 @@ -/* - * 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.jwk; - - -import java.io.Serializable; -import java.math.BigInteger; -import java.net.URI; -import java.security.*; -import java.security.cert.CertificateEncodingException; -import java.security.cert.X509Certificate; -import java.security.interfaces.RSAMultiPrimePrivateCrtKey; -import java.security.interfaces.RSAPrivateCrtKey; -import java.security.interfaces.RSAPrivateKey; -import java.security.interfaces.RSAPublicKey; -import java.security.spec.*; -import java.text.ParseException; -import java.util.*; - -import net.jcip.annotations.Immutable; -import net.minidev.json.JSONArray; -import net.minidev.json.JSONObject; - -import com.nimbusds.jose.Algorithm; -import com.nimbusds.jose.JOSEException; -import com.nimbusds.jose.util.Base64; -import com.nimbusds.jose.util.*; - - -/** - * Public and private {@link KeyType#RSA RSA} JSON Web Key (JWK). This class is - * immutable. - * - *

Provides RSA JWK import from / export to the following standard Java - * interfaces and classes: - * - *

    - *
  • {@link java.security.interfaces.RSAPublicKey} - *
  • {@link java.security.interfaces.RSAPrivateKey} - *
      - *
    • {@link java.security.interfaces.RSAPrivateCrtKey} - *
    • {@link java.security.interfaces.RSAMultiPrimePrivateCrtKey} - *
    - *
  • {@link java.security.PrivateKey} for an RSA key in a PKCS#11 store - *
  • {@link java.security.KeyPair} - *
- * - *

Example JSON object representation of a public RSA JWK: - * - *

- * { 
- *   "kty" : "RSA",
- *   "n"   : "0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx
- *            4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMs
- *            tn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2
- *            QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbI
- *            SD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqb
- *            w0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw",
- *   "e"   : "AQAB",
- *   "alg" : "RS256",
- *   "kid" : "2011-04-29"
- * }
- * 
- * - *

Example JSON object representation of a public and private RSA JWK (with - * both the first and the second private key representations): - * - *

- * { 
- *   "kty" : "RSA",
- *   "n"   : "0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx
- *            4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMs
- *            tn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2
- *            QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbI
- *            SD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqb
- *            w0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw",
- *   "e"   : "AQAB",
- *   "d"   : "X4cTteJY_gn4FYPsXB8rdXix5vwsg1FLN5E3EaG6RJoVH-HLLKD9
- *            M7dx5oo7GURknchnrRweUkC7hT5fJLM0WbFAKNLWY2vv7B6NqXSzUvxT0_YSfqij
- *            wp3RTzlBaCxWp4doFk5N2o8Gy_nHNKroADIkJ46pRUohsXywbReAdYaMwFs9tv8d
- *            _cPVY3i07a3t8MN6TNwm0dSawm9v47UiCl3Sk5ZiG7xojPLu4sbg1U2jx4IBTNBz
- *            nbJSzFHK66jT8bgkuqsk0GjskDJk19Z4qwjwbsnn4j2WBii3RL-Us2lGVkY8fkFz
- *            me1z0HbIkfz0Y6mqnOYtqc0X4jfcKoAC8Q",
- *   "p"   : "83i-7IvMGXoMXCskv73TKr8637FiO7Z27zv8oj6pbWUQyLPQBQxtPV
- *            nwD20R-60eTDmD2ujnMt5PoqMrm8RfmNhVWDtjjMmCMjOpSXicFHj7XOuVIYQyqV
- *            WlWEh6dN36GVZYk93N8Bc9vY41xy8B9RzzOGVQzXvNEvn7O0nVbfs",
- *   "q"   : "3dfOR9cuYq-0S-mkFLzgItgMEfFzB2q3hWehMuG0oCuqnb3vobLyum
- *            qjVZQO1dIrdwgTnCdpYzBcOfW5r370AFXjiWft_NGEiovonizhKpo9VVS78TzFgx
- *            kIdrecRezsZ-1kYd_s1qDbxtkDEgfAITAG9LUnADun4vIcb6yelxk",
- *   "dp"  : "G4sPXkc6Ya9y8oJW9_ILj4xuppu0lzi_H7VTkS8xj5SdX3coE0oim
- *            YwxIi2emTAue0UOa5dpgFGyBJ4c8tQ2VF402XRugKDTP8akYhFo5tAA77Qe_Nmtu
- *            YZc3C3m3I24G2GvR5sSDxUyAN2zq8Lfn9EUms6rY3Ob8YeiKkTiBj0",
- *   "dq"  : "s9lAH9fggBsoFR8Oac2R_E2gw282rT2kGOAhvIllETE1efrA6huUU
- *            vMfBcMpn8lqeW6vzznYY5SSQF7pMdC_agI3nG8Ibp1BUb0JUiraRNqUfLhcQb_d9
- *            GF4Dh7e74WbRsobRonujTYN1xCaP6TO61jvWrX-L18txXw494Q_cgk",
- *   "qi"  : "GyM_p6JrXySiz1toFgKbWV-JdI3jQ4ypu9rbMWx3rQJBfmt0FoYzg
- *            UIZEVFEcOqwemRN81zoDAaa-Bk0KWNGDjJHZDdDmFhW3AN7lI-puxk_mHZGJ11rx
- *            yR8O55XLSe3SPmRfKwZI6yU24ZxvQKFYItdldUKGzO6Ia6zTKhAVRU",
- *   "alg" : "RS256",
- *   "kid" : "2011-04-29"
- * }
- * 
- * - *

Use the builder to create a new RSA JWK: - * - *

- * RSAKey key = new RSAKey.Builder(n, e)
- * 	.keyUse(KeyUse.SIGNATURE)
- * 	.keyID("123")
- * 	.build();
- * 
- * - *

See RFC 3447. - * - *

See http://en.wikipedia.org/wiki/RSA_%28algorithm%29 - * - * @author Vladimir Dzhuvinov - * @author Justin Richer - * @author Cedric Staub - * @version 2019-04-15 - */ -@Immutable -public final class RSAKey extends JWK implements AsymmetricJWK { - - - private static final long serialVersionUID = 1L; - - - /** - * Other Primes Info, represents the private {@code oth} parameter of a - * RSA JWK. This class is immutable. - */ - @Immutable - public static class OtherPrimesInfo implements Serializable { - - - private static final long serialVersionUID = 1L; - - - /** - * The prime factor. - */ - private final Base64URL r; - - - /** - * The factor Chinese Remainder Theorem (CRT) exponent. - */ - private final Base64URL d; - - - /** - * The factor Chinese Remainder Theorem (CRT) coefficient. - */ - private final Base64URL t; - - - /** - * Creates a new JWK Other Primes Info with the specified - * parameters. - * - * @param r The prime factor. Must not be {@code null}. - * @param d The factor Chinese Remainder Theorem (CRT) - * exponent. Must not be {@code null}. - * @param t The factor Chinese Remainder Theorem (CRT) - * coefficient. Must not be {@code null}. - */ - public OtherPrimesInfo(final Base64URL r, final Base64URL d, final Base64URL t) { - - if (r == null) { - - throw new IllegalArgumentException("The prime factor must not be null"); - } - - this.r = r; - - if (d == null) { - - throw new IllegalArgumentException("The factor CRT exponent must not be null"); - } - - this.d = d; - - if (t == null) { - - throw new IllegalArgumentException("The factor CRT coefficient must not be null"); - } - - this.t = t; - } - - - /** - * Creates a new JWK Other Primes Info from the specified - * {@code java.security.spec.RSAOtherPrimeInfo} instance. - * - * @param oth The RSA Other Primes Info instance. Must not be - * {@code null}. - */ - public OtherPrimesInfo(final RSAOtherPrimeInfo oth) { - - r = Base64URL.encode(oth.getPrime()); - d = Base64URL.encode(oth.getExponent()); - t = Base64URL.encode(oth.getCrtCoefficient()); - } - - - /** - * Gets the prime factor ({@code r}). - * - * @return The prime factor. - */ - public Base64URL getPrimeFactor() { - - return r; - } - - - /** - * Gets factor Chinese Remainder Theorem (CRT) exponent - * ({@code d}). - * - * @return The factor Chinese Remainder Theorem (CRT) exponent. - */ - public Base64URL getFactorCRTExponent() { - - return d; - } - - - /** - * The factor Chinese Remainder Theorem (CRT) coefficient - * ({@code t}). - * - * @return The factor Chinese Remainder Theorem (CRT) - * coefficient. - */ - public Base64URL getFactorCRTCoefficient() { - - return t; - } - - - /** - * Converts the specified array of - * {@code java.security.spec.RSAOtherPrimeInfo} instances to a - * list of JWK Other Prime Infos. - * - * @param othArray Array of RSA Other Primes Info instances. - * May be be {@code null}. - * - * @return The corresponding list of JWK Other Prime Infos, or - * empty list of the array was {@code null}. - */ - public static List toList(final RSAOtherPrimeInfo[] othArray) { - - List list = new ArrayList<>(); - - if (othArray == null) { - - // Return empty list - return list; - } - - for (RSAOtherPrimeInfo oth: othArray) { - - list.add(new OtherPrimesInfo(oth)); - } - - return list; - } - } - - - /** - * Builder for constructing RSA JWKs. - * - *

Example usage: - * - *

-	 * RSAKey key = new RSAKey.Builder(n, e).
-	 *              privateExponent(d).
-	 *              algorithm(JWSAlgorithm.RS512).
-	 *              keyID("456").
-	 *              build();
-	 * 
- */ - public static class Builder { - - - // Public RSA params - - /** - * The modulus value for the RSA key. - */ - private final Base64URL n; - - - /** - * The public exponent of the RSA key. - */ - private final Base64URL e; - - - // Private RSA params, 1st representation - - /** - * The private exponent of the RSA key. - */ - private Base64URL d; - - - // Private RSA params, 2nd representation - - /** - * The first prime factor of the private RSA key. - */ - private Base64URL p; - - - /** - * The second prime factor of the private RSA key. - */ - private Base64URL q; - - - /** - * The first factor Chinese Remainder Theorem exponent of the - * private RSA key. - */ - private Base64URL dp; - - - /** - * The second factor Chinese Remainder Theorem exponent of the - * private RSA key. - */ - private Base64URL dq; - - - /** - * The first Chinese Remainder Theorem coefficient of the private RSA - * key. - */ - private Base64URL qi; - - - /** - * The other primes information of the private RSA key, should - * they exist. When only two primes have been used (the normal - * case), this parameter MUST be omitted. When three or more - * primes have been used, the number of array elements MUST be - * the number of primes used minus two. - */ - private List oth; - - - // Private RSA key, as PKCS#11 handle - - /** - * The private RSA key, as PKCS#11 handle. - */ - private PrivateKey priv; - - - /** - * The key use, optional. - */ - private KeyUse use; - - - /** - * The key operations, optional. - */ - private Set ops; - - - /** - * The intended JOSE algorithm for the key, optional. - */ - private Algorithm alg; - - - /** - * The key ID, optional. - */ - private String kid; - - - /** - * X.509 certificate URL, optional. - */ - private URI x5u; - - - /** - * X.509 certificate SHA-1 thumbprint, optional. - */ - @Deprecated - private Base64URL x5t; - - - /** - * X.509 certificate SHA-256 thumbprint, optional. - */ - private Base64URL x5t256; - - - /** - * The X.509 certificate chain, optional. - */ - private List x5c; - - - /** - * Reference to the underlying key store, {@code null} if none. - */ - private KeyStore ks; - - - /** - * Creates a new RSA JWK builder. - * - * @param n The the modulus value for the public RSA key. It is - * represented as the Base64URL encoding of value's - * big endian representation. Must not be - * {@code null}. - * @param e The exponent value for the public RSA key. It is - * represented as the Base64URL encoding of value's - * big endian representation. Must not be - * {@code null}. - */ - public Builder(final Base64URL n, final Base64URL e) { - - // Ensure the public params are defined - - if (n == null) { - throw new IllegalArgumentException("The modulus value must not be null"); - } - - this.n = n; - - - if (e == null) { - throw new IllegalArgumentException("The public exponent value must not be null"); - } - - this.e = e; - } - - - /** - * Creates a new RSA JWK builder. - * - * @param pub The public RSA key to represent. Must not be - * {@code null}. - */ - public Builder(final RSAPublicKey pub) { - - n = Base64URL.encode(pub.getModulus()); - e = Base64URL.encode(pub.getPublicExponent()); - } - - - /** - * Creates a new RSA JWK builder. - * - * @param rsaJWK The RSA JWK to start with. Must not be - * {@code null}. - */ - public Builder(final RSAKey rsaJWK) { - - n = rsaJWK.n; - e = rsaJWK.e; - d = rsaJWK.d; - p = rsaJWK.p; - q = rsaJWK.q; - dp = rsaJWK.dp; - dq = rsaJWK.dq; - qi = rsaJWK.qi; - oth = rsaJWK.oth; - priv = rsaJWK.privateKey; - use = rsaJWK.getKeyUse(); - ops = rsaJWK.getKeyOperations(); - alg = rsaJWK.getAlgorithm(); - kid = rsaJWK.getKeyID(); - x5u = rsaJWK.getX509CertURL(); - x5t = rsaJWK.getX509CertThumbprint(); - x5t256 = rsaJWK.getX509CertSHA256Thumbprint(); - x5c = rsaJWK.getX509CertChain(); - ks = rsaJWK.getKeyStore(); - } - - - /** - * Sets the private exponent ({@code d}) of the RSA key. - * - * @param d The private RSA key exponent. It is represented as - * the Base64URL encoding of the value's big endian - * representation. {@code null} if not specified (for - * a public key or a private key using the second - * representation only). - * - * @return This builder. - */ - public Builder privateExponent(final Base64URL d) { - - this.d = d; - return this; - } - - - /** - * Sets the private RSA key, using the first representation. - * - * @param priv The private RSA key, used to obtain the private - * exponent ({@code d}). Must not be {@code null}. - * - * @return This builder. - */ - public Builder privateKey(final RSAPrivateKey priv) { - - if (priv instanceof RSAPrivateCrtKey) { - return this.privateKey((RSAPrivateCrtKey) priv); - } else if (priv instanceof RSAMultiPrimePrivateCrtKey) { - return this.privateKey((RSAMultiPrimePrivateCrtKey) priv); - } else { - this.d = Base64URL.encode(priv.getPrivateExponent()); - return this; - } - } - - - /** - * Sets the private RSA key, typically for a key located in a - * PKCS#11 store that doesn't expose the private key parameters - * (such as a smart card or HSM). - * - * @param priv The private RSA key reference. Its algorithm - * must be "RSA". Must not be {@code null}. - * - * @return This builder. - */ - public Builder privateKey(final PrivateKey priv) { - if (priv instanceof RSAPrivateKey) { - return privateKey((RSAPrivateKey) priv); - } - - if (! "RSA".equalsIgnoreCase(priv.getAlgorithm())) { - throw new IllegalArgumentException("The private key algorithm must be RSA"); - } - - this.priv = priv; - return this; - } - - - /** - * Sets the first prime factor ({@code p}) of the private RSA - * key. - * - * @param p The RSA first prime factor. It is represented as - * the Base64URL encoding of the value's big endian - * representation. {@code null} if not specified (for - * a public key or a private key using the first - * representation only). - * - * @return This builder. - */ - public Builder firstPrimeFactor(final Base64URL p) { - - this.p = p; - return this; - } - - - /** - * Sets the second prime factor ({@code q}) of the private RSA - * key. - * - * @param q The RSA second prime factor. It is represented as - * the Base64URL encoding of the value's big endian - * representation. {@code null} if not specified (for - * a public key or a private key using the first - * representation only). - * - * @return This builder. - */ - public Builder secondPrimeFactor(final Base64URL q) { - - this.q = q; - return this; - } - - - /** - * Sets the first factor Chinese Remainder Theorem (CRT) - * exponent ({@code dp}) of the private RSA key. - * - * @param dp The RSA first factor CRT exponent. It is - * represented as the Base64URL encoding of the - * value's big endian representation. {@code null} - * if not specified (for a public key or a private - * key using the first representation only). - * - * @return This builder. - */ - public Builder firstFactorCRTExponent(final Base64URL dp) { - - this.dp = dp; - return this; - } - - - /** - * Sets the second factor Chinese Remainder Theorem (CRT) - * exponent ({@code dq}) of the private RSA key. - * - * @param dq The RSA second factor CRT exponent. It is - * represented as the Base64URL encoding of the - * value's big endian representation. {@code null} if - * not specified (for a public key or a private key - * using the first representation only). - * - * @return This builder. - */ - public Builder secondFactorCRTExponent(final Base64URL dq) { - - this.dq = dq; - return this; - } - - - /** - * Sets the first Chinese Remainder Theorem (CRT) coefficient - * ({@code qi}) of the private RSA key. - * - * @param qi The RSA first CRT coefficient. It is represented - * as the Base64URL encoding of the value's big - * endian representation. {@code null} if not - * specified (for a public key or a private key using - * the first representation only). - * - * @return This builder. - */ - public Builder firstCRTCoefficient(final Base64URL qi) { - - this.qi = qi; - return this; - } - - - /** - * Sets the other primes information ({@code oth}) for the - * private RSA key, should they exist. - * - * @param oth The RSA other primes information, {@code null} or - * empty list if not specified. - * - * @return This builder. - */ - public Builder otherPrimes(final List oth) { - - this.oth = oth; - return this; - } - - - /** - * Sets the private RSA key, using the second representation - * (see RFC 3447, section 3.2). - * - * @param priv The private RSA key, used to obtain the private - * exponent ({@code d}), the first prime factor - * ({@code p}), the second prime factor - * ({@code q}), the first factor CRT exponent - * ({@code dp}), the second factor CRT exponent - * ({@code dq}) and the first CRT coefficient - * ({@code qi}). Must not be {@code null}. - * - * @return This builder. - */ - public Builder privateKey(final RSAPrivateCrtKey priv) { - - d = Base64URL.encode(priv.getPrivateExponent()); - p = Base64URL.encode(priv.getPrimeP()); - q = Base64URL.encode(priv.getPrimeQ()); - dp = Base64URL.encode(priv.getPrimeExponentP()); - dq = Base64URL.encode(priv.getPrimeExponentQ()); - qi = Base64URL.encode(priv.getCrtCoefficient()); - - return this; - } - - - /** - * Sets the private RSA key, using the second representation, - * with optional other primes info (see RFC 3447, section 3.2). - * - * @param priv The private RSA key, used to obtain the private - * exponent ({@code d}), the first prime factor - * ({@code p}), the second prime factor - * ({@code q}), the first factor CRT exponent - * ({@code dp}), the second factor CRT exponent - * ({@code dq}), the first CRT coefficient - * ({@code qi}) and the other primes info - * ({@code oth}). Must not be {@code null}. - * - * @return This builder. - */ - public Builder privateKey(final RSAMultiPrimePrivateCrtKey priv) { - - d = Base64URL.encode(priv.getPrivateExponent()); - p = Base64URL.encode(priv.getPrimeP()); - q = Base64URL.encode(priv.getPrimeQ()); - dp = Base64URL.encode(priv.getPrimeExponentP()); - dq = Base64URL.encode(priv.getPrimeExponentQ()); - qi = Base64URL.encode(priv.getCrtCoefficient()); - oth = OtherPrimesInfo.toList(priv.getOtherPrimeInfo()); - - return this; - } - - - /** - * Sets the use ({@code use}) of the JWK. - * - * @param use The key use, {@code null} if not specified or if - * the key is intended for signing as well as - * encryption. - * - * @return This builder. - */ - public Builder keyUse(final KeyUse use) { - - this.use = use; - return this; - } - - - /** - * Sets the operations ({@code key_ops}) of the JWK (for a - * non-public key). - * - * @param ops The key operations, {@code null} if not - * specified. - * - * @return This builder. - */ - public Builder keyOperations(final Set ops) { - - this.ops = ops; - return this; - } - - - /** - * Sets the intended JOSE algorithm ({@code alg}) for the JWK. - * - * @param alg The intended JOSE algorithm, {@code null} if not - * specified. - * - * @return This builder. - */ - public Builder algorithm(final Algorithm alg) { - - this.alg = alg; - return this; - } - - /** - * Sets the ID ({@code kid}) of the JWK. The key ID can be used - * to match a specific key. This can be used, for instance, to - * choose a key within a {@link JWKSet} during key rollover. - * The key ID may also correspond to a JWS/JWE {@code kid} - * header parameter value. - * - * @param kid The key ID, {@code null} if not specified. - * - * @return This builder. - */ - public Builder keyID(final String kid) { - - this.kid = kid; - return this; - } - - - /** - * Sets the ID ({@code kid}) of the JWK to its SHA-256 JWK - * thumbprint (RFC 7638). The key ID can be used to match a - * specific key. This can be used, for instance, to choose a - * key within a {@link JWKSet} during key rollover. The key ID - * may also correspond to a JWS/JWE {@code kid} header - * parameter value. - * - * @return This builder. - * - * @throws JOSEException If the SHA-256 hash algorithm is not - * supported. - */ - public Builder keyIDFromThumbprint() - throws JOSEException { - - return keyIDFromThumbprint("SHA-256"); - } - - - /** - * Sets the ID ({@code kid}) of the JWK to its JWK thumbprint - * (RFC 7638). The key ID can be used to match a specific key. - * This can be used, for instance, to choose a key within a - * {@link JWKSet} during key rollover. The key ID may also - * correspond to a JWS/JWE {@code kid} header parameter value. - * - * @param hashAlg The hash algorithm for the JWK thumbprint - * computation. Must not be {@code null}. - * - * @return This builder. - * - * @throws JOSEException If the hash algorithm is not - * supported. - */ - public Builder keyIDFromThumbprint(final String hashAlg) - throws JOSEException { - - // Put mandatory params in sorted order - LinkedHashMap requiredParams = new LinkedHashMap<>(); - requiredParams.put("e", e.toString()); - requiredParams.put("kty", KeyType.RSA.getValue()); - requiredParams.put("n", n.toString()); - this.kid = ThumbprintUtils.compute(hashAlg, requiredParams).toString(); - return this; - } - - - /** - * Sets the X.509 certificate URL ({@code x5u}) of the JWK. - * - * @param x5u The X.509 certificate URL, {@code null} if not - * specified. - * - * @return This builder. - */ - public Builder x509CertURL(final URI x5u) { - - this.x5u = x5u; - return this; - } - - - /** - * Sets the X.509 certificate SHA-1 thumbprint ({@code x5t}) of - * the JWK. - * - * @param x5t The X.509 certificate SHA-1 thumbprint, - * {@code null} if not specified. - * - * @return This builder. - */ - @Deprecated - public Builder x509CertThumbprint(final Base64URL x5t) { - - this.x5t = x5t; - return this; - } - - - /** - * Sets the X.509 certificate SHA-256 thumbprint - * ({@code x5t#S256}) of the JWK. - * - * @param x5t256 The X.509 certificate SHA-256 thumbprint, - * {@code null} if not specified. - * - * @return This builder. - */ - public Builder x509CertSHA256Thumbprint(final Base64URL x5t256) { - - this.x5t256 = x5t256; - return this; - } - - - /** - * Sets the X.509 certificate chain ({@code x5c}) of the JWK. - * - * @param x5c The X.509 certificate chain as a unmodifiable - * list, {@code null} if not specified. - * - * @return This builder. - */ - public Builder x509CertChain(final List x5c) { - - this.x5c = x5c; - return this; - } - - - /** - * Sets the underlying key store. - * - * @param keyStore Reference to the underlying key store, - * {@code null} if none. - * - * @return This builder. - */ - public Builder keyStore(final KeyStore keyStore) { - - this.ks = keyStore; - return this; - } - - - /** - * Builds a new RSA JWK. - * - * @return The RSA JWK. - * - * @throws IllegalStateException If the JWK parameters were - * inconsistently specified. - */ - public RSAKey build() { - - try { - // The full constructor - return new RSAKey(n, e, d, p, q, dp, dq, qi, oth, - priv, - use, ops, alg, kid, x5u, x5t, x5t256, x5c, - ks); - - } catch (IllegalArgumentException e) { - - throw new IllegalStateException(e.getMessage(), e); - } - } - } - - - // Public RSA params - - /** - * The modulus value of the RSA key. - */ - private final Base64URL n; - - - /** - * The public exponent of the RSA key. - */ - private final Base64URL e; - - - // Private RSA params, 1st representation - - /** - * The private exponent of the RSA key. - */ - private final Base64URL d; - - - // Private RSA params, 2nd representation - - /** - * The first prime factor of the private RSA key. - */ - private final Base64URL p; - - - /** - * The second prime factor of the private RSA key. - */ - private final Base64URL q; - - - /** - * The first factor Chinese Remainder Theorem exponent of the private - * RSA key. - */ - private final Base64URL dp; - - - /** - * The second factor Chinese Remainder Theorem exponent of the private - * RSA key. - */ - private final Base64URL dq; - - - /** - * The first Chinese Remainder Theorem coefficient of the private RSA - * key. - */ - private final Base64URL qi; - - - /** - * The other primes information of the private RSA key, should they - * exist. When only two primes have been used (the normal case), this - * parameter MUST be omitted. When three or more primes have been used, - * the number of array elements MUST be the number of primes used minus - * two. - */ - private final List oth; - - - // Private RSA PKCS#11 key handle - - /** - * Private PKCS#11 key handle. - */ - private final PrivateKey privateKey; - - - /** - * Creates a new public RSA JSON Web Key (JWK) with the specified - * parameters. - * - * @param n The the modulus value for the public RSA key. It is - * represented as the Base64URL encoding of value's big - * endian representation. Must not be {@code null}. - * @param e The exponent value for the public RSA key. It is - * represented as the Base64URL encoding of value's big - * endian representation. Must not be {@code null}. - * @param use The key use, {@code null} if not specified or if the - * key is intended for signing as well as encryption. - * @param ops The key operations, {@code null} if not specified. - * @param alg The intended JOSE algorithm for the key, {@code null} - * if not specified. - * @param kid The key ID. {@code null} if not specified. - * @param x5u The X.509 certificate URL, {@code null} if not - * specified. - * @param x5t The X.509 certificate SHA-1 thumbprint, {@code null} - * if not specified. - * @param x5t256 The X.509 certificate SHA-256 thumbprint, {@code null} - * if not specified. - * @param x5c The X.509 certificate chain, {@code null} if not - * specified. - * @param ks Reference to the underlying key store, {@code null} if - * not specified. - */ - public RSAKey(final Base64URL n, final Base64URL e, - final KeyUse use, final Set ops, final Algorithm alg, final String kid, - final URI x5u, final Base64URL x5t, final Base64URL x5t256, final List x5c, - final KeyStore ks) { - - // Call the full constructor, all private key parameters are null - this(n, e, null, null, null, null, null, null, null, null, use, ops, alg, kid, - x5u, x5t, x5t256, x5c, - ks); - } - - - /** - * Creates a new public / private RSA JSON Web Key (JWK) with the - * specified parameters. The private RSA key is specified by its first - * representation (see RFC 3447, section 3.2). - * - * @param n The the modulus value for the public RSA key. It is - * represented as the Base64URL encoding of value's big - * endian representation. Must not be {@code null}. - * @param e The exponent value for the public RSA key. It is - * represented as the Base64URL encoding of value's big - * endian representation. Must not be {@code null}. - * @param d The private exponent. It is represented as the - * Base64URL encoding of the value's big endian - * representation. Must not be {@code null}. - * @param use The key use, {@code null} if not specified or if the - * key is intended for signing as well as encryption. - * @param ops The key operations, {@code null} if not specified. - * @param alg The intended JOSE algorithm for the key, {@code null} - * if not specified. - * @param kid The key ID. {@code null} if not specified. - * @param x5u The X.509 certificate URL, {@code null} if not - * specified. - * @param x5t The X.509 certificate SHA-1 thumbprint, {@code null} - * if not specified. - * @param x5t256 The X.509 certificate SHA-256 thumbprint, {@code null} - * if not specified. - * @param x5c The X.509 certificate chain, {@code null} if not - * specified. - * @param ks Reference to the underlying key store, {@code null} if - * not specified. - */ - public RSAKey(final Base64URL n, final Base64URL e, final Base64URL d, - final KeyUse use, final Set ops, final Algorithm alg, final String kid, - final URI x5u, final Base64URL x5t, final Base64URL x5t256, final List x5c, - final KeyStore ks) { - - // Call the full constructor, the second private representation - // parameters are all null - this(n, e, d, null, null, null, null, null, null, null, use, ops, alg, kid, - x5u, x5t, x5t256, x5c, ks); - - if (d == null) { - throw new IllegalArgumentException("The private exponent must not be null"); - } - } - - - /** - * Creates a new public / private RSA JSON Web Key (JWK) with the - * specified parameters. The private RSA key is specified by its - * second representation (see RFC 3447, section 3.2). - * - * @param n The the modulus value for the public RSA key. It is - * represented as the Base64URL encoding of value's big - * endian representation. Must not be {@code null}. - * @param e The exponent value for the public RSA key. It is - * represented as the Base64URL encoding of value's big - * endian representation. Must not be {@code null}. - * @param p The first prime factor. It is represented as the - * Base64URL encoding of the value's big endian - * representation. Must not be {@code null}. - * @param q The second prime factor. It is represented as the - * Base64URL encoding of the value's big endian - * representation. Must not be {@code null}. - * @param dp The first factor Chinese Remainder Theorem exponent. - * It is represented as the Base64URL encoding of the - * value's big endian representation. Must not be - * {@code null}. - * @param dq The second factor Chinese Remainder Theorem exponent. - * It is represented as the Base64URL encoding of the - * value's big endian representation. Must not be - * {@code null}. - * @param qi The first Chinese Remainder Theorem coefficient. It is - * represented as the Base64URL encoding of the value's - * big endian representation. Must not be {@code null}. - * @param oth The other primes information, should they exist, - * {@code null} or an empty list if not specified. - * @param use The key use, {@code null} if not specified or if the - * key is intended for signing as well as encryption. - * @param ops The key operations, {@code null} if not specified. - * @param alg The intended JOSE algorithm for the key, {@code null} - * if not specified. - * @param kid The key ID. {@code null} if not specified. - * @param x5u The X.509 certificate URL, {@code null} if not - * specified. - * @param x5t The X.509 certificate SHA-1 thumbprint, {@code null} - * if not specified. - * @param x5t256 The X.509 certificate SHA-256 thumbprint, {@code null} - * if not specified. - * @param x5c The X.509 certificate chain, {@code null} if not - * specified. - * @param ks Reference to the underlying key store, {@code null} if - * not specified. - */ - public RSAKey(final Base64URL n, final Base64URL e, - final Base64URL p, final Base64URL q, - final Base64URL dp, final Base64URL dq, final Base64URL qi, - final List oth, - final KeyUse use, final Set ops, final Algorithm alg, final String kid, - final URI x5u, final Base64URL x5t, final Base64URL x5t256, final List x5c, - final KeyStore ks) { - - // Call the full constructor, the first private representation - // d param is null - this(n, e, null, p, q, dp, dq, qi, oth, null, use, ops, alg, kid, - x5u, x5t, x5t256, x5c, - ks); - - if (p == null) { - throw new IllegalArgumentException("The first prime factor must not be null"); - } - - if (q == null) { - throw new IllegalArgumentException("The second prime factor must not be null"); - } - - if (dp == null) { - throw new IllegalArgumentException("The first factor CRT exponent must not be null"); - } - - if (dq == null) { - throw new IllegalArgumentException("The second factor CRT exponent must not be null"); - } - - if (qi == null) { - throw new IllegalArgumentException("The first CRT coefficient must not be null"); - } - } - - - /** - * Creates a new public / private RSA JSON Web Key (JWK) with the - * specified parameters. The private RSA key is specified by both its - * first and second representations (see RFC 3447, section 3.2). - * - *

A valid first private RSA key representation must specify the - * {@code d} parameter. - * - *

A valid second private RSA key representation must specify all - * required Chinese Remainder Theorem (CRT) parameters - {@code p}, - * {@code q}, {@code dp}, {@code dq} and {@code qi}, else an - * {@link java.lang.IllegalArgumentException} will be thrown. - * - * @param n The the modulus value for the public RSA key. It is - * represented as the Base64URL encoding of value's big - * endian representation. Must not be {@code null}. - * @param e The exponent value for the public RSA key. It is - * represented as the Base64URL encoding of value's big - * endian representation. Must not be {@code null}. - * @param d The private exponent. It is represented as the Base64URL - * encoding of the value's big endian representation. May - * be {@code null}. - * @param p The first prime factor. It is represented as the - * Base64URL encoding of the value's big endian - * representation. May be {@code null}. - * @param q The second prime factor. It is represented as the - * Base64URL encoding of the value's big endian - * representation. May be {@code null}. - * @param dp The first factor Chinese Remainder Theorem exponent. It - * is represented as the Base64URL encoding of the value's - * big endian representation. May be {@code null}. - * @param dq The second factor Chinese Remainder Theorem exponent. It - * is represented as the Base64URL encoding of the value's - * big endian representation. May be {@code null}. - * @param qi The first Chinese Remainder Theorem coefficient. It is - * represented as the Base64URL encoding of the value's big - * endian representation. May be {@code null}. - * @param oth The other primes information, should they exist, - * {@code null} or an empty list if not specified. - * @param use The key use, {@code null} if not specified or if the key - * is intended for signing as well as encryption. - * @param ops The key operations, {@code null} if not specified. - * @param alg The intended JOSE algorithm for the key, {@code null} if - * not specified. - * @param kid The key ID. {@code null} if not specified. - * @param x5u The X.509 certificate URL, {@code null} if not specified. - * @param x5t The X.509 certificate SHA-1 thumbprint, {@code null} - * if not specified. - * @param x5t256 The X.509 certificate SHA-256 thumbprint, {@code null} - * if not specified. - * @param x5c The X.509 certificate chain, {@code null} if not - * specified. - */ - @Deprecated - public RSAKey(final Base64URL n, final Base64URL e, - final Base64URL d, - final Base64URL p, final Base64URL q, - final Base64URL dp, final Base64URL dq, final Base64URL qi, - final List oth, - final KeyUse use, final Set ops, final Algorithm alg, final String kid, - final URI x5u, final Base64URL x5t, final Base64URL x5t256, final List x5c) { - - this(n, e, d, p, q, dp, dq, qi, oth, null, use, ops, alg, kid, x5u, x5t, x5t256, x5c, null); - } - - - /** - * Creates a new public / private RSA JSON Web Key (JWK) with the - * specified parameters. The private RSA key can be specified by its - * first representation, its second representation (see RFC 3447, - * section 3.2), or by a PKCS#11 handle as {@link PrivateKey}. - * - *

A valid first private RSA key representation must specify the - * {@code d} parameter. - * - *

A valid second private RSA key representation must specify all - * required Chinese Remainder Theorem (CRT) parameters - {@code p}, - * {@code q}, {@code dp}, {@code dq} and {@code qi}, else an - * {@link java.lang.IllegalArgumentException} will be thrown. - * - * @param n The the modulus value for the public RSA key. It is - * represented as the Base64URL encoding of value's big - * endian representation. Must not be {@code null}. - * @param e The exponent value for the public RSA key. It is - * represented as the Base64URL encoding of value's big - * endian representation. Must not be {@code null}. - * @param d The private exponent. It is represented as the Base64URL - * encoding of the value's big endian representation. May - * be {@code null}. - * @param p The first prime factor. It is represented as the - * Base64URL encoding of the value's big endian - * representation. May be {@code null}. - * @param q The second prime factor. It is represented as the - * Base64URL encoding of the value's big endian - * representation. May be {@code null}. - * @param dp The first factor Chinese Remainder Theorem exponent. It - * is represented as the Base64URL encoding of the value's - * big endian representation. May be {@code null}. - * @param dq The second factor Chinese Remainder Theorem exponent. It - * is represented as the Base64URL encoding of the value's - * big endian representation. May be {@code null}. - * @param qi The first Chinese Remainder Theorem coefficient. It is - * represented as the Base64URL encoding of the value's big - * endian representation. May be {@code null}. - * @param oth The other primes information, should they exist, - * {@code null} or an empty list if not specified. - * @param use The key use, {@code null} if not specified or if the key - * is intended for signing as well as encryption. - * @param ops The key operations, {@code null} if not specified. - * @param alg The intended JOSE algorithm for the key, {@code null} if - * not specified. - * @param kid The key ID. {@code null} if not specified. - * @param x5u The X.509 certificate URL, {@code null} if not specified. - * @param x5t The X.509 certificate SHA-1 thumbprint, {@code null} - * if not specified. - * @param x5t256 The X.509 certificate SHA-256 thumbprint, {@code null} - * if not specified. - * @param x5c The X.509 certificate chain, {@code null} if not - * specified. - * @param ks Reference to the underlying key store, {@code null} if - * not specified. - */ - public RSAKey(final Base64URL n, final Base64URL e, - final Base64URL d, - final Base64URL p, final Base64URL q, - final Base64URL dp, final Base64URL dq, final Base64URL qi, - final List oth, - final PrivateKey prv, - final KeyUse use, final Set ops, final Algorithm alg, final String kid, - final URI x5u, final Base64URL x5t, final Base64URL x5t256, final List x5c, - final KeyStore ks) { - - super(KeyType.RSA, use, ops, alg, kid, x5u, x5t, x5t256, x5c, ks); - - - // Ensure the public params are defined - - if (n == null) { - throw new IllegalArgumentException("The modulus value must not be null"); - } - this.n = n; - - - if (e == null) { - throw new IllegalArgumentException("The public exponent value must not be null"); - } - this.e = e; - - if (getParsedX509CertChain() != null) { - if (! matches(getParsedX509CertChain().get(0))) - throw new IllegalArgumentException("The public subject key info of the first X.509 certificate in the chain must match the JWK type and public parameters"); - } - - // Private params, 1st representation - - this.d = d; - - - // Private params, 2nd representation, check for consistency - - if (p != null && q != null && dp != null && dq != null && qi != null) { - - // CRT params fully specified - this.p = p; - this.q = q; - this.dp = dp; - this.dq = dq; - this.qi = qi; - - // Other RSA primes info optional, default to empty list - if (oth != null) { - this.oth = Collections.unmodifiableList(oth); - } else { - this.oth = Collections.emptyList(); - } - - } else if (p == null && q == null && dp == null && dq == null && qi == null && oth == null) { - - // No CRT params - this.p = null; - this.q = null; - this.dp = null; - this.dq = null; - this.qi = null; - - this.oth = Collections.emptyList(); - - } else if (p != null || q != null || dp != null || dq != null || qi != null) { - - if (p == null) { - throw new IllegalArgumentException("Incomplete second private (CRT) representation: The first prime factor must not be null"); - } else if (q == null) { - throw new IllegalArgumentException("Incomplete second private (CRT) representation: The second prime factor must not be null"); - } else if (dp == null) { - throw new IllegalArgumentException("Incomplete second private (CRT) representation: The first factor CRT exponent must not be null"); - } else if (dq == null) { - throw new IllegalArgumentException("Incomplete second private (CRT) representation: The second factor CRT exponent must not be null"); - } else { - throw new IllegalArgumentException("Incomplete second private (CRT) representation: The first CRT coefficient must not be null"); - } - } else { - // No CRT params - this.p = null; - this.q = null; - this.dp = null; - this.dq = null; - this.qi = null; - this.oth = Collections.emptyList(); - } - - this.privateKey = prv; // PKCS#11 handle - } - - - /** - * Creates a new public RSA JSON Web Key (JWK) with the specified - * parameters. - * - * @param pub The public RSA key to represent. Must not be - * {@code null}. - * @param use The key use, {@code null} if not specified or if the - * key is intended for signing as well as encryption. - * @param ops The key operations, {@code null} if not specified. - * @param alg The intended JOSE algorithm for the key, {@code null} - * if not specified. - * @param kid The key ID. {@code null} if not specified. - * @param x5u The X.509 certificate URL, {@code null} if not - * specified. - * @param x5t The X.509 certificate SHA-1 thumbprint, {@code null} - * if not specified. - * @param x5t256 The X.509 certificate SHA-256 thumbprint, {@code null} - * if not specified. - * @param x5c The X.509 certificate chain, {@code null} if not - * specified. - * @param ks Reference to the underlying key store, {@code null} if - * not specified. - */ - public RSAKey(final RSAPublicKey pub, - final KeyUse use, final Set ops, final Algorithm alg, final String kid, - final URI x5u, final Base64URL x5t, final Base64URL x5t256, final List x5c, - final KeyStore ks) { - - this(Base64URL.encode(pub.getModulus()), - Base64URL.encode(pub.getPublicExponent()), - use, ops, alg, kid, - x5u, x5t, x5t256, x5c, - ks); - } - - - /** - * Creates a new public / private RSA JSON Web Key (JWK) with the - * specified parameters. The private RSA key is specified by its first - * representation (see RFC 3447, section 3.2). - * - * @param pub The public RSA key to represent. Must not be - * {@code null}. - * @param priv The private RSA key to represent. Must not be - * {@code null}. - * @param use The key use, {@code null} if not specified or if the - * key is intended for signing as well as encryption. - * @param ops The key operations, {@code null} if not specified. - * @param alg The intended JOSE algorithm for the key, {@code null} - * if not specified. - * @param kid The key ID. {@code null} if not specified. - * @param x5u The X.509 certificate URL, {@code null} if not - * specified. - * @param x5t The X.509 certificate SHA-1 thumbprint, {@code null} - * if not specified. - * @param x5t256 The X.509 certificate SHA-256 thumbprint, {@code null} - * if not specified. - * @param x5c The X.509 certificate chain, {@code null} if not - * specified. - * @param ks Reference to the underlying key store, {@code null} if - * not specified. - */ - public RSAKey(final RSAPublicKey pub, final RSAPrivateKey priv, - final KeyUse use, final Set ops, final Algorithm alg, final String kid, - final URI x5u, final Base64URL x5t, final Base64URL x5t256, final List x5c, - final KeyStore ks) { - - this(Base64URL.encode(pub.getModulus()), - Base64URL.encode(pub.getPublicExponent()), - Base64URL.encode(priv.getPrivateExponent()), - use, ops, alg, kid, - x5u, x5t, x5t256, x5c, - ks); - } - - - /** - * Creates a new public / private RSA JSON Web Key (JWK) with the - * specified parameters. The private RSA key is specified by its second - * representation (see RFC 3447, section 3.2). - * - * @param pub The public RSA key to represent. Must not be - * {@code null}. - * @param priv The private RSA key to represent. Must not be - * {@code null}. - * @param use The key use, {@code null} if not specified or if the - * key is intended for signing as well as encryption. - * @param ops The key operations, {@code null} if not specified. - * @param alg The intended JOSE algorithm for the key, {@code null} - * if not specified. - * @param kid The key ID. {@code null} if not specified. - * @param x5u The X.509 certificate URL, {@code null} if not - * specified. - * @param x5t The X.509 certificate SHA-1 thumbprint, {@code null} - * if not specified. - * @param x5t256 The X.509 certificate SHA-256 thumbprint, {@code null} - * if not specified. - * @param x5c The X.509 certificate chain, {@code null} if not - * specified. - * @param ks Reference to the underlying key store, {@code null} if - * not specified. - */ - public RSAKey(final RSAPublicKey pub, final RSAPrivateCrtKey priv, - final KeyUse use, final Set ops, final Algorithm alg, final String kid, - final URI x5u, final Base64URL x5t, final Base64URL x5t256, final List x5c, - final KeyStore ks) { - - this(Base64URL.encode(pub.getModulus()), - Base64URL.encode(pub.getPublicExponent()), - Base64URL.encode(priv.getPrivateExponent()), - Base64URL.encode(priv.getPrimeP()), - Base64URL.encode(priv.getPrimeQ()), - Base64URL.encode(priv.getPrimeExponentP()), - Base64URL.encode(priv.getPrimeExponentQ()), - Base64URL.encode(priv.getCrtCoefficient()), - null, - null, - use, ops, alg, kid, - x5u, x5t, x5t256, x5c, - ks); - } - - - /** - * Creates a new public / private RSA JSON Web Key (JWK) with the - * specified parameters. The private RSA key is specified by its second - * representation, with optional other primes info (see RFC 3447, - * section 3.2). - * - * @param pub The public RSA key to represent. Must not be - * {@code null}. - * @param priv The private RSA key to represent. Must not be - * {@code null}. - * @param use The key use, {@code null} if not specified or if the - * key is intended for signing as well as encryption. - * @param ops The key operations, {@code null} if not specified. - * @param alg The intended JOSE algorithm for the key, {@code null} - * if not specified. - * @param kid The key ID. {@code null} if not specified. - * @param x5u The X.509 certificate URL, {@code null} if not - * specified. - * @param x5t The X.509 certificate SHA-1 thumbprint, {@code null} - * if not specified. - * @param x5t256 The X.509 certificate SHA-256 thumbprint, {@code null} - * if not specified. - * @param x5c The X.509 certificate chain, {@code null} if not - * specified. - * @param ks Reference to the underlying key store, {@code null} if - * not specified. - */ - public RSAKey(final RSAPublicKey pub, final RSAMultiPrimePrivateCrtKey priv, - final KeyUse use, final Set ops, final Algorithm alg, final String kid, - final URI x5u, final Base64URL x5t, final Base64URL x5t256, final List x5c, - final KeyStore ks) { - - this(Base64URL.encode(pub.getModulus()), - Base64URL.encode(pub.getPublicExponent()), - Base64URL.encode(priv.getPrivateExponent()), - Base64URL.encode(priv.getPrimeP()), - Base64URL.encode(priv.getPrimeQ()), - Base64URL.encode(priv.getPrimeExponentP()), - Base64URL.encode(priv.getPrimeExponentQ()), - Base64URL.encode(priv.getCrtCoefficient()), - OtherPrimesInfo.toList(priv.getOtherPrimeInfo()), - null, - use, ops, alg, kid, - x5u, x5t, x5t256, x5c, - ks); - } - - - /** - * Creates a new public / private RSA JSON Web Key (JWK) with the - * specified parameters. The private RSA key is specified by a PKCS#11 - * handle. - * - * @param pub The public RSA key to represent. Must not be - * {@code null}. - * @param priv The private RSA key as PKCS#11 handle, {@code null} if - * not specified. - * @param use The key use, {@code null} if not specified or if the - * key is intended for signing as well as encryption. - * @param ops The key operations, {@code null} if not specified. - * @param alg The intended JOSE algorithm for the key, {@code null} - * if not specified. - * @param kid The key ID. {@code null} if not specified. - * @param x5u The X.509 certificate URL, {@code null} if not - * specified. - * @param x5t The X.509 certificate SHA-1 thumbprint, {@code null} - * if not specified. - * @param x5t256 The X.509 certificate SHA-256 thumbprint, {@code null} - * if not specified. - * @param x5c The X.509 certificate chain, {@code null} if not - * specified. - * @param ks Reference to the underlying key store, {@code null} if - * not specified. - */ - public RSAKey(final RSAPublicKey pub, final PrivateKey priv, - final KeyUse use, final Set ops, final Algorithm alg, final String kid, - final URI x5u, final Base64URL x5t, final Base64URL x5t256, final List x5c, - final KeyStore ks) { - - this(Base64URL.encode(pub.getModulus()), - Base64URL.encode(pub.getPublicExponent()), - null, - null, - null, - null, - null, - null, - null, - priv, - use, ops, alg, kid, - x5u, x5t, x5t256, x5c, - ks); - } - - - /** - * Gets the modulus value ({@code n}) of the RSA key. - * - * @return The RSA key modulus. It is represented as the Base64URL - * encoding of the value's big endian representation. - */ - public Base64URL getModulus() { - - return n; - } - - - /** - * Gets the public exponent ({@code e}) of the RSA key. - * - * @return The public RSA key exponent. It is represented as the - * Base64URL encoding of the value's big endian representation. - */ - public Base64URL getPublicExponent() { - - return e; - } - - - /** - * Gets the private exponent ({@code d}) of the RSA key. - * - * @return The private RSA key exponent. It is represented as the - * Base64URL encoding of the value's big endian representation. - * {@code null} if not specified (for a public key or a private - * key using the second representation only). - */ - public Base64URL getPrivateExponent() { - - return d; - } - - - /** - * Gets the first prime factor ({@code p}) of the private RSA key. - * - * @return The RSA first prime factor. It is represented as the - * Base64URL encoding of the value's big endian representation. - * {@code null} if not specified (for a public key or a private - * key using the first representation only). - */ - public Base64URL getFirstPrimeFactor() { - - return p; - } - - - /** - * Gets the second prime factor ({@code q}) of the private RSA key. - * - * @return The RSA second prime factor. It is represented as the - * Base64URL encoding of the value's big endian representation. - * {@code null} if not specified (for a public key or a private - * key using the first representation only). - */ - public Base64URL getSecondPrimeFactor() { - - return q; - } - - - /** - * Gets the first factor Chinese Remainder Theorem (CRT) exponent - * ({@code dp}) of the private RSA key. - * - * @return The RSA first factor CRT exponent. It is represented as the - * Base64URL encoding of the value's big endian representation. - * {@code null} if not specified (for a public key or a private - * key using the first representation only). - */ - public Base64URL getFirstFactorCRTExponent() { - - return dp; - } - - - /** - * Gets the second factor Chinese Remainder Theorem (CRT) exponent - * ({@code dq}) of the private RSA key. - * - * @return The RSA second factor CRT exponent. It is represented as the - * Base64URL encoding of the value's big endian representation. - * {@code null} if not specified (for a public key or a private - * key using the first representation only). - */ - public Base64URL getSecondFactorCRTExponent() { - - return dq; - } - - - /** - * Gets the first Chinese Remainder Theorem (CRT) coefficient - * ({@code qi})} of the private RSA key. - * - * @return The RSA first CRT coefficient. It is represented as the - * Base64URL encoding of the value's big endian representation. - * {@code null} if not specified (for a public key or a private - * key using the first representation only). - */ - public Base64URL getFirstCRTCoefficient() { - - return qi; - } - - - /** - * Gets the other primes information ({@code oth}) for the private RSA - * key, should they exist. - * - * @return The RSA other primes information, {@code null} or empty list - * if not specified. - */ - public List getOtherPrimes() { - - return oth; - } - - - /** - * Returns a standard {@code java.security.interfaces.RSAPublicKey} - * representation of this RSA JWK. - * - * @return The public RSA key. - * - * @throws JOSEException If RSA is not supported by the underlying Java - * Cryptography (JCA) provider or if the JWK - * parameters are invalid for a public RSA key. - */ - public RSAPublicKey toRSAPublicKey() - throws JOSEException { - - BigInteger modulus = n.decodeToBigInteger(); - BigInteger exponent = e.decodeToBigInteger(); - - RSAPublicKeySpec spec = new RSAPublicKeySpec(modulus, exponent); - - try { - KeyFactory factory = KeyFactory.getInstance("RSA"); - - return (RSAPublicKey) factory.generatePublic(spec); - - } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { - - throw new JOSEException(e.getMessage(), e); - } - } - - - /** - * Returns a standard {@code java.security.interfaces.RSAPrivateKey} - * representation of this RSA JWK. - * - * @return The private RSA key, {@code null} if not specified by this - * JWK. - * - * @throws JOSEException If RSA is not supported by the underlying Java - * Cryptography (JCA) provider or if the JWK - * parameters are invalid for a private RSA key. - */ - public RSAPrivateKey toRSAPrivateKey() - throws JOSEException { - - if (d == null) { - // no private key - return null; - } - - BigInteger modulus = n.decodeToBigInteger(); - BigInteger privateExponent = d.decodeToBigInteger(); - - RSAPrivateKeySpec spec; - - if (p == null) { - // Use 1st representation - spec = new RSAPrivateKeySpec(modulus, privateExponent); - - } else { - // Use 2nd (CRT) representation - BigInteger publicExponent = e.decodeToBigInteger(); - BigInteger primeP = p.decodeToBigInteger(); - BigInteger primeQ = q.decodeToBigInteger(); - BigInteger primeExponentP = dp.decodeToBigInteger(); - BigInteger primeExponentQ = dq.decodeToBigInteger(); - BigInteger crtCoefficient = qi.decodeToBigInteger(); - - if (oth != null && ! oth.isEmpty()) { - // Construct other info spec - RSAOtherPrimeInfo[] otherInfo = new RSAOtherPrimeInfo[oth.size()]; - - for (int i=0; i < oth.size(); i++) { - - OtherPrimesInfo opi = oth.get(i); - - BigInteger otherPrime = opi.getPrimeFactor().decodeToBigInteger(); - BigInteger otherPrimeExponent = opi.getFactorCRTExponent().decodeToBigInteger(); - BigInteger otherCrtCoefficient = opi.getFactorCRTCoefficient().decodeToBigInteger(); - - otherInfo[i] = new RSAOtherPrimeInfo(otherPrime, - otherPrimeExponent, - otherCrtCoefficient); - } - - spec = new RSAMultiPrimePrivateCrtKeySpec(modulus, - publicExponent, - privateExponent, - primeP, - primeQ, - primeExponentP, - primeExponentQ, - crtCoefficient, - otherInfo); - } else { - // Construct spec with no other info - spec = new RSAPrivateCrtKeySpec(modulus, - publicExponent, - privateExponent, - primeP, - primeQ, - primeExponentP, - primeExponentQ, - crtCoefficient); - } - } - - try { - KeyFactory factory = KeyFactory.getInstance("RSA"); - - return (RSAPrivateKey) factory.generatePrivate(spec); - - } catch (InvalidKeySpecException | NoSuchAlgorithmException e) { - - throw new JOSEException(e.getMessage(), e); - } - } - - - @Override - public PublicKey toPublicKey() - throws JOSEException { - - return toRSAPublicKey(); - } - - - @Override - public PrivateKey toPrivateKey() - throws JOSEException { - - PrivateKey prv = toRSAPrivateKey(); - - if (prv != null) { - // Return private RSA key with key material - return prv; - } - - // Return private RSA key as PKCS#11 handle, or null - return privateKey; - } - - - /** - * Returns a standard {@code java.security.KeyPair} representation of - * this RSA JWK. - * - * @return The RSA key pair. The private RSA key will be {@code null} - * if not specified. - * - * @throws JOSEException If RSA is not supported by the underlying Java - * Cryptography (JCA) provider or if the JWK - * parameters are invalid for a public and / or - * private RSA key. - */ - @Override - public KeyPair toKeyPair() - throws JOSEException { - - return new KeyPair(toRSAPublicKey(), toPrivateKey()); - } - - - @Override - public boolean matches(final X509Certificate cert) { - - RSAPublicKey certRSAKey; - try { - certRSAKey = (RSAPublicKey) getParsedX509CertChain().get(0).getPublicKey(); - } catch (ClassCastException ex) { - return false; - } - if (! e.decodeToBigInteger().equals(certRSAKey.getPublicExponent())) { - return false; - } - if (! n.decodeToBigInteger().equals(certRSAKey.getModulus())) { - return false; - } - return true; - } - - - @Override - public LinkedHashMap getRequiredParams() { - - // Put mandatory params in sorted order - LinkedHashMap requiredParams = new LinkedHashMap<>(); - requiredParams.put("e", e.toString()); - requiredParams.put("kty", getKeyType().getValue()); - requiredParams.put("n", n.toString()); - return requiredParams; - } - - - @Override - public boolean isPrivate() { - - // Check if 1st or 2nd form params are specified, or PKCS#11 handle - return d != null || p != null || privateKey != null; - } - - - @Override - public int size() { - - try { - return ByteUtils.safeBitLength(n.decode()); - } catch (IntegerOverflowException e) { - throw new ArithmeticException(e.getMessage()); - } - } - - - /** - * Returns a copy of this RSA JWK with any private values removed. - * - * @return The copied public RSA JWK. - */ - @Override - public RSAKey toPublicJWK() { - - return new RSAKey( - getModulus(), getPublicExponent(), - getKeyUse(), getKeyOperations(), getAlgorithm(), getKeyID(), - getX509CertURL(), getX509CertThumbprint(), getX509CertSHA256Thumbprint(), getX509CertChain(), - getKeyStore()); - } - - - @Override - public JSONObject toJSONObject() { - - JSONObject o = super.toJSONObject(); - - // Append public RSA key specific attributes - o.put("n", n.toString()); - o.put("e", e.toString()); - if (d != null) { - o.put("d", d.toString()); - } - if (p != null) { - o.put("p", p.toString()); - } - if (q != null) { - o.put("q", q.toString()); - } - if (dp != null) { - o.put("dp", dp.toString()); - } - if (dq != null) { - o.put("dq", dq.toString()); - } - if (qi != null) { - o.put("qi", qi.toString()); - } - if (oth != null && !oth.isEmpty()) { - - JSONArray a = new JSONArray(); - - for (OtherPrimesInfo other : oth) { - - JSONObject oo = new JSONObject(); - oo.put("r", other.r.toString()); - oo.put("d", other.d.toString()); - oo.put("t", other.t.toString()); - - a.add(oo); - } - - o.put("oth", a); - } - - return o; - } - - - /** - * Parses a public / private RSA JWK from the specified JSON object - * string representation. - * - * @param s The JSON object string to parse. Must not be {@code null}. - * - * @return The public / private RSA JWK. - * - * @throws ParseException If the string couldn't be parsed to an RSA - * JWK. - */ - public static RSAKey parse(final String s) - throws ParseException { - - return parse(JSONObjectUtils.parse(s)); - } - - - /** - * Parses a public / private RSA JWK from the specified JSON object - * representation. - * - * @param jsonObject The JSON object to parse. Must not be - * {@code null}. - * - * @return The public / private RSA Key. - * - * @throws ParseException If the JSON object couldn't be parsed to an - * RSA JWK. - */ - public static RSAKey parse(final JSONObject jsonObject) - throws ParseException { - - // Parse the mandatory public key parameters first - Base64URL n = new Base64URL(JSONObjectUtils.getString(jsonObject, "n")); - Base64URL e = new Base64URL(JSONObjectUtils.getString(jsonObject, "e")); - - // Check key type - KeyType kty = KeyType.parse(JSONObjectUtils.getString(jsonObject, "kty")); - if (kty != KeyType.RSA) { - throw new ParseException("The key type \"kty\" must be RSA", 0); - } - - // Parse the optional private key parameters - - // 1st private representation - Base64URL d = null; - if (jsonObject.containsKey("d")) { - d = new Base64URL(JSONObjectUtils.getString(jsonObject, "d")); - } - - // 2nd private (CRT) representation - Base64URL p = null; - if (jsonObject.containsKey("p")) { - p = new Base64URL(JSONObjectUtils.getString(jsonObject, "p")); - } - Base64URL q = null; - if (jsonObject.containsKey("q")) { - q = new Base64URL(JSONObjectUtils.getString(jsonObject, "q")); - } - Base64URL dp = null; - if (jsonObject.containsKey("dp")) { - dp = new Base64URL(JSONObjectUtils.getString(jsonObject, "dp")); - } - Base64URL dq= null; - if (jsonObject.containsKey("dq")) { - dq = new Base64URL(JSONObjectUtils.getString(jsonObject, "dq")); - } - Base64URL qi = null; - if (jsonObject.containsKey("qi")) { - qi = new Base64URL(JSONObjectUtils.getString(jsonObject, "qi")); - } - - List oth = null; - if (jsonObject.containsKey("oth")) { - - JSONArray arr = JSONObjectUtils.getJSONArray(jsonObject, "oth"); - oth = new ArrayList<>(arr.size()); - - for (Object o : arr) { - - if (o instanceof JSONObject) { - JSONObject otherJson = (JSONObject)o; - - Base64URL r = new Base64URL(JSONObjectUtils.getString(otherJson, "r")); - Base64URL odq = new Base64URL(JSONObjectUtils.getString(otherJson, "dq")); - Base64URL t = new Base64URL(JSONObjectUtils.getString(otherJson, "t")); - - OtherPrimesInfo prime = new OtherPrimesInfo(r, odq, t); - oth.add(prime); - } - } - } - - try { - return new RSAKey(n, e, d, p, q, dp, dq, qi, oth, null, - JWKMetadata.parseKeyUse(jsonObject), - JWKMetadata.parseKeyOperations(jsonObject), - JWKMetadata.parseAlgorithm(jsonObject), - JWKMetadata.parseKeyID(jsonObject), - JWKMetadata.parseX509CertURL(jsonObject), - JWKMetadata.parseX509CertThumbprint(jsonObject), - JWKMetadata.parseX509CertSHA256Thumbprint(jsonObject), - JWKMetadata.parseX509CertChain(jsonObject), - null); - - } catch (IllegalArgumentException ex) { - // Inconsistent 2nd spec, conflicting 'use' and 'key_ops', etc. - throw new ParseException(ex.getMessage(), 0); - } - } - - - /** - * Parses a public RSA JWK from the specified X.509 certificate. - * - *

Important: The X.509 certificate is not - * validated! - * - *

Sets the following JWK parameters: - * - *

    - *
  • The JWK use inferred by {@link KeyUse#from}. - *
  • The JWK ID from the X.509 serial number (in base 10). - *
  • The JWK X.509 certificate chain (this certificate only). - *
  • The JWK X.509 certificate SHA-256 thumbprint. - *
- * - * @param cert The X.509 certificate. Must not be {@code null}. - * - * @return The public RSA key. - * - * @throws JOSEException If parsing failed. - */ - public static RSAKey parse(final X509Certificate cert) - throws JOSEException { - - if (! (cert.getPublicKey() instanceof RSAPublicKey)) { - throw new JOSEException("The public key of the X.509 certificate is not RSA"); - } - - RSAPublicKey publicKey = (RSAPublicKey)cert.getPublicKey(); - - try { - MessageDigest sha256 = MessageDigest.getInstance("SHA-256"); - - return new RSAKey.Builder(publicKey) - .keyUse(KeyUse.from(cert)) - .keyID(cert.getSerialNumber().toString(10)) - .x509CertChain(Collections.singletonList(Base64.encode(cert.getEncoded()))) - .x509CertSHA256Thumbprint(Base64URL.encode(sha256.digest(cert.getEncoded()))) - .build(); - } catch (NoSuchAlgorithmException e) { - throw new JOSEException("Couldn't encode x5t parameter: " + e.getMessage(), e); - } catch (CertificateEncodingException e) { - throw new JOSEException("Couldn't encode x5c parameter: " + e.getMessage(), e); - } - } - - - /** - * Loads a public / private RSA JWK from the specified JCA key store. - * - *

Important: The X.509 certificate is not - * validated! - * - * @param keyStore The key store. Must not be {@code null}. - * @param alias The alias. Must not be {@code null}. - * @param pin The pin to unlock the private key if any, empty or - * {@code null} if not required. - * - * @return The public / private RSA key, {@code null} if no key with - * the specified alias was found. - * - * @throws KeyStoreException On a key store exception. - * @throws JOSEException If RSA key loading failed. - */ - public static RSAKey load(final KeyStore keyStore, - final String alias, - final char[] pin) - throws KeyStoreException, JOSEException { - - java.security.cert.Certificate cert = keyStore.getCertificate(alias); - - if (cert == null || ! (cert instanceof X509Certificate)) { - return null; - } - - X509Certificate x509Cert = (X509Certificate)cert; - - if (! (x509Cert.getPublicKey() instanceof RSAPublicKey)) { - throw new JOSEException("Couldn't load RSA JWK: The key algorithm is not RSA"); - } - - RSAKey rsaJWK = RSAKey.parse(x509Cert); - - // Let kid=alias - rsaJWK = new RSAKey.Builder(rsaJWK).keyID(alias).keyStore(keyStore).build(); - - // Check for private counterpart - Key key; - try { - key = keyStore.getKey(alias, pin); - } catch (UnrecoverableKeyException | NoSuchAlgorithmException e) { - throw new JOSEException("Couldn't retrieve private RSA key (bad pin?): " + e.getMessage(), e); - } - - if (key instanceof RSAPrivateKey) { - // Simple file based key store - return new RSAKey.Builder(rsaJWK) - .privateKey((RSAPrivateKey)key) - .build(); - } else if (key instanceof PrivateKey && "RSA".equalsIgnoreCase(key.getAlgorithm())) { - // PKCS#11 store - return new RSAKey.Builder(rsaJWK) - .privateKey((PrivateKey)key) - .build(); - } else { - return rsaJWK; - } - } - - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof RSAKey)) return false; - if (!super.equals(o)) return false; - RSAKey rsaKey = (RSAKey) o; - return Objects.equals(n, rsaKey.n) && - Objects.equals(e, rsaKey.e) && - Objects.equals(d, rsaKey.d) && - Objects.equals(p, rsaKey.p) && - Objects.equals(q, rsaKey.q) && - Objects.equals(dp, rsaKey.dp) && - Objects.equals(dq, rsaKey.dq) && - Objects.equals(qi, rsaKey.qi) && - Objects.equals(oth, rsaKey.oth) && - Objects.equals(privateKey, rsaKey.privateKey); - } - - - @Override - public int hashCode() { - return Objects.hash(super.hashCode(), n, e, d, p, q, dp, dq, qi, oth, privateKey); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/SecretJWK.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/SecretJWK.java deleted file mode 100644 index 08c08b30d..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/SecretJWK.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * 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.jwk; - - -import javax.crypto.SecretKey; - - -/** - * Secret (symmetric) JSON Web Key (JWK). - * - * @author Vladimir Dzhuvinov - * @version 2015-12-08 - */ -public interface SecretJWK { - - - /** - * Returns a Java secret key representation of the JWK. - * - * @return The Java secret key. - */ - SecretKey toSecretKey(); -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/ThumbprintUtils.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/ThumbprintUtils.java deleted file mode 100644 index ea9a49e8d..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/ThumbprintUtils.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * 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.jwk; - - -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.LinkedHashMap; - -import com.nimbusds.jose.JOSEException; -import com.nimbusds.jose.util.Base64URL; -import com.nimbusds.jose.util.StandardCharset; -import net.minidev.json.JSONObject; - - -/** - * Thumbprint utilities. - * - *

See RFC 7638. - * - * @author Vladimir Dzhuvinov - * @version 2016-07-26 - */ -public final class ThumbprintUtils { - - - /** - * Computes the SHA-256 thumbprint for the specified JWK. - * - * @param jwk The JWK. Must not be {@code null}. - * - * @return The JWK thumbprint. - * - * @throws JOSEException If the SHA-256 hash algorithm is not - * supported. - */ - public static Base64URL compute(final JWK jwk) - throws JOSEException { - - return compute("SHA-256", jwk); - } - - - /** - * Computes the thumbprint for the specified JWK. - * - * @param hashAlg The hash algorithm. Must not be {@code null}. - * @param jwk The JWK. Must not be {@code null}. - * - * @return The JWK thumbprint. - * - * @throws JOSEException If the hash algorithm is not supported. - */ - public static Base64URL compute(final String hashAlg, final JWK jwk) - throws JOSEException { - - final LinkedHashMap orderedParams = jwk.getRequiredParams(); - - return compute(hashAlg, orderedParams); - } - - - /** - * Computes the thumbprint for the specified required JWK parameters. - * - * @param hashAlg The hash algorithm. Must not be {@code null}. - * @param params The required JWK parameters, alphanumerically sorted - * by parameter name and ready for JSON object - * serialisation. Must not be {@code null}. - * - * @return The JWK thumbprint. - * - * @throws JOSEException If the hash algorithm is not supported. - */ - public static Base64URL compute(final String hashAlg, final LinkedHashMap params) - throws JOSEException { - - final String json = JSONObject.toJSONString(params); - - final MessageDigest md; - - try { - md = MessageDigest.getInstance(hashAlg); - - } catch (NoSuchAlgorithmException e) { - - throw new JOSEException("Couldn't compute JWK thumbprint: Unsupported hash algorithm: " + e.getMessage(), e); - } - - md.update(json.getBytes(StandardCharset.UTF_8)); - - return Base64URL.encode(md.digest()); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/gen/ECKeyGenerator.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/gen/ECKeyGenerator.java deleted file mode 100644 index af36f7a00..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/gen/ECKeyGenerator.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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.jwk.gen; - - -import java.security.InvalidAlgorithmParameterException; -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.NoSuchAlgorithmException; -import java.security.interfaces.ECPrivateKey; -import java.security.interfaces.ECPublicKey; -import java.security.spec.ECParameterSpec; - -import com.nimbusds.jose.JOSEException; -import com.nimbusds.jose.jwk.Curve; -import com.nimbusds.jose.jwk.ECKey; - - -/** - * Elliptic Curve (EC) JSON Web Key (JWK) generator. - * - *

Supported curves: - * - *

    - *
  • {@link Curve#P_256 P-256} - *
  • {@link Curve#P_256K P-256K} - *
  • {@link Curve#P_384 P-384} - *
  • {@link Curve#P_521 P-512} - *
- * - * @author Vladimir Dzhuvinov - * @version 2018-07-15 - */ -public class ECKeyGenerator extends JWKGenerator { - - - /** - * The curve. - */ - private final Curve crv; - - - /** - * Creates a new EC JWK generator. - * - * @param crv The curve. Must not be {@code null}. - */ - public ECKeyGenerator(final Curve crv) { - - if (crv == null) { - throw new IllegalArgumentException("The curve must not be null"); - } - this.crv = crv; - } - - - @Override - public ECKey generate() - throws JOSEException { - - ECParameterSpec ecSpec = crv.toECParameterSpec(); - - KeyPairGenerator generator; - try { - if (keyStore != null) { - // For PKCS#11 - generator = KeyPairGenerator.getInstance("EC", keyStore.getProvider()); - } else { - generator = KeyPairGenerator.getInstance("EC"); - } - generator.initialize(ecSpec); - } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException e) { - throw new JOSEException(e.getMessage(), e); - } - - KeyPair kp = generator.generateKeyPair(); - - ECPublicKey pub = (ECPublicKey) kp.getPublic(); - ECPrivateKey priv = (ECPrivateKey) kp.getPrivate(); - - ECKey.Builder builder = new ECKey.Builder(crv, pub) - .privateKey(priv) - .keyUse(use) - .keyOperations(ops) - .algorithm(alg) - .keyStore(keyStore); - - if (x5tKid) { - builder.keyIDFromThumbprint(); - } else { - builder.keyID(kid); - } - - return builder.build(); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/gen/JWKGenerator.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/gen/JWKGenerator.java deleted file mode 100644 index da50458c9..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/gen/JWKGenerator.java +++ /dev/null @@ -1,184 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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.jwk.gen; - - -import java.security.KeyStore; -import java.util.Set; - -import com.nimbusds.jose.Algorithm; -import com.nimbusds.jose.JOSEException; -import com.nimbusds.jose.jwk.JWK; -import com.nimbusds.jose.jwk.JWKSet; -import com.nimbusds.jose.jwk.KeyOperation; -import com.nimbusds.jose.jwk.KeyUse; - - -/** - * Abstract JWK generator. - * - * @author Vladimir Dzhuvinov - * @version 2018-09-07 - */ -public abstract class JWKGenerator { - - - /** - * The key use, optional. - */ - protected KeyUse use; - - - /** - * The key operations, optional. - */ - protected Set ops; - - - /** - * The intended JOSE algorithm for the key, optional. - */ - protected Algorithm alg; - - - /** - * The key ID, optional. - */ - protected String kid; - - - /** - * If {@code true} sets the ID of the JWK to the SHA-256 thumbprint of - * the JWK. - */ - protected boolean x5tKid; - - - /** - * Reference to the underlying key store, {@code null} if none. - */ - protected KeyStore keyStore; - - - /** - * Sets the use ({@code use}) of the JWK. - * - * @param use The key use, {@code null} if not specified or if - * the key is intended for signing as well as - * encryption. - * - * @return This generator. - */ - public JWKGenerator keyUse(final KeyUse use) { - - this.use = use; - return this; - } - - - /** - * Sets the operations ({@code key_ops}) of the JWK. - * - * @param ops The key operations, {@code null} if not - * specified. - * - * @return This generator. - */ - public JWKGenerator keyOperations(final Set ops) { - - this.ops = ops; - return this; - } - - - /** - * Sets the intended JOSE algorithm ({@code alg}) for the JWK. - * - * @param alg The intended JOSE algorithm, {@code null} if not - * specified. - * - * @return This generator. - */ - public JWKGenerator algorithm(final Algorithm alg) { - - this.alg = alg; - return this; - } - - /** - * Sets the ID ({@code kid}) of the JWK. The key ID can be used - * to match a specific key. This can be used, for instance, to - * choose a key within a {@link JWKSet} during key rollover. - * The key ID may also correspond to a JWS/JWE {@code kid} - * header parameter value. - * - * @param kid The key ID, {@code null} if not specified. - * - * @return This generator. - */ - public JWKGenerator keyID(final String kid) { - - this.kid = kid; - return this; - } - - - /** - * Sets the ID ({@code kid}) of the JWK to its SHA-256 JWK - * thumbprint (RFC 7638). The key ID can be used to match a - * specific key. This can be used, for instance, to choose a - * key within a {@link JWKSet} during key rollover. The key ID - * may also correspond to a JWS/JWE {@code kid} header - * parameter value. - * - * @param x5tKid If {@code true} sets the ID of the JWK to the SHA-256 - * JWK thumbprint. - * - * @return This generator. - */ - public JWKGenerator keyIDFromThumbprint(final boolean x5tKid) { - - this.x5tKid = x5tKid; - return this; - } - - - /** - * Sets the underlying key store. - * - * @param keyStore Reference to the underlying key store, - * {@code null} if none. - * - * @return This generator. - */ - public JWKGenerator keyStore(final KeyStore keyStore) { - - this.keyStore = keyStore; - return this; - } - - - /** - * Generates the JWK according to the set parameters. - * - * @return The generated JWK. - * - * @throws JOSEException If the key generation failed. - */ - public abstract T generate() throws JOSEException; -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/gen/OctetKeyPairGenerator.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/gen/OctetKeyPairGenerator.java deleted file mode 100644 index 73e986e5e..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/gen/OctetKeyPairGenerator.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2018, Connect2id Ltd and contributors. - * - * 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.jwk.gen; - -import java.security.GeneralSecurityException; -import java.security.InvalidKeyException; -import java.util.Collections; -import java.util.LinkedHashSet; -import java.util.Set; - -import com.google.crypto.tink.subtle.Ed25519Sign; -import com.google.crypto.tink.subtle.X25519; -import com.nimbusds.jose.JOSEException; -import com.nimbusds.jose.jwk.Curve; -import com.nimbusds.jose.jwk.OctetKeyPair; -import com.nimbusds.jose.util.Base64URL; - - -/** - * Octet Key Pair (OKP) JSON Web Key (JWK) generator. - * - *

Supported curves: - * - *

    - *
  • {@link Curve#X25519 X25519} - *
  • {@link Curve#Ed25519 Ed25519} - *
- * - * @author Tim McLean - * @version 2018-07-18 - */ -public class OctetKeyPairGenerator extends JWKGenerator { - - - /** - * The curve. - */ - private final Curve crv; - - - /** - * The supported values for the "crv" property. - */ - public static final Set SUPPORTED_CURVES; - - - static { - Set curves = new LinkedHashSet<>(); - curves.add(Curve.X25519); - curves.add(Curve.Ed25519); - SUPPORTED_CURVES = Collections.unmodifiableSet(curves); - } - - - /** - * Creates a new OctetKeyPair JWK generator. - * - * @param crv The curve. Must not be {@code null}. - */ - public OctetKeyPairGenerator(final Curve crv) { - - if (crv == null) { - throw new IllegalArgumentException("The curve must not be null"); - } - - if (! SUPPORTED_CURVES.contains(crv)) { - throw new IllegalArgumentException("Curve not supported for OKP generation"); - } - - this.crv = crv; - } - - - @Override - public OctetKeyPair generate() - throws JOSEException { - - final Base64URL privateKey; - final Base64URL publicKey; - - if (this.crv.equals(Curve.X25519)) { - - final byte[] privateKeyBytes; - final byte[] publicKeyBytes; - - try { - privateKeyBytes = X25519.generatePrivateKey(); - publicKeyBytes = X25519.publicFromPrivate(privateKeyBytes); - - } catch (InvalidKeyException e) { - // internal Tink error, should not happen - throw new JOSEException(e.getMessage(), e); - } - - privateKey = Base64URL.encode(privateKeyBytes); - publicKey = Base64URL.encode(publicKeyBytes); - - } else if (this.crv.equals(Curve.Ed25519)) { - - final Ed25519Sign.KeyPair tinkKeyPair; - - try { - tinkKeyPair = Ed25519Sign.KeyPair.newKeyPair(); - - } catch (GeneralSecurityException e) { - // internal Tink error, should not happen - throw new JOSEException(e.getMessage(), e); - } - - privateKey = Base64URL.encode(tinkKeyPair.getPrivateKey()); - publicKey = Base64URL.encode(tinkKeyPair.getPublicKey()); - - } else { - - throw new JOSEException("Curve not supported"); - } - - OctetKeyPair.Builder builder = new OctetKeyPair.Builder(crv, publicKey) - .d(privateKey) - .keyUse(use) - .keyOperations(ops) - .algorithm(alg); - - if (x5tKid) { - builder.keyIDFromThumbprint(); - } else { - builder.keyID(kid); - } - - return builder.build(); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/gen/OctetSequenceKeyGenerator.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/gen/OctetSequenceKeyGenerator.java deleted file mode 100644 index 0c3a6feb1..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/gen/OctetSequenceKeyGenerator.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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.jwk.gen; - - -import java.security.SecureRandom; - -import com.nimbusds.jose.JOSEException; -import com.nimbusds.jose.jwk.OctetSequenceKey; -import com.nimbusds.jose.util.Base64URL; - - -/** - * Octet sequence JSON Web Key (JWK) generator. - * - * @author Vladimir Dzhuvinov - * @version 2018-07-20 - */ -public class OctetSequenceKeyGenerator extends JWKGenerator { - - - /** - * The minimum size of generated keys. - */ - public static final int MIN_KEY_SIZE_BITS = 112; - - - /** - * The key size, in bits. - */ - private final int size; - - - /** - * The secure random generator to use, {@code null} to use the default - * one. - */ - private SecureRandom secureRandom; - - - /** - * Creates a new octet sequence JWK generator. - * - * @param size The key size, in bits. Must be at least 112 bits long - * for sufficient entropy. - */ - public OctetSequenceKeyGenerator(final int size) { - if (size < MIN_KEY_SIZE_BITS) { - throw new IllegalArgumentException("The key size must be at least " + MIN_KEY_SIZE_BITS + " bits"); - } - if (size % 8 != 0) { - throw new IllegalArgumentException("The key size in bits must be divisible by 8"); - } - this.size = size; - } - - - /** - * Sets the secure random generator to use. - * - * @param secureRandom The secure random generator to use, {@code null} - * to use the default one. - * - * @return This generator. - */ - public OctetSequenceKeyGenerator secureRandom(final SecureRandom secureRandom) { - - this.secureRandom = secureRandom; - return this; - } - - - @Override - public OctetSequenceKey generate() - throws JOSEException { - - byte[] keyMaterial = new byte[size / 8]; - - if (secureRandom != null) { - secureRandom.nextBytes(keyMaterial); - } else { - // The default random gen - new SecureRandom().nextBytes(keyMaterial); - } - - OctetSequenceKey.Builder builder = new OctetSequenceKey.Builder(Base64URL.encode(keyMaterial)) - .keyUse(use) - .keyOperations(ops) - .algorithm(alg) - .keyStore(keyStore); - - if (x5tKid) { - builder.keyIDFromThumbprint(); - } else { - builder.keyID(kid); - } - - return builder.build(); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/gen/RSAKeyGenerator.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/gen/RSAKeyGenerator.java deleted file mode 100644 index 17c7c97d1..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/gen/RSAKeyGenerator.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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.jwk.gen; - - -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.NoSuchAlgorithmException; -import java.security.interfaces.RSAPrivateKey; -import java.security.interfaces.RSAPublicKey; - -import com.nimbusds.jose.JOSEException; -import com.nimbusds.jose.jwk.RSAKey; - - -/** - * RSA JSON Web Key (JWK) generator. - * - * @author Vladimir Dzhuvinov - * @version 2018-07-20 - */ -public class RSAKeyGenerator extends JWKGenerator { - - - /** - * The minimum size of generated keys. - */ - public static final int MIN_KEY_SIZE_BITS = 2048; - - - /** - * The RSA key size, in bits. - */ - private final int size; - - - /** - * Creates a new RSA JWK generator. - * - * @param size The RSA key size, in bits. Must be at least 2048 bits - * long for sufficient strength. - */ - public RSAKeyGenerator(final int size) { - - this(size, false); - } - - - /** - * Creates a new RSA JWK generator. - * - * @param size The RSA key size, in bits. Must be at least - * 2048 bits long for sufficient strength. - * @param allowWeakKeys {@code true} to allow generation of keys - * shorter than 2048 bits. - */ - public RSAKeyGenerator(final int size, final boolean allowWeakKeys) { - - if (! allowWeakKeys && size < MIN_KEY_SIZE_BITS) { - throw new IllegalArgumentException("The key size must be at least " + MIN_KEY_SIZE_BITS + " bits"); - } - this.size = size; - } - - - @Override - public RSAKey generate() - throws JOSEException { - - KeyPairGenerator generator; - try { - if (keyStore != null) { - // For PKCS#11 - generator = KeyPairGenerator.getInstance("RSA", keyStore.getProvider()); - } else { - generator = KeyPairGenerator.getInstance("RSA"); - } - generator.initialize(size); - } catch (NoSuchAlgorithmException e) { - throw new JOSEException(e.getMessage(), e); - } - - KeyPair kp = generator.generateKeyPair(); - - RSAPublicKey pub = (RSAPublicKey) kp.getPublic(); - RSAPrivateKey priv = (RSAPrivateKey) kp.getPrivate(); - - RSAKey.Builder builder = new RSAKey.Builder(pub) - .privateKey(priv) - .keyUse(use) - .keyOperations(ops) - .algorithm(alg) - .keyStore(keyStore); - - if (x5tKid) { - builder.keyIDFromThumbprint(); - } else { - builder.keyID(kid); - } - - return builder.build(); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/gen/package-info.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/gen/package-info.java deleted file mode 100644 index 7798ee2fe..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/gen/package-info.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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. - */ -/** - * Key generation utilities. - */ -package com.nimbusds.jose.jwk.gen; \ No newline at end of file diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/package-info.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/package-info.java deleted file mode 100644 index eae81217c..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/package-info.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * 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. - */ - -/** - * JSON Web Key (JWK) classes. - * - *

This package provides representation, serialisation and parsing of - * Elliptic Curve (EC), RSA and symmetric JWKs. - * - *

References: - * - *

- */ -package com.nimbusds.jose.jwk; \ No newline at end of file diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/source/DefaultJWKSetCache.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/source/DefaultJWKSetCache.java deleted file mode 100644 index d69c7d21c..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/source/DefaultJWKSetCache.java +++ /dev/null @@ -1,161 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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.jwk.source; - - -import java.util.Date; -import java.util.concurrent.TimeUnit; - -import com.nimbusds.jose.jwk.JWKSet; - - -/** - * JSON Web Key (JWK) set cache implementation. - * - * @author Vladimir Dzhuvinov - * @version 2018-12-01 - */ -public class DefaultJWKSetCache implements JWKSetCache { - - - /** - * The default lifespan for cached JWK sets (5 minutes). - */ - public static final long DEFAULT_LIFESPAN_MINUTES = 5; - - - /** - * The lifespan the cached JWK set, in {@link #timeUnit}s, negative - * means no expiration - */ - private final long lifespan; - - - /** - * The lifespan time unit, may be {@code null} if no expiration. - */ - private final TimeUnit timeUnit; - - - /** - * The cache put timestamp, negative if not specified. - */ - private long putTimestamp = -1; - - - /** - * Creates a new JWK set, the default lifespan of the cached JWK set is - * set to 5 minutes. - */ - public DefaultJWKSetCache() { - - this(DEFAULT_LIFESPAN_MINUTES, TimeUnit.MINUTES); - } - - - /** - * Creates a new JWK set cache. - * - * @param lifespan The lifespan of the cached JWK set before it - * expires, negative means no expiration. - * @param timeUnit The lifespan time unit, may be {@code null} if no - * expiration. - */ - public DefaultJWKSetCache(final long lifespan, final TimeUnit timeUnit) { - - this.lifespan = lifespan; - - if (lifespan > -1 && timeUnit == null) { - throw new IllegalArgumentException("A time unit must be specified for non-negative lifespans"); - } - - this.timeUnit = timeUnit; - } - - - /** - * The cached JWK set, {@code null} if none. - */ - private JWKSet jwkSet; - - - @Override - public void put(final JWKSet jwkSet) { - - this.jwkSet = jwkSet; - - if (jwkSet != null) { - putTimestamp = new Date().getTime(); - } else { - // cache cleared - putTimestamp = -1; - } - } - - - @Override - public JWKSet get() { - - if (isExpired()) { - jwkSet = null; // clear - } - - return jwkSet; - } - - - /** - * Returns the cache put timestamp. - * - * @return The cache put timestamp, negative if not specified. - */ - public long getPutTimestamp() { - - return putTimestamp; - } - - - /** - * Returns {@code true} if the cached JWK set is expired. - * - * @return {@code true} if expired. - */ - public boolean isExpired() { - - return putTimestamp > -1 && - lifespan > -1 && - new Date().getTime() > putTimestamp + TimeUnit.MILLISECONDS.convert(lifespan, timeUnit); - } - - - /** - * Returns the configured lifespan of the cached JWK. - * - * @param timeUnit The time unit to use. - * - * @return The configured lifespan, negative means no expiration. - */ - public long getLifespan(final TimeUnit timeUnit) { - - if (lifespan < 0) { - return lifespan; - } - - return timeUnit.convert(lifespan, timeUnit); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/source/ImmutableJWKSet.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/source/ImmutableJWKSet.java deleted file mode 100644 index 11d94ae47..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/source/ImmutableJWKSet.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * 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.jwk.source; - - -import java.util.List; - -import com.nimbusds.jose.jwk.JWK; -import com.nimbusds.jose.jwk.JWKSelector; -import com.nimbusds.jose.jwk.JWKSet; -import com.nimbusds.jose.proc.SecurityContext; -import net.jcip.annotations.Immutable; - - -/** - * JSON Web Key (JWK) source backed by an immutable JWK set. - * - * @author Vladimir Dzhuvinov - * @version 2016-04-10 - */ -@Immutable -public class ImmutableJWKSet implements JWKSource { - - - /** - * The JWK set. - */ - private final JWKSet jwkSet; - - - /** - * Creates a new JWK source backed by an immutable JWK set. - * - * @param jwkSet The JWK set. Must not be {@code null}. - */ - public ImmutableJWKSet(final JWKSet jwkSet) { - if (jwkSet == null) { - throw new IllegalArgumentException("The JWK set must not be null"); - } - this.jwkSet = jwkSet; - } - - - /** - * Returns the JWK set. - * - * @return The JWK set. - */ - public JWKSet getJWKSet() { - return jwkSet; - } - - - /** - * {@inheritDoc} The security context is ignored. - */ - @Override - public List get(final JWKSelector jwkSelector, final C context) { - - return jwkSelector.select(jwkSet); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/source/ImmutableSecret.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/source/ImmutableSecret.java deleted file mode 100644 index db46b956f..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/source/ImmutableSecret.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * 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.jwk.source; - - -import javax.crypto.SecretKey; - -import com.nimbusds.jose.jwk.JWKSet; -import com.nimbusds.jose.jwk.OctetSequenceKey; -import com.nimbusds.jose.proc.SecurityContext; -import net.jcip.annotations.Immutable; - - -/** - * JSON Web Key (JWK) source backed by an immutable secret. - * - * @author Vladimir Dzhuvinov - * @version 2016-04-10 - */ -@Immutable -public class ImmutableSecret extends ImmutableJWKSet { - - - /** - * Creates a new JSON Web Key (JWK) source backed by an immutable - * secret. - * - * @param secret The secret. Must not be empty or {@code null}. - */ - public ImmutableSecret(final byte[] secret) { - - super(new JWKSet(new OctetSequenceKey.Builder(secret).build())); - } - - - /** - * Creates a new JSON Web Key (JWK) source backed by an immutable - * secret key. - * - * @param secretKey The secret key. Must not be {@code null}. - */ - public ImmutableSecret(final SecretKey secretKey) { - - super(new JWKSet(new OctetSequenceKey.Builder(secretKey).build())); - } - - - /** - * Returns the secret. - * - * @return The secret. - */ - public byte[] getSecret() { - - return ((OctetSequenceKey) getJWKSet().getKeys().get(0)).toByteArray(); - } - - - /** - * Returns the secret key. - * - * @return The secret key. - */ - public SecretKey getSecretKey() { - - return ((OctetSequenceKey) getJWKSet().getKeys().get(0)).toSecretKey(); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/source/JWKSecurityContextJWKSet.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/source/JWKSecurityContextJWKSet.java deleted file mode 100644 index 28428e56e..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/source/JWKSecurityContextJWKSet.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2019, Connect2id Ltd and contributors. - * - * 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.jwk.source; - -import java.util.List; - -import com.nimbusds.jose.KeySourceException; -import com.nimbusds.jose.jwk.JWK; -import com.nimbusds.jose.jwk.JWKSelector; -import com.nimbusds.jose.jwk.JWKSet; -import com.nimbusds.jose.proc.JWKSecurityContext; - - -/** - * A {@link JWKSource} backed by keys found in the {@link JWKSecurityContext}. - * - * @author Rob Winch - * @author Josh Cummings - * @version 2019-01-10 - */ -public class JWKSecurityContextJWKSet implements JWKSource { - - /** - * {@inheritDoc} - */ - @Override - public List get(final JWKSelector jwkSelector, final JWKSecurityContext context) throws KeySourceException { - if (context == null) { - throw new IllegalArgumentException("Security Context must not be null"); - } - - return jwkSelector.select(new JWKSet(context.getKeys())); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/source/JWKSetCache.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/source/JWKSetCache.java deleted file mode 100644 index dd6ca391b..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/source/JWKSetCache.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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.jwk.source; - - -import com.nimbusds.jose.jwk.JWKSet; - - -/** - * JSON Web Key (JWK) set cache. - * - * @author Vladimir Dzhuvinov - * @version 2018-10-28 - */ -public interface JWKSetCache { - - - /** - * Puts the specified JWK set into the cache or clears the cache. - * - * @param jwkSet The JWK set to cache, {@code null} to clear the cache. - */ - void put(final JWKSet jwkSet); - - - /** - * Gets the cached JWK set. - * - * @return The cached JWK set, {@code null} if none or expired. - */ - JWKSet get(); -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/source/JWKSource.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/source/JWKSource.java deleted file mode 100644 index dedbd8b2e..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/source/JWKSource.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * 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.jwk.source; - - -import java.util.List; - -import com.nimbusds.jose.KeySourceException; -import com.nimbusds.jose.jwk.JWK; -import com.nimbusds.jose.jwk.JWKSelector; -import com.nimbusds.jose.proc.SecurityContext; - - -/** - * JSON Web Key (JWK) source. Exposes a method for retrieving JWKs matching a - * specified selector. An optional context parameter is available to facilitate - * passing of additional data between the caller and the underlying JWK source - * (in both directions). Implementations must be thread-safe. - * - * @author Vladimir Dzhuvinov - * @version 2016-06-21 - */ -public interface JWKSource { - - - /** - * Retrieves a list of JWKs matching the specified selector. - * - * @param jwkSelector A JWK selector. Must not be {@code null}. - * @param context Optional context, {@code null} if not required. - * - * @return The matching JWKs, empty list if no matches were found. - * - * @throws KeySourceException If key sourcing failed. - */ - List get(final JWKSelector jwkSelector, final C context) - throws KeySourceException; -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/source/RemoteJWKSet.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/source/RemoteJWKSet.java deleted file mode 100644 index f509b595e..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/source/RemoteJWKSet.java +++ /dev/null @@ -1,294 +0,0 @@ -/* - * 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.jwk.source; - - -import java.io.IOException; -import java.net.URL; -import java.util.Collections; -import java.util.List; -import java.util.Set; - -import com.nimbusds.jose.RemoteKeySourceException; -import com.nimbusds.jose.jwk.JWK; -import com.nimbusds.jose.jwk.JWKMatcher; -import com.nimbusds.jose.jwk.JWKSelector; -import com.nimbusds.jose.jwk.JWKSet; -import com.nimbusds.jose.proc.SecurityContext; -import com.nimbusds.jose.util.DefaultResourceRetriever; -import com.nimbusds.jose.util.Resource; -import com.nimbusds.jose.util.ResourceRetriever; -import net.jcip.annotations.ThreadSafe; - - -/** - * Remote JSON Web Key (JWK) source specified by a JWK set URL. The retrieved - * JWK set is cached to minimise network calls. The cache is updated whenever - * the key selector tries to get a key with an unknown ID. - * - * @author Vladimir Dzhuvinov - * @version 2018-10-28 - */ -@ThreadSafe -public class RemoteJWKSet implements JWKSource { - - - /** - * The default HTTP connect timeout for JWK set retrieval, in - * milliseconds. Set to 250 milliseconds. - */ - public static final int DEFAULT_HTTP_CONNECT_TIMEOUT = 250; - - - /** - * The default HTTP read timeout for JWK set retrieval, in - * milliseconds. Set to 250 milliseconds. - */ - public static final int DEFAULT_HTTP_READ_TIMEOUT = 250; - - - /** - * The default HTTP entity size limit for JWK set retrieval, in bytes. - * Set to 50 KBytes. - */ - public static final int DEFAULT_HTTP_SIZE_LIMIT = 50 * 1024; - - - /** - * The JWK set URL. - */ - private final URL jwkSetURL; - - - /** - * The JWK set cache. - */ - private final JWKSetCache jwkSetCache; - - - /** - * The JWK set retriever. - */ - private final ResourceRetriever jwkSetRetriever; - - - /** - * Creates a new remote JWK set using the - * {@link DefaultResourceRetriever default HTTP resource retriever}, - * with a HTTP connect timeout set to 250 ms, HTTP read timeout set to - * 250 ms and a 50 KByte size limit. - * - * @param jwkSetURL The JWK set URL. Must not be {@code null}. - */ - public RemoteJWKSet(final URL jwkSetURL) { - this(jwkSetURL, null); - } - - - /** - * Creates a new remote JWK set. - * - * @param jwkSetURL The JWK set URL. Must not be {@code null}. - * @param resourceRetriever The HTTP resource retriever to use, - * {@code null} to use the - * {@link DefaultResourceRetriever default - * one}. - */ - public RemoteJWKSet(final URL jwkSetURL, - final ResourceRetriever resourceRetriever) { - - this(jwkSetURL, resourceRetriever, null); - } - - - /** - * Creates a new remote JWK set. - * - * @param jwkSetURL The JWK set URL. Must not be {@code null}. - * @param resourceRetriever The HTTP resource retriever to use, - * {@code null} to use the - * {@link DefaultResourceRetriever default - * one}. - * @param jwkSetCache The JWK set cache to use, {@code null} to - * use the {@link DefaultJWKSetCache default - * one}. - */ - public RemoteJWKSet(final URL jwkSetURL, - final ResourceRetriever resourceRetriever, - final JWKSetCache jwkSetCache) { - - if (jwkSetURL == null) { - throw new IllegalArgumentException("The JWK set URL must not be null"); - } - this.jwkSetURL = jwkSetURL; - - if (resourceRetriever != null) { - jwkSetRetriever = resourceRetriever; - } else { - jwkSetRetriever = new DefaultResourceRetriever(DEFAULT_HTTP_CONNECT_TIMEOUT, DEFAULT_HTTP_READ_TIMEOUT, DEFAULT_HTTP_SIZE_LIMIT); - } - - if (jwkSetCache != null) { - this.jwkSetCache = jwkSetCache; - } else { - this.jwkSetCache = new DefaultJWKSetCache(); - } - } - - - /** - * Updates the cached JWK set from the configured URL. - * - * @return The updated JWK set. - * - * @throws RemoteKeySourceException If JWK retrieval failed. - */ - private JWKSet updateJWKSetFromURL() - throws RemoteKeySourceException { - Resource res; - try { - res = jwkSetRetriever.retrieveResource(jwkSetURL); - } catch (IOException e) { - throw new RemoteKeySourceException("Couldn't retrieve remote JWK set: " + e.getMessage(), e); - } - JWKSet jwkSet; - try { - jwkSet = JWKSet.parse(res.getContent()); - } catch (java.text.ParseException e) { - throw new RemoteKeySourceException("Couldn't parse remote JWK set: " + e.getMessage(), e); - } - jwkSetCache.put(jwkSet); - return jwkSet; - } - - - /** - * Returns the JWK set URL. - * - * @return The JWK set URL. - */ - public URL getJWKSetURL() { - - return jwkSetURL; - } - - - /** - * Returns the HTTP resource retriever. - * - * @return The HTTP resource retriever. - */ - public ResourceRetriever getResourceRetriever() { - - return jwkSetRetriever; - } - - - /** - * Returns the configured JWK set cache. - * - * @return The JWK set cache. - */ - public JWKSetCache getJWKSetCache() { - - return jwkSetCache; - } - - - /** - * Returns the cached JWK set. - * - * @return The cached JWK set, {@code null} if none or expired. - */ - public JWKSet getCachedJWKSet() { - - return jwkSetCache.get(); - } - - - /** - * Returns the first specified key ID (kid) for a JWK matcher. - * - * @param jwkMatcher The JWK matcher. Must not be {@code null}. - * - * @return The first key ID, {@code null} if none. - */ - protected static String getFirstSpecifiedKeyID(final JWKMatcher jwkMatcher) { - - Set keyIDs = jwkMatcher.getKeyIDs(); - - if (keyIDs == null || keyIDs.isEmpty()) { - return null; - } - - for (String id: keyIDs) { - if (id != null) { - return id; - } - } - return null; // No kid in matcher - } - - - /** - * {@inheritDoc} The security context is ignored. - */ - @Override - public List get(final JWKSelector jwkSelector, final C context) - throws RemoteKeySourceException { - - // Get the JWK set, may necessitate a cache update - JWKSet jwkSet = jwkSetCache.get(); - if (jwkSet == null) { - jwkSet = updateJWKSetFromURL(); - } - - // Run the selector on the JWK set - List matches = jwkSelector.select(jwkSet); - - if (! matches.isEmpty()) { - // Success - return matches; - } - - // Refresh the JWK set if the sought key ID is not in the cached JWK set - - // Looking for JWK with specific ID? - String soughtKeyID = getFirstSpecifiedKeyID(jwkSelector.getMatcher()); - if (soughtKeyID == null) { - // No key ID specified, return no matches - return Collections.emptyList(); - } - - if (jwkSet.getKeyByKeyId(soughtKeyID) != null) { - // The key ID exists in the cached JWK set, matching - // failed for some other reason, return no matches - return Collections.emptyList(); - } - - // Make new HTTP GET to the JWK set URL - jwkSet = updateJWKSetFromURL(); - if (jwkSet == null) { - // Retrieval has failed - return Collections.emptyList(); - } - - // Repeat select, return final result (success or no matches) - return jwkSelector.select(jwkSet); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/source/package-info.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/source/package-info.java deleted file mode 100644 index 8c86ecfbc..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/jwk/source/package-info.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * 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. - */ - -/** - * Interface and utilities for sourcing JSON Web Keys (JWKs). Typical sources - * can be a local text file containing a JWK set, a JWK set specified by URL, a - * Java keystore, or a database. - */ -package com.nimbusds.jose.jwk.source; \ No newline at end of file diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/package-info.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/package-info.java deleted file mode 100644 index a1c71c035..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/package-info.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * 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. - */ - -/** - * Javascript Object Signing and Encryption (JOSE) classes. - * - *

This package provides representation, compact serialisation and parsing - * for the following JOSE objects: - * - *

    - *
  • {@link com.nimbusds.jose.PlainObject Unsecured ({@code alg=none}) - * JOSE objects}. - *
  • {@link com.nimbusds.jose.JWSObject JSON Web Signature (JWS) - * objects}. - *
  • {@link com.nimbusds.jose.JWEObject JSON Web Encryption (JWE) - * objects}. - *
- * - *

References: - * - *

- */ -package com.nimbusds.jose; diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/AbstractJWKSelectorWithSource.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/AbstractJWKSelectorWithSource.java deleted file mode 100644 index 85bc60306..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/AbstractJWKSelectorWithSource.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * 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.proc; - - -import com.nimbusds.jose.jwk.source.JWKSource; -import net.jcip.annotations.ThreadSafe; - - -/** - * Abstract JSON Web Key (JWK) selector with source. - * - * @author Vladimir Dzhuvinov - * @version 2016-04-10 - */ -@ThreadSafe -abstract class AbstractJWKSelectorWithSource { - - - /** - * The JWK source. - */ - private final JWKSource jwkSource; - - - /** - * Creates a new abstract JWK selector with a source. - * - * @param jwkSource The JWK source. Must not be {@code null}. - */ - public AbstractJWKSelectorWithSource(final JWKSource jwkSource) { - if (jwkSource == null) { - throw new IllegalArgumentException("The JWK source must not be null"); - } - this.jwkSource = jwkSource; - } - - - /** - * Returns the JWK source. - * - * @return The JWK source. - */ - public JWKSource getJWKSource() { - return jwkSource; - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/BadJOSEException.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/BadJOSEException.java deleted file mode 100644 index b22fda12a..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/BadJOSEException.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * 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.proc; - - -/** - * Bad JSON Object Signing and Encryption (JOSE) exception. - * - * @author Vladimir Dzhuvinov - * @version 2015-06-10 - */ -public class BadJOSEException extends Exception { - - - /** - * Creates a new bad JOSE exception. - * - * @param message The exception message. - */ - public BadJOSEException(final String message) { - - super(message); - } - - - /** - * Creates a new bad JOSE exception. - * - * @param message The exception message. - * @param cause The exception cause. - */ - public BadJOSEException(final String message, final Throwable cause) { - - super(message, cause); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/BadJWEException.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/BadJWEException.java deleted file mode 100644 index c1b64b492..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/BadJWEException.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * 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.proc; - - -/** - * Bad JSON Web Encryption (JWE) exception. Used to indicate a JWE-protected - * object that couldn't be successfully decrypted or its integrity has been - * compromised. - * - * @author Vladimir Dzhuvinov - * @version 2015-06-11 - */ -public class BadJWEException extends BadJOSEException { - - - /** - * Creates a new bad JWE exception. - * - * @param message The exception message. - */ - public BadJWEException(final String message) { - - super(message); - } - - - /** - * Creates a new bad JWE exception. - * - * @param message The exception message. - * @param cause The exception cause. - */ - public BadJWEException(final String message, final Throwable cause) { - - super(message, cause); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/BadJWSException.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/BadJWSException.java deleted file mode 100644 index c4ce6ea32..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/BadJWSException.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * 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.proc; - - -/** - * Bad JSON Web Signature (JWS) exception. Used to indicate an invalid - * signature or hash-based message authentication code (HMAC). - * - * @author Vladimir Dzhuvinov - * @version 2015-06-11 - */ -public class BadJWSException extends BadJOSEException { - - - /** - * Creates a new bad JWS exception. - * - * @param message The exception message. - */ - public BadJWSException(final String message) { - - super(message); - } - - - /** - * Creates a new bad JWS exception. - * - * @param message The exception message. - * @param cause The exception cause. - */ - public BadJWSException(final String message, final Throwable cause) { - - super(message, cause); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/ConfigurableJOSEProcessor.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/ConfigurableJOSEProcessor.java deleted file mode 100644 index df7bee1a1..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/ConfigurableJOSEProcessor.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * 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.proc; - - -/** - * Configurable processor of {@link com.nimbusds.jose.PlainObject unsecured} - * (plain), {@link com.nimbusds.jose.JWSObject JWS} and - * {@link com.nimbusds.jose.JWEObject JWE} objects. - * - * @author Vladimir Dzhuvinov - * @version 2015-08-22 - */ -public interface ConfigurableJOSEProcessor - extends JOSEProcessor, JOSEProcessorConfiguration { - -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/DefaultJOSEProcessor.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/DefaultJOSEProcessor.java deleted file mode 100644 index 04bb48881..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/DefaultJOSEProcessor.java +++ /dev/null @@ -1,325 +0,0 @@ -/* - * 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.proc; - - -import java.security.Key; -import java.text.ParseException; -import java.util.List; -import java.util.ListIterator; - -import com.nimbusds.jose.*; -import com.nimbusds.jose.crypto.factories.DefaultJWEDecrypterFactory; -import com.nimbusds.jose.crypto.factories.DefaultJWSVerifierFactory; -import net.jcip.annotations.ThreadSafe; - - -/** - * Default processor of {@link com.nimbusds.jose.PlainObject unsecured} - * (plain), {@link com.nimbusds.jose.JWSObject JWS} and - * {@link com.nimbusds.jose.JWEObject JWE} objects. - * - *

Must be configured with the following: - * - *

    - *
  1. To verify JWS objects: A {@link JWSKeySelector JWS key selector} to - * determine the key candidate(s) for the signature verification. The key - * selection procedure is application-specific and may involve key ID - * lookup, a certificate check and / or other information supplied in the - * message {@link SecurityContext context}.
  2. - * - *
  3. To decrypt JWE objects: A {@link JWEKeySelector JWE key selector} to - * determine the key candidate(s) for decryption. The key selection - * procedure is application-specific and may involve key ID lookup, a - * certificate check and / or other information supplied in the message - * {@link SecurityContext context}.
  4. - *
- * - *

An optional context parameter is available to facilitate passing of - * additional data between the caller and the underlying selector of key - * candidates (in both directions). - * - *

See sections 6 of RFC 7515 (JWS) and RFC 7516 (JWE) for guidelines on key - * selection. - * - *

This processor comes with the default {@link DefaultJWSVerifierFactory - * JWS verifier factory} and the default {@link DefaultJWEDecrypterFactory - * JWE decrypter factory}; they can construct verifiers / decrypters for all - * standard JOSE algorithms implemented by the library. - * - *

Note that for security reasons this processor is hardwired to reject - * unsecured (plain) JOSE objects. Override the {@link #process(PlainObject, - * SecurityContext)} method if you need to handle unsecured JOSE objects as - * well. - * - *

To process JSON Web Tokens (JWTs) use the - * {@link com.nimbusds.jwt.proc.DefaultJWTProcessor} class. - * - * @author Vladimir Dzhuvinov - * @version 2016-06-15 - */ -@ThreadSafe -public class DefaultJOSEProcessor implements ConfigurableJOSEProcessor{ - - // Cache exceptions - private static final BadJOSEException PLAIN_JOSE_REJECTED_EXCEPTION = - new BadJOSEException("Unsecured (plain) JOSE objects are rejected, extend class to handle"); - private static final BadJOSEException NO_JWS_KEY_SELECTOR_EXCEPTION = - new BadJOSEException("JWS object rejected: No JWS key selector is configured"); - private static final BadJOSEException NO_JWE_KEY_SELECTOR_EXCEPTION = - new BadJOSEException("JWE object rejected: No JWE key selector is configured"); - private static final JOSEException NO_JWS_VERIFIER_FACTORY_EXCEPTION = - new JOSEException("No JWS verifier is configured"); - private static final JOSEException NO_JWE_DECRYPTER_FACTORY_EXCEPTION = - new JOSEException("No JWE decrypter is configured"); - private static final BadJOSEException NO_JWS_KEY_CANDIDATES_EXCEPTION = - new BadJOSEException("JWS object rejected: Another algorithm expected, or no matching key(s) found"); - private static final BadJOSEException NO_JWE_KEY_CANDIDATES_EXCEPTION = - new BadJOSEException("JWE object rejected: Another algorithm expected, or no matching key(s) found"); - private static final BadJOSEException INVALID_SIGNATURE = - new BadJWSException("JWS object rejected: Invalid signature"); - private static final BadJOSEException NO_MATCHING_VERIFIERS_EXCEPTION = - new BadJOSEException("JWS object rejected: No matching verifier(s) found"); - private static final BadJOSEException NO_MATCHING_DECRYPTERS_EXCEPTION = - new BadJOSEException("JWE object rejected: No matching decrypter(s) found"); - - - /** - * The JWS key selector. - */ - private JWSKeySelector jwsKeySelector; - - - /** - * The JWE key selector. - */ - private JWEKeySelector jweKeySelector; - - - /** - * The JWS verifier factory. - */ - private JWSVerifierFactory jwsVerifierFactory = new DefaultJWSVerifierFactory(); - - - /** - * The JWE decrypter factory. - */ - private JWEDecrypterFactory jweDecrypterFactory = new DefaultJWEDecrypterFactory(); - - - @Override - public JWSKeySelector getJWSKeySelector() { - - return jwsKeySelector; - } - - - @Override - public void setJWSKeySelector(final JWSKeySelector jwsKeySelector) { - - this.jwsKeySelector = jwsKeySelector; - } - - - @Override - public JWEKeySelector getJWEKeySelector() { - - return jweKeySelector; - } - - - @Override - public void setJWEKeySelector(final JWEKeySelector jweKeySelector) { - - this.jweKeySelector = jweKeySelector; - } - - - @Override - public JWSVerifierFactory getJWSVerifierFactory() { - - return jwsVerifierFactory; - } - - - @Override - public void setJWSVerifierFactory(final JWSVerifierFactory factory) { - - jwsVerifierFactory = factory; - } - - - @Override - public JWEDecrypterFactory getJWEDecrypterFactory() { - - return jweDecrypterFactory; - } - - - @Override - public void setJWEDecrypterFactory(final JWEDecrypterFactory factory) { - - jweDecrypterFactory = factory; - } - - - @Override - public Payload process(final String compactJOSE, final C context) - throws ParseException, BadJOSEException, JOSEException { - - return process(JOSEObject.parse(compactJOSE), context); - } - - - @Override - public Payload process(final JOSEObject joseObject, final C context) - throws BadJOSEException, JOSEException { - - if (joseObject instanceof JWSObject) { - return process((JWSObject)joseObject, context); - } - - if (joseObject instanceof JWEObject) { - return process((JWEObject)joseObject, context); - } - - if (joseObject instanceof PlainObject) { - return process((PlainObject)joseObject, context); - } - - // Should never happen - throw new JOSEException("Unexpected JOSE object type: " + joseObject.getClass()); - } - - - @Override - public Payload process(final PlainObject plainObject, C context) - throws BadJOSEException { - - throw PLAIN_JOSE_REJECTED_EXCEPTION; - } - - - @Override - public Payload process(final JWSObject jwsObject, C context) - throws BadJOSEException, JOSEException { - - if (getJWSKeySelector() == null) { - // JWS key selector may have been deliberately omitted - throw NO_JWS_KEY_SELECTOR_EXCEPTION; - } - - if (getJWSVerifierFactory() == null) { - throw NO_JWS_VERIFIER_FACTORY_EXCEPTION; - } - - List keyCandidates = getJWSKeySelector().selectJWSKeys(jwsObject.getHeader(), context); - - if (keyCandidates == null || keyCandidates.isEmpty()) { - throw NO_JWS_KEY_CANDIDATES_EXCEPTION; - } - - ListIterator it = keyCandidates.listIterator(); - - while (it.hasNext()) { - - JWSVerifier verifier = getJWSVerifierFactory().createJWSVerifier(jwsObject.getHeader(), it.next()); - - if (verifier == null) { - continue; - } - - final boolean validSignature = jwsObject.verify(verifier); - - if (validSignature) { - return jwsObject.getPayload(); - } - - if (! it.hasNext()) { - // No more keys to try out - throw INVALID_SIGNATURE; - } - } - - throw NO_MATCHING_VERIFIERS_EXCEPTION; - } - - - @Override - public Payload process(final JWEObject jweObject, C context) - throws BadJOSEException, JOSEException { - - if (getJWEKeySelector() == null) { - // JWE key selector may have been deliberately omitted - throw NO_JWE_KEY_SELECTOR_EXCEPTION; - } - - if (getJWEDecrypterFactory() == null) { - throw NO_JWE_DECRYPTER_FACTORY_EXCEPTION; - } - - List keyCandidates = getJWEKeySelector().selectJWEKeys(jweObject.getHeader(), context); - - if (keyCandidates == null || keyCandidates.isEmpty()) { - throw NO_JWE_KEY_CANDIDATES_EXCEPTION; - } - - ListIterator it = keyCandidates.listIterator(); - - while (it.hasNext()) { - - JWEDecrypter decrypter = getJWEDecrypterFactory().createJWEDecrypter(jweObject.getHeader(), it.next()); - - if (decrypter == null) { - continue; - } - - try { - jweObject.decrypt(decrypter); - - } catch (JOSEException e) { - - if (it.hasNext()) { - // Try next key - continue; - } - - // No more keys to try - throw new BadJWEException("JWE object rejected: " + e.getMessage(), e); - } - - if ("JWT".equalsIgnoreCase(jweObject.getHeader().getContentType())) { - - // Handle nested signed JWT, see http://tools.ietf.org/html/rfc7519#section-5.2 - JWSObject nestedJWS = jweObject.getPayload().toJWSObject(); - - if (nestedJWS == null) { - // Cannot parse payload to JWS object, return original form - return jweObject.getPayload(); - } - - return process(nestedJWS, context); - } - - return jweObject.getPayload(); - } - - throw NO_MATCHING_DECRYPTERS_EXCEPTION; - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/JOSEMatcher.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/JOSEMatcher.java deleted file mode 100644 index 6092df074..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/JOSEMatcher.java +++ /dev/null @@ -1,526 +0,0 @@ -/* - * 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.proc; - - -import java.net.URI; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; -import java.util.Set; - -import com.nimbusds.jose.*; - - -/** - * JOSE object / header matcher. May be used to ensure a JOSE object / header - * matches a set of application-specific criteria. - * - *

Supported matching criteria: - * - *

    - *
  • Any, one or more JOSE classes (plain, JWS, JWE). - *
  • Any, one or more algorithms (alg). - *
  • Any, one or more encryption methods (enc). - *
  • Any, one or more JWK URLs (jku). - *
  • Any, one or more JWK IDs (kid). - *
- * - *

Matching by X.509 certificate URL, thumbprint and chain is not supported. - * - * @author Vladimir Dzhuvinov - * @version 2015-04-22 - */ -public class JOSEMatcher { - - - /** - * The JOSE classes to match. - */ - private final Set> classes; - - - /** - * The JOSE algorithms to match. - */ - private final Set algs; - - - /** - * The JOSE encryption methods to match (applies to JWE only). - */ - private final Set encs; - - - /** - * The JWK URLs (jku) to match. - */ - private final Set jkus; - - - /** - * The JWK IDs (kid) to match. - */ - private final Set kids; - - - /** - * Builder for constructing JOSE matchers. - * - *

Example usage: - * - *

-	 * JOSEMatcher matcher = new JOSEMatcher().keyID("123").build();
-	 * 
- */ - public static class Builder { - - - /** - * The JOSE classes to match. - */ - private Set> classes; - - - /** - * The JOSE algorithms to match. - */ - private Set algs; - - - /** - * The JOSE encryption methods to match (applies to JWE only). - */ - private Set encs; - - - /** - * The JWK URLs (jku) to match. - */ - private Set jkus; - - - /** - * The JWK IDs (kid) to match. - */ - private Set kids; - - - /** - * Sets a single JOSE class to match. - * - * @param clazz The JOSE class to match, {@code null} if not - * specified. - * - * @return This builder. - */ - public Builder joseClass(final Class clazz) { - - if (clazz == null) { - this.classes = null; - } else { - this.classes = new HashSet>(Collections.singletonList(clazz)); - } - return this; - } - - - /** - * Sets multiple JOSE classes to match. - * - * @param classes The JOSE classes to match. - * - * @return This builder. - */ - public Builder joseClasses(final Class... classes) { - - joseClasses(new HashSet<>(Arrays.asList(classes))); - return this; - } - - - /** - * Sets multiple JOSE classes to match. - * - * @param classes The JOSE classes to match, {@code null} if - * not specified. - * - * @return This builder. - */ - public Builder joseClasses(final Set> classes) { - - this.classes = classes; - return this; - } - - - /** - * Sets a single JOSE algorithm to match. - * - * @param alg The JOSE algorithm, {@code null} if not - * specified. - * - * @return This builder. - */ - public Builder algorithm(final Algorithm alg) { - - if (alg == null) { - algs = null; - } else { - algs = new HashSet<>(Collections.singletonList(alg)); - } - return this; - } - - - /** - * Sets multiple JOSE algorithms to match. - * - * @param algs The JOSE algorithms. - * - * @return This builder. - */ - public Builder algorithms(final Algorithm ... algs) { - - algorithms(new HashSet<>(Arrays.asList(algs))); - return this; - } - - - /** - * Sets multiple JOSE algorithms to match. - * - * @param algs The JOSE algorithms, {@code null} if not - * specified. - * - * @return This builder. - */ - public Builder algorithms(final Set algs) { - - this.algs = algs; - return this; - } - - - /** - * Sets a single JOSE encryption method to match. - * - * @param enc The JOSE encryption methods, {@code null} if not - * specified. - * - * @return This builder. - */ - public Builder encryptionMethod(final EncryptionMethod enc) { - - if (enc == null) { - encs = null; - } else { - encs = new HashSet<>(Collections.singletonList(enc)); - } - return this; - } - - - /** - * Sets multiple JOSE encryption methods to match. - * - * @param encs The JOSE encryption methods. - * - * @return This builder. - */ - public Builder encryptionMethods(final EncryptionMethod... encs) { - - encryptionMethods(new HashSet<>(Arrays.asList(encs))); - return this; - } - - - /** - * Sets multiple JOSE encryption methods to match. - * - * @param encs The JOSE encryption methods, {@code null} if not - * specified. - * - * @return This builder. - */ - public Builder encryptionMethods(final Set encs) { - - this.encs = encs; - return this; - } - - - /** - * Sets a single JWK URL to match. - * - * @param jku The JWK URL, {@code null} if not specified. - * - * @return This builder. - */ - public Builder jwkURL(final URI jku) { - - if (jku == null) { - jkus = null; - } else { - jkus = new HashSet<>(Collections.singletonList(jku)); - } - return this; - } - - - /** - * Sets multiple JWK URLs to match. - * - * @param jkus The JWK URLs. - * - * @return This builder. - */ - public Builder jwkURLs(final URI... jkus) { - - jwkURLs(new HashSet<>(Arrays.asList(jkus))); - return this; - } - - - /** - * Sets multiple JWK URLs to match. - * - * @param jkus The JWK URLs, {@code null} if not specified. - * - * @return This builder. - */ - public Builder jwkURLs(final Set jkus) { - - this.jkus = jkus; - return this; - } - - - /** - * Sets a single key ID to match. - * - * @param kid The key ID, {@code null} if not specified. - * - * @return This builder. - */ - public Builder keyID(final String kid) { - - if (kid == null) { - kids = null; - } else { - kids = new HashSet<>(Collections.singletonList(kid)); - } - return this; - } - - - /** - * Sets multiple key IDs to match. - * - * @param ids The key IDs. - * - * @return This builder. - */ - public Builder keyIDs(final String ... ids) { - - keyIDs(new HashSet<>(Arrays.asList(ids))); - return this; - } - - - /** - * Sets multiple key IDs to match. - * - * @param kids The key IDs, {@code null} if not specified. - * - * @return This builder. - */ - public Builder keyIDs(final Set kids) { - - this.kids = kids; - return this; - } - - - /** - * Builds a new JOSE matcher. - * - * @return The JOSE matcher. - */ - public JOSEMatcher build() { - - return new JOSEMatcher(classes, algs, encs, jkus, kids); - } - } - - - /** - * Creates a new JOSE matcher. - * - * @param classes The JOSE classes to match, {@code null} if not - * specified. - * @param algs The JOSE algorithms to match, {@code null} if not - * specified. - * @param encs The JOSE encryption methods to match, {@code null} if - * not specified. - * @param jkus The JWK URLs to match, {@code null} if not specified. - * @param kids The key IDs to match, {@code null} if not specified. - */ - public JOSEMatcher(final Set> classes, - final Set algs, - final Set encs, - final Set jkus, - final Set kids) { - - this.classes = classes; - this.algs = algs; - this.encs = encs; - this.jkus = jkus; - this.kids = kids; - } - - - /** - * Returns the JOSE classes to match. - * - * @return The JOSE classes, {@code null} if not specified. - */ - public Set> getJOSEClasses() { - - return classes; - } - - - /** - * Returns the JOSE algorithms to match. - * - * @return The JOSE algorithms, {@code null} if not specified. - */ - public Set getAlgorithms() { - - return algs; - } - - - /** - * Returns the JOSE encryption methods to match. - * - * @return The JOSE encryption methods, {@code null} if not specified. - */ - public Set getEncryptionMethods() { - - return encs; - } - - - /** - * Returns the JWK URLs to match. - * - * @return The JWK URLs, {@code null} if not specified. - */ - public Set getJWKURLs() { - - return jkus; - } - - - /** - * Returns the key IDs to match. - * - * @return The key IDs, {@code null} if not specified. - */ - public Set getKeyIDs() { - - return kids; - } - - - /** - * Returns {@code true} if the specified JOSE object matches. - * - * @param joseObject The JOSE object. Must not be {@code null}. - * - * @return {@code true} if the JOSE object matches, else {@code false}. - */ - public boolean matches(final JOSEObject joseObject) { - - if (classes != null) { - - boolean pass = false; - for (Class c: classes) { - if (c != null && c.isInstance(joseObject)) { - pass = true; - } - } - - if (!pass) { - return false; - } - } - - if (algs != null && ! algs.contains(joseObject.getHeader().getAlgorithm())) - return false; - - if (encs != null) { - - if (! (joseObject instanceof JWEObject)) - return false; - - JWEObject jweObject = (JWEObject)joseObject; - - if (! encs.contains(jweObject.getHeader().getEncryptionMethod())) - return false; - } - - if (jkus != null) { - - final URI jku; - - if (joseObject instanceof JWSObject) { - jku = ((JWSObject) joseObject).getHeader().getJWKURL(); - } else if (joseObject instanceof JWEObject) { - jku = ((JWEObject) joseObject).getHeader().getJWKURL(); - } else { - // Plain object - jku = null; // jku not supported by unsecured JOSE objects - } - - if (! jkus.contains(jku)) - return false; - } - - if (kids != null) { - - final String kid; - - if (joseObject instanceof JWSObject) { - kid = ((JWSObject) joseObject).getHeader().getKeyID(); - } else if (joseObject instanceof JWEObject) { - kid = ((JWEObject) joseObject).getHeader().getKeyID(); - } else { - // Plain object - kid = null; // kid not supported by unsecured JOSE objects - } - - if (! kids.contains(kid)) - return false; - } - - return true; - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/JOSEProcessor.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/JOSEProcessor.java deleted file mode 100644 index f30d43274..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/JOSEProcessor.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * 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.proc; - - -import java.text.ParseException; - -import com.nimbusds.jose.*; - - -/** - * Interface for parsing and processing {@link com.nimbusds.jose.PlainObject - * unsecured} (plain), {@link com.nimbusds.jose.JWSObject JWS} and - * {@link com.nimbusds.jose.JWEObject JWE} objects. An optional context - * parameter is available to facilitate passing of additional data between the - * caller and the underlying JOSE processor (in both directions). - * - * @author Vladimir Dzhuvinov - * @version 2015-08-20 - */ -public interface JOSEProcessor { - - - /** - * Parses and processes the specified JOSE object (unsecured, JWS or - * JWE). - * - * @param compactEncodedJOSE The JOSE object, compact-encoded to a - * URL-safe string. Must not be {@code null}. - * @param context Optional context, {@code null} if not - * required. - * - * @return The payload on success. - * - * @throws ParseException If the string couldn't be parsed to a valid - * JOSE object. - * @throws BadJOSEException If the JOSE object is rejected. - * @throws JOSEException If an internal processing exception is - * encountered. - */ - Payload process(final String compactEncodedJOSE, final C context) - throws ParseException, BadJOSEException, JOSEException; - - - /** - * Processes the specified JOSE object (unsecured, JWS or JWE). - * - * @param joseObject The JOSE object. Must not be {@code null}. - * @param context Optional context, {@code null} if not required. - * - * @return The payload on success. - * - * @throws BadJOSEException If the JOSE object is rejected. - * @throws JOSEException If an internal processing exception is - * encountered. - */ - Payload process(final JOSEObject joseObject, final C context) - throws BadJOSEException, JOSEException; - - - /** - * Processes the specified unsecured (plain) JOSE object, typically by - * checking its context. - * - * @param plainObject The unsecured (plain) JOSE object. Not - * {@code null}. - * @param context Optional context, {@code null} if not required. - * - * @return The payload on success. - * - * @throws BadJOSEException If the unsecured (plain) JOSE object is - * rejected. - * @throws JOSEException If an internal processing exception is - * encountered. - */ - Payload process(final PlainObject plainObject, final C context) - throws BadJOSEException, JOSEException; - - - /** - * Processes the specified JWS object by verifying its signature. The - * key candidate(s) are selected by examining the JWS header and / or - * the message context. - * - * @param jwsObject The JWS object. Not {@code null}. - * @param context Optional context, {@code null} if not required. - * - * @return The payload on success. - * - * @throws BadJOSEException If the JWS object is rejected, typically - * due to a bad signature. - * @throws JOSEException If an internal processing exception is - * encountered. - */ - Payload process(final JWSObject jwsObject, final C context) - throws BadJOSEException, JOSEException; - - - /** - * Processes the specified JWE object by decrypting it. The key - * candidate(s) are selected by examining the JWS header and / or the - * message context. - * - * @param jweObject The JWE object. Not {@code null}. - * @param context Optional context of the JWE object, {@code null} if - * not required. - * - * @return The payload on success. - * - * @throws BadJOSEException If the JWE object is rejected, typically - * due to failed decryption. - * @throws JOSEException If an internal processing exception is - * encountered. - */ - Payload process(final JWEObject jweObject, final C context) - throws BadJOSEException, JOSEException; -} - diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/JOSEProcessorConfiguration.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/JOSEProcessorConfiguration.java deleted file mode 100644 index 71b7f75f3..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/JOSEProcessorConfiguration.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * 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.proc; - - -/** - * JOSE processor configuration. - * - *

Specifies the required components to process secured JOSE objects: - * - *

    - *
  • To verify JWS objects: - *
      - *
    • Key selector to determine key candidate(s) for JWS - * verification based on the JWS header and application- - * specific context information. - *
    • Factory to construct a JWS verifier for a given key - * candidate and JWS header information. - *
    - *
  • To decrypt JWT objects: - *
      - *
    • Key selector to determine key candidate(s) for JWE - * decryption based on the JWS header and application-specific - * context information. - *
    • Factory to construct a JWE decrypter for a given key - * candidate and JWE header information. - *
    - *
- * - * @author Vladimir Dzhuvinov - * @version 2015-08-22 - */ -public interface JOSEProcessorConfiguration { - - - /** - * Gets the JWS key selector. - * - * @return The JWS key selector, {@code null} if not specified. - */ - JWSKeySelector getJWSKeySelector(); - - - /** - * Sets the JWS key selector. - * - * @param jwsKeySelector The JWS key selector, {@code null} if not - * specified. - */ - void setJWSKeySelector(final JWSKeySelector jwsKeySelector); - - - /** - * Gets the JWE key selector. - * - * @return The JWE key selector, {@code null} if not specified. - */ - JWEKeySelector getJWEKeySelector(); - - - /** - * Sets the JWE key selector. - * - * @param jweKeySelector The JWE key selector, {@code null} if not - * specified. - */ - void setJWEKeySelector(final JWEKeySelector jweKeySelector); - - - /** - * Gets the factory for creating JWS verifier instances. - * - * @return The JWS verifier factory, {@code null} if not specified. - */ - JWSVerifierFactory getJWSVerifierFactory(); - - - /** - * Sets the factory for creating JWS verifier instances. - * - * @param factory The JWS verifier factory, {@code null} if not - * specified. - */ - void setJWSVerifierFactory(final JWSVerifierFactory factory); - - - /** - * Gets the factory for creating JWE decrypter instances. - * - * @return The JWE decrypter factory, {@code null} if not specified. - */ - JWEDecrypterFactory getJWEDecrypterFactory(); - - - /** - * Sets the factory for creating JWE decrypter instances. - * - * @param factory The JWE decrypter factory, {@code null} if not - * specified. - */ - void setJWEDecrypterFactory(final JWEDecrypterFactory factory); -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/JWEDecrypterFactory.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/JWEDecrypterFactory.java deleted file mode 100644 index ea315ae85..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/JWEDecrypterFactory.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * 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.proc; - - -import java.security.Key; - -import com.nimbusds.jose.JOSEException; -import com.nimbusds.jose.JWEDecrypter; -import com.nimbusds.jose.JWEHeader; -import com.nimbusds.jose.JWEProvider; - - -/** - * JSON Web Encryption (JWE) decrypter factory. - * - * @author Vladimir Dzhuvinov - * @version 2015-11-16 - */ -public interface JWEDecrypterFactory extends JWEProvider { - - - /** - * Creates a new JWE decrypter for the specified header and key. - * - * @param header The JWE header. Not {@code null}. - * @param key The key intended to verify the JWS message. Not - * {@code null}. - * - * @return The JWE decrypter. - * - * @throws JOSEException If the JWE algorithm / encryption method is - * not supported or the key type or length - * doesn't match expected for the JWE algorithm. - */ - JWEDecrypter createJWEDecrypter(final JWEHeader header, final Key key) - throws JOSEException; -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/JWEDecryptionKeySelector.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/JWEDecryptionKeySelector.java deleted file mode 100644 index 6a55c8261..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/JWEDecryptionKeySelector.java +++ /dev/null @@ -1,148 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2019, 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.proc; - - -import java.security.Key; -import java.security.PrivateKey; -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; -import javax.crypto.SecretKey; - -import com.nimbusds.jose.EncryptionMethod; -import com.nimbusds.jose.JWEAlgorithm; -import com.nimbusds.jose.JWEHeader; -import com.nimbusds.jose.KeySourceException; -import com.nimbusds.jose.jwk.*; -import com.nimbusds.jose.jwk.source.JWKSource; -import net.jcip.annotations.ThreadSafe; - - -/** - * Key selector for decrypting JWE objects, where the key candidates are - * retrieved from a {@link JWKSource JSON Web Key (JWK) source}. - * - * @author Vladimir Dzhuvinov - * @version 2016-06-21 - */ -@ThreadSafe -public class JWEDecryptionKeySelector extends AbstractJWKSelectorWithSource implements JWEKeySelector { - - - /** - * The expected JWE algorithm. - */ - private final JWEAlgorithm jweAlg; - - - /** - * The expected JWE encryption method. - */ - private final EncryptionMethod jweEnc; - - - /** - * Creates a new decryption key selector. - * - * @param jweAlg The expected JWE algorithm for the objects to be - * decrypted. Must not be {@code null}. - * @param jweEnc The expected JWE encryption method for the objects - * to be decrypted. Must not be {@code null}. - * @param jwkSource The JWK source. Must include the private keys and - * must not be {@code null}. - */ - public JWEDecryptionKeySelector(final JWEAlgorithm jweAlg, - final EncryptionMethod jweEnc, - final JWKSource jwkSource) { - super(jwkSource); - if (jweAlg == null) { - throw new IllegalArgumentException("The JWE algorithm must not be null"); - } - this.jweAlg = jweAlg; - if (jweEnc == null) { - throw new IllegalArgumentException("The JWE encryption method must not be null"); - } - this.jweEnc = jweEnc; - } - - - /** - * Returns the expected JWE algorithm. - * - * @return The expected JWE algorithm. - */ - public JWEAlgorithm getExpectedJWEAlgorithm() { - return jweAlg; - } - - - /** - * The expected JWE encryption method. - * - * @return The expected JWE encryption method. - */ - public EncryptionMethod getExpectedJWEEncryptionMethod() { - return jweEnc; - } - - - /** - * Creates a JWK matcher for the expected JWE algorithms and the - * specified JWE header. - * - * @param jweHeader The JWE header. Must not be {@code null}. - * - * @return The JWK matcher, {@code null} if none could be created. - */ - protected JWKMatcher createJWKMatcher(final JWEHeader jweHeader) { - - if (! getExpectedJWEAlgorithm().equals(jweHeader.getAlgorithm())) { - return null; - } - - if (! getExpectedJWEEncryptionMethod().equals(jweHeader.getEncryptionMethod())) { - return null; - } - - return JWKMatcher.forJWEHeader(jweHeader); - } - - - @Override - public List selectJWEKeys(final JWEHeader jweHeader, final C context) - throws KeySourceException { - - if (! jweAlg.equals(jweHeader.getAlgorithm()) || ! jweEnc.equals(jweHeader.getEncryptionMethod())) { - // Unexpected JWE alg or enc - return Collections.emptyList(); - } - - JWKMatcher jwkMatcher = createJWKMatcher(jweHeader); - List jwkMatches = getJWKSource().get(new JWKSelector(jwkMatcher), context); - List sanitizedKeyList = new LinkedList<>(); - - for (Key key: KeyConverter.toJavaKeys(jwkMatches)) { - if (key instanceof PrivateKey || key instanceof SecretKey) { - sanitizedKeyList.add(key); - } // skip public keys - } - - return sanitizedKeyList; - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/JWEKeySelector.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/JWEKeySelector.java deleted file mode 100644 index e635ee46c..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/JWEKeySelector.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * 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.proc; - - -import java.io.IOException; -import java.security.Key; -import java.util.List; - -import com.nimbusds.jose.JWEHeader; -import com.nimbusds.jose.KeySourceException; - - -/** - * Interface for selecting key candidates for decrypting a JSON Web Encryption - * (JWE) object. Applications should utilise this interface or a similar - * framework to determine whether a received JWE object (or encrypted JWT) is - * eligible for {@link com.nimbusds.jose.JWEDecrypter decryption} and further - * processing. - * - *

The key selection should be based on application specific criteria, such - * as recognised header parameters referencing the key (e.g. {@code kid}, - * {@code x5t}) and / or the JWE object {@link SecurityContext}. - * - *

See JSON Web Signature (JWE), Appendix D. Notes on Key Selection for - * suggestions. - * - *

Possible key types: - * - *

    - *
  • {@link javax.crypto.SecretKey} for AES keys. - *
  • {@link java.security.interfaces.RSAPrivateKey} private RSA keys. - *
  • {@link java.security.interfaces.ECPrivateKey} private EC keys. - *
- * - * @author Vladimir Dzhuvinov - * @version 2016-06-21 - */ -public interface JWEKeySelector { - - - /** - * Selects key candidates for decrypting a JWE object. - * - * @param header The header of the JWE object. Must not be - * {@code null}. - * @param context Optional context of the JWE object, {@code null} if - * not required. - * - * @return The key candidates in trial order, empty list if none. - * - * @throws KeySourceException If a key source exception is encountered, - * e.g. on remote JWK retrieval. - */ - List selectJWEKeys(final JWEHeader header, final C context) - throws KeySourceException; -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/JWKSecurityContext.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/JWKSecurityContext.java deleted file mode 100644 index 05f3e9ad4..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/JWKSecurityContext.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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.proc; - - -import java.util.List; - -import com.nimbusds.jose.jwk.JWK; - -/** - * A security context that contains JSON Web Keys (JWK). Typically, this would - * be used when the keys are evaluated outside of token validation. - * - * @author Rob Winch - * @author Josh Cummings - * @version 2019-01-10 - */ -public class JWKSecurityContext implements SecurityContext { - - private final List keys; - - /** - * Constructs a {@code JWKSecurityContext} with the provided - * parameters. - * - * @param keys The list of keys. - */ - public JWKSecurityContext(final List keys) { - this.keys = keys; - - if (keys == null) { - throw new IllegalArgumentException("The list of keys must not be null"); - } - } - - /** - * Gets the list of {@link JWK}s. - * - * @return The {@code JWK} list. - */ - public List getKeys() { - return keys; - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/JWSKeySelector.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/JWSKeySelector.java deleted file mode 100644 index 40522ea07..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/JWSKeySelector.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * 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.proc; - - -import java.security.Key; -import java.util.List; - -import com.nimbusds.jose.JWSHeader; -import com.nimbusds.jose.KeySourceException; - - -/** - * Interface for selecting key candidates for verifying a JSON Web Signature - * (JWS) object. Applications should utilise this interface or a similar - * framework to determine whether a received JWS object (or signed JWT) is - * eligible for {@link com.nimbusds.jose.JWSVerifier verification} and further - * processing. - * - *

The key selection should be based on application specific criteria, such - * as recognised header parameters referencing the key (e.g. {@code kid}, - * {@code x5t}) and / or the JWS object {@link SecurityContext}. - * - *

See JSON Web Signature (JWS), Appendix D. Notes on Key Selection for - * suggestions. - * - *

Possible key types: - * - *

    - *
  • {@link javax.crypto.SecretKey} for HMAC keys. - *
  • {@link java.security.interfaces.RSAPublicKey} public RSA keys. - *
  • {@link java.security.interfaces.ECPublicKey} public EC keys. - *
- * - * @author Vladimir Dzhuvinov - * @version 2016-06-21 - */ -public interface JWSKeySelector { - - - /** - * Selects key candidates for verifying a JWS object. - * - * @param header The header of the JWS object. Must not be - * {@code null}. - * @param context Optional context of the JWS object, {@code null} if - * not required. - * - * @return The key candidates in trial order, empty list if none. - * - * @throws KeySourceException If a key sourcing exception is - * encountered, e.g. on remote JWK - * retrieval. - */ - List selectJWSKeys(final JWSHeader header, final C context) - throws KeySourceException; -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/JWSVerificationKeySelector.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/JWSVerificationKeySelector.java deleted file mode 100644 index abe6fee98..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/JWSVerificationKeySelector.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2019, 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.proc; - - -import java.security.Key; -import java.security.PublicKey; -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; -import javax.crypto.SecretKey; - -import com.nimbusds.jose.JWSAlgorithm; -import com.nimbusds.jose.JWSHeader; -import com.nimbusds.jose.KeySourceException; -import com.nimbusds.jose.jwk.*; -import com.nimbusds.jose.jwk.source.JWKSource; -import net.jcip.annotations.ThreadSafe; - - -/** - * Key selector for verifying JWS objects, where the key candidates are - * retrieved from a {@link JWKSource JSON Web Key (JWK) source}. - * - * @author Vladimir Dzhuvinov - * @version 2016-06-21 - */ -@ThreadSafe -public class JWSVerificationKeySelector extends AbstractJWKSelectorWithSource implements JWSKeySelector { - - - /** - * The expected JWS algorithm. - */ - private final JWSAlgorithm jwsAlg; - - - /** - * Creates a new JWS verification key selector. - * - * @param jwsAlg The expected JWS algorithm for the objects to be - * verified. Must not be {@code null}. - * @param jwkSource The JWK source. Must not be {@code null}. - */ - public JWSVerificationKeySelector(final JWSAlgorithm jwsAlg, final JWKSource jwkSource) { - super(jwkSource); - if (jwsAlg == null) { - throw new IllegalArgumentException("The JWS algorithm must not be null"); - } - this.jwsAlg = jwsAlg; - } - - - /** - * Returns the expected JWS algorithm. - * - * @return The expected JWS algorithm. - */ - public JWSAlgorithm getExpectedJWSAlgorithm() { - - return jwsAlg; - } - - - /** - * Creates a JWK matcher for the expected JWS algorithm and the - * specified JWS header. - * - * @param jwsHeader The JWS header. Must not be {@code null}. - * - * @return The JWK matcher, {@code null} if none could be created. - */ - protected JWKMatcher createJWKMatcher(final JWSHeader jwsHeader) { - - if (! getExpectedJWSAlgorithm().equals(jwsHeader.getAlgorithm())) { - // Unexpected JWS alg - return null; - } else { - return JWKMatcher.forJWSHeader(jwsHeader); - } - } - - - @Override - public List selectJWSKeys(final JWSHeader jwsHeader, final C context) - throws KeySourceException { - - if (! jwsAlg.equals(jwsHeader.getAlgorithm())) { - // Unexpected JWS alg - return Collections.emptyList(); - } - - JWKMatcher jwkMatcher = createJWKMatcher(jwsHeader); - if (jwkMatcher == null) { - return Collections.emptyList(); - } - - List jwkMatches = getJWKSource().get(new JWKSelector(jwkMatcher), context); - - List sanitizedKeyList = new LinkedList<>(); - - for (Key key: KeyConverter.toJavaKeys(jwkMatches)) { - if (key instanceof PublicKey || key instanceof SecretKey) { - sanitizedKeyList.add(key); - } // skip asymmetric private keys - } - - return sanitizedKeyList; - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/JWSVerifierFactory.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/JWSVerifierFactory.java deleted file mode 100644 index d0e8c6df0..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/JWSVerifierFactory.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * 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.proc; - - -import java.security.Key; - -import com.nimbusds.jose.JOSEException; -import com.nimbusds.jose.JWSHeader; -import com.nimbusds.jose.JWSProvider; -import com.nimbusds.jose.JWSVerifier; - - -/** - * JSON Web Signature (JWS) verifier factory. - * - * @author Vladimir Dzhuvinov - * @version 2015-11-16 - */ -public interface JWSVerifierFactory extends JWSProvider { - - - /** - * Creates a new JWS verifier for the specified header and key. - * - * @param header The JWS header. Not {@code null}. - * @param key The key intended to verify the JWS message. Not - * {@code null}. - * - * @return The JWS verifier. - * - * @throws JOSEException If the JWS algorithm is not supported or the - * key type or length doesn't match the expected - * for the JWS algorithm. - */ - JWSVerifier createJWSVerifier(final JWSHeader header, final Key key) - throws JOSEException; -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/SecurityContext.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/SecurityContext.java deleted file mode 100644 index 9faff19a7..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/SecurityContext.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * 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.proc; - - -/** - * Security context. Provides additional information necessary for processing - * a JOSE object. - * - *

Example context information: - * - *

    - *
  • Identifier of the message producer (e.g. OpenID Connect issuer) to - * retrieve its public key to verify the JWS signature. - *
  • Indicator whether the message was received over a secure channel - * (e.g. TLS/SSL) which is essential for processing unsecured (plain) - * JOSE objects. - *
- * - * @author Vladimir Dzhuvinov - * @version 2015-06-10 - */ -public interface SecurityContext { - - -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/SimpleSecurityContext.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/SimpleSecurityContext.java deleted file mode 100644 index 8447bddfd..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/SimpleSecurityContext.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * 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.proc; - - -import java.util.HashMap; - - -/** - * Simple map-based security context. May be extended to provide typed setters - * and getters. - * - * @author Vladimir Dzhuvinov - * @version 2015-04-22 - */ -public class SimpleSecurityContext extends HashMap implements SecurityContext { - - -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/package-info.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/package-info.java deleted file mode 100644 index 8004281ce..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/proc/package-info.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * 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. - */ - -/** - * Secure framework for application-specific verification and decryption of - * JOSE objects (with arbitrary payloads). Provides a core - * {@link com.nimbusds.jose.proc.JOSEProcessor interface} for processing JWS, - * JWE and unsecured (plain) objects, with a - * {@link com.nimbusds.jose.proc.DefaultJOSEProcessor default implementation} - * which can be configured and extended as required. - * - *

To process JSON Web Tokens (JWT) refer to the - * {@link com.nimbusds.jwt.proc} package. - */ -package com.nimbusds.jose.proc; \ No newline at end of file diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/AbstractRestrictedResourceRetriever.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/AbstractRestrictedResourceRetriever.java deleted file mode 100644 index f5fe7a49d..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/AbstractRestrictedResourceRetriever.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * 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.util; - - -import net.jcip.annotations.ThreadSafe; - - -/** - * Abstract retrieval of resources by URL with HTTP timeout and entity size - * restrictions. - */ -@ThreadSafe -public abstract class AbstractRestrictedResourceRetriever implements RestrictedResourceRetriever { - - - /** - * The HTTP connect timeout, in milliseconds. - */ - private int connectTimeout; - - - /** - * The HTTP read timeout, in milliseconds. - */ - private int readTimeout; - - - /** - * The HTTP entity size limit, in bytes. - */ - private int sizeLimit; - - - /** - * Creates a new abstract restricted resource retriever. - * - * @param connectTimeout The HTTP connects timeout, in milliseconds, - * zero for infinite. Must not be negative. - * @param readTimeout The HTTP read timeout, in milliseconds, zero - * for infinite. Must not be negative. - * @param sizeLimit The HTTP entity size limit, in bytes, zero for - * infinite. Must not be negative. - */ - public AbstractRestrictedResourceRetriever(int connectTimeout, int readTimeout, int sizeLimit) { - setConnectTimeout(connectTimeout); - setReadTimeout(readTimeout); - setSizeLimit(sizeLimit); - } - - - @Override - public int getConnectTimeout() { - - return connectTimeout; - } - - - @Override - public void setConnectTimeout(final int connectTimeoutMs) { - - if (connectTimeoutMs < 0) { - throw new IllegalArgumentException("The connect timeout must not be negative"); - } - - this.connectTimeout = connectTimeoutMs; - } - - - @Override - public int getReadTimeout() { - - return readTimeout; - } - - - @Override - public void setReadTimeout(final int readTimeoutMs) { - - if (readTimeoutMs < 0) { - throw new IllegalArgumentException("The read timeout must not be negative"); - } - - this.readTimeout = readTimeoutMs; - } - - - @Override - public int getSizeLimit() { - - return sizeLimit; - } - - - @Override - public void setSizeLimit(int sizeLimitBytes) { - - if (sizeLimitBytes < 0) { - throw new IllegalArgumentException("The size limit must not be negative"); - } - - this.sizeLimit = sizeLimitBytes; - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/ArrayUtils.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/ArrayUtils.java deleted file mode 100644 index 8bbd8fff3..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/ArrayUtils.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * 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.util; - - -import java.util.Arrays; - - -/** - * Array utilities. - */ -public class ArrayUtils { - - - /** - * Concatenates the specified arrays. - * - * @param first The first array. Must not be {@code null}. - * @param rest The remaining arrays. - * @param The array type. - * - * @return The resulting array. - */ - public static T[] concat(final T[] first, final T[]... rest) { - int totalLength = first.length; - for (T[] array : rest) { - totalLength += array.length; - } - T[] result = Arrays.copyOf(first, totalLength); - int offset = first.length; - for (T[] array : rest) { - System.arraycopy(array, 0, result, offset, array.length); - offset += array.length; - } - return result; - } - - - /** - * Prevents public instantiation. - */ - private ArrayUtils() { - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/Base64.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/Base64.java deleted file mode 100644 index c72b62765..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/Base64.java +++ /dev/null @@ -1,193 +0,0 @@ -/* - * 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.util; - - -import java.io.Serializable; -import java.math.BigInteger; - -import net.jcip.annotations.Immutable; -import net.minidev.json.JSONAware; -import net.minidev.json.JSONValue; - - -/** - * Base64-encoded object. - * - * @author Vladimir Dzhuvinov - */ -@Immutable -public class Base64 implements JSONAware, Serializable { - - - private static final long serialVersionUID = 1L; - - - /** - * The Base64 value. - */ - private final String value; - - - /** - * Creates a new Base64-encoded object. - * - * @param base64 The Base64-encoded object value. The value is not - * validated for having characters from a Base64 - * alphabet. Must not be {@code null}. - */ - public Base64(final String base64) { - - if (base64 == null) { - - throw new IllegalArgumentException("The Base64 value must not be null"); - } - - value = base64; - } - - - /** - * Decodes this Base64 object to a byte array. - * - * @return The resulting byte array. - */ - public byte[] decode() { - - return Base64Codec.decode(value); - } - - - /** - * Decodes this Base64 object to an unsigned big integer. - * - *

Same as {@code new BigInteger(1, base64.decode())}. - * - * @return The resulting big integer. - */ - public BigInteger decodeToBigInteger() { - - return new BigInteger(1, decode()); - } - - - /** - * Decodes this Base64 object to a string. - * - * @return The resulting string, in the UTF-8 character set. - */ - public String decodeToString() { - - return new String(decode(), StandardCharset.UTF_8); - } - - - /** - * Returns a JSON string representation of this object. - * - * @return The JSON string representation of this object. - */ - @Override - public String toJSONString() { - - return "\"" + JSONValue.escape(value) + "\""; - } - - - /** - * Returns a Base64 string representation of this object. The string - * will be chunked into 76 character blocks separated by CRLF. - * - * @return The Base64 string representation, chunked into 76 character - * blocks separated by CRLF. - */ - @Override - public String toString() { - - return value; - } - - - /** - * Overrides {@code Object.hashCode()}. - * - * @return The object hash code. - */ - @Override - public int hashCode() { - - return value.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 Base64 && - this.toString().equals(object.toString()); - } - - - /** - * Base64-encodes the specified byte array. - * - * @param bytes The byte array to encode. Must not be {@code null}. - * - * @return The resulting Base64 object. - */ - public static Base64 encode(final byte[] bytes) { - - return new Base64(Base64Codec.encodeToString(bytes, false)); - } - - - /** - * Base64-encodes the specified big integer, without the sign bit. - * - * @param bigInt The big integer to encode. Must not be {@code null}. - * - * @return The resulting Base64 object. - */ - public static Base64 encode(final BigInteger bigInt) { - - return encode(BigIntegerUtils.toBytesUnsigned(bigInt)); - } - - - /** - * Base64-encodes the specified string. - * - * @param text The string to encode. Must be in the UTF-8 character set - * and not {@code null}. - * - * @return The resulting Base64 object. - */ - public static Base64 encode(final String text) { - - return encode(text.getBytes(StandardCharset.UTF_8)); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/Base64Codec.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/Base64Codec.java deleted file mode 100644 index 519755945..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/Base64Codec.java +++ /dev/null @@ -1,393 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2018, 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.util; - - -import java.util.Arrays; - - -/** - * @author Tim McLean - * @author others - * @version 2018-07-23 - */ -final class Base64Codec { - - - /** - * Computes the base 64 encoded character length for the specified - * input byte length. - * - * @param inputLength The input byte length. - * @param urlSafe {@code true} for URL-safe encoding. - * - * @return The base 64 encoded character length. - */ - static int computeEncodedLength(final int inputLength, final boolean urlSafe) { - - if (inputLength == 0) { - return 0; - } - - if (urlSafe) { - - // Compute the number of complete quads (4-char blocks) - int fullQuadLength = (inputLength / 3) << 2; - - // Compute the remaining bytes at the end - int remainder = inputLength % 3; - - // Compute the total - return remainder == 0 ? fullQuadLength : fullQuadLength + remainder + 1; - } else { - // Original Mig code - return ((inputLength - 1) / 3 + 1) << 2; - } - } - - - // *** Timing-protected (tp) utility methods *** - // This class is used to encode/decode private keys, so we make an effort - // to prevent side channel leaks. Here we define a number of timing leak - // resistant utility methods. Boolean values are stored in ints in order to - // prevent optimizations that would reintroduce timing leaks. - // - // Some background information on preventing side channel leaks: - // - https://www.chosenplaintext.ca/articles/beginners-guide-constant-time-cryptography.html - - /** - * Select one of two values based on {@code bool} without leaking - * information about which one was selected. - * - * @param bool Must be 1 or 0 - * @param when_true The value to return if {@code bool} is 1 - * @param when_false The value to return if {@code bool} is 0 - * @return Either when_true or when_false - */ - static int tpSelect(int bool, int when_true, int when_false) { - - // Will be 0x00000000 when bool == 1, or 0xFFFFFFFF when bool == 0 - final int mask = bool - 1; - - return when_true ^ (mask & (when_true ^ when_false)); - } - - - /** - * Checks if a < b without leaking information about either a or b - * - * @param a Any int - * @param b Any int - * @return 1 if yes, 0 if no - */ - static int tpLT(int a, int b) { - - return (int) (((long) a - (long) b) >>> 63); - } - - - /** - * Checks if a > b without leaking information about either a or b - * - * @param a Any int - * @param b Any int - * @return 1 if yes, 0 if no - */ - static int tpGT(int a, int b) { - - return (int) (((long) b - (long) a) >>> 63); - } - - - /** - * Checks if a == b without leaking information about either a or b - * - * @param a Any int - * @param b Any int - * @return 1 if yes, 0 if no - */ - static int tpEq(int a, int b) { - - // This is magic but it will make sense - // if you think about it for 30 minutes - - final int bit_diff = a ^ b; - final int msb_iff_zero_diff = (bit_diff - 1) & (~bit_diff); - return msb_iff_zero_diff >>> 63; - } - - - /** - * Convert a digit index to the appropriate base 64 ASCII byte. - * - * Uses '+' and '/' for 62 and 63, as required for standard base 64. - * - * @param digit_idx Must be at least 0 and at most 63. Output is undefined - * if digit_idx is not on this range. - * @return An ASCII character - */ - static byte encodeDigitBase64(int digit_idx) { - - assert digit_idx >= 0 && digit_idx <= 63; - - // Figure out which type of digit this should be - final int is_uppercase = tpLT(digit_idx, 26); - final int is_lowercase = tpGT(digit_idx, 25) & tpLT(digit_idx, 52); - final int is_decimal = tpGT(digit_idx, 51) & tpLT(digit_idx, 62); - final int is_62 = tpEq(digit_idx, 62); - final int is_63 = tpEq(digit_idx, 63); - - // Translate from digit index to ASCII for each hypothetical scenario - final int as_uppercase = digit_idx - 0 + 65; - final int as_lowercase = digit_idx - 26 + 97; - final int as_decimal = digit_idx - 52 + 48; - final int as_62 = (int) '+'; - final int as_63 = (int) '/'; - - // Zero out all scenarios except for the right one, and combine - final int ascii = - tpSelect(is_uppercase, as_uppercase, 0) | - tpSelect(is_lowercase, as_lowercase, 0) | - tpSelect(is_decimal , as_decimal , 0) | - tpSelect(is_62 , as_62 , 0) | - tpSelect(is_63 , as_63 , 0); - - return (byte) ascii; - } - - - /** - * Convert a digit index to the appropriate base64url ASCII byte. - * - * Uses '-' and '_' for 62 and 63, as required for the base64url encoding. - * - * @param digit_idx Must be at least 0 and at most 63. Output is undefined - * if digit_idx is not on this range. - * @return An ASCII character - */ - static byte encodeDigitBase64URL(int digit_idx) { - - assert digit_idx >= 0 && digit_idx <= 63; - - // Figure out which type of digit this should be - final int is_uppercase = tpLT(digit_idx, 26); - final int is_lowercase = tpGT(digit_idx, 25) & tpLT(digit_idx, 52); - final int is_decimal = tpGT(digit_idx, 51) & tpLT(digit_idx, 62); - final int is_62 = tpEq(digit_idx, 62); - final int is_63 = tpEq(digit_idx, 63); - - // Translate from digit index to ASCII for each hypothetical scenario - final int as_uppercase = digit_idx - 0 + 65; - final int as_lowercase = digit_idx - 26 + 97; - final int as_decimal = digit_idx - 52 + 48; - final int as_62 = (int) '-'; - final int as_63 = (int) '_'; - - // Zero out all scenarios except for the right one, and combine - final int ascii = - tpSelect(is_uppercase, as_uppercase, 0) | - tpSelect(is_lowercase, as_lowercase, 0) | - tpSelect(is_decimal , as_decimal , 0) | - tpSelect(is_62 , as_62 , 0) | - tpSelect(is_63 , as_63 , 0); - - return (byte) ascii; - } - - - /** - * Decode an ASCII byte to a base 64 digit index (0 to 63), or -1 if the - * input is not a valid base 64 digit. - * - * Supports '+' and '/' for standard base 64, but also '-' and '_' for - * base64url. - * - * @param ascii An ASCII character. - * @return A digit index i such that 0 <= i <= 63, or -1 if the input was not a digit. - */ - static int decodeDigit(byte ascii) { - - // Figure out which type of digit this is - final int is_uppercase = tpGT(ascii, 64) & tpLT(ascii, 91); - final int is_lowercase = tpGT(ascii, 96) & tpLT(ascii, 123); - final int is_decimal = tpGT(ascii, 47) & tpLT(ascii, 58); - final int is_62 = tpEq(ascii, (int) '-') | tpEq(ascii, (int) '+'); - final int is_63 = tpEq(ascii, (int) '_') | tpEq(ascii, (int) '/'); - - // It should be one of the five categories - final int is_valid = is_uppercase | is_lowercase | is_decimal | is_62 | is_63; - - // Translate from ASCII to digit index for each hypothetical scenario - final int from_uppercase = ascii - 65 + 0; - final int from_lowercase = ascii - 97 + 26; - final int from_decimal = ascii - 48 + 52; - final int from_62 = 62; - final int from_63 = 63; - - // Zero out all scenarios except for the right one, and combine - final int digit_idx = - tpSelect(is_uppercase, from_uppercase, 0) | - tpSelect(is_lowercase, from_lowercase, 0) | - tpSelect(is_decimal , from_decimal , 0) | - tpSelect(is_62 , from_62 , 0) | - tpSelect(is_63 , from_63 , 0) | - tpSelect(is_valid , 0 , -1); - - assert digit_idx >= -1 && digit_idx <= 63; - - return digit_idx; - } - - - /** - * Encodes a byte array into a base 64 encoded string. - * - * @param byteArray The bytes to convert. If {@code null} or length 0 - * an empty array will be returned. - * @param urlSafe If {@code true} to apply URL-safe encoding (padding - * still included and not to spec). - * - * @return The base 64 encoded string. Never {@code null}. - */ - public static String encodeToString(byte[] byteArray, final boolean urlSafe) { - - // Check special case - final int sLen = byteArray != null ? byteArray.length : 0; - - if (sLen == 0) { - return ""; - } - - final int eLen = (sLen / 3) * 3; // Length of even 24-bits. - final int dLen = computeEncodedLength(sLen, urlSafe); // Returned byte count - final byte[] out = new byte[dLen]; - - // Encode even 24-bits - for (int s = 0, d = 0; s < eLen; ) { - - // Copy next three bytes into lower 24 bits of int, paying attention to sign - final int i = (byteArray[s++] & 0xff) << 16 | (byteArray[s++] & 0xff) << 8 | (byteArray[s++] & 0xff); - - // Encode the int into four chars - if (urlSafe) { - out[d++] = encodeDigitBase64URL((i >>> 18) & 0x3f); - out[d++] = encodeDigitBase64URL((i >>> 12) & 0x3f); - out[d++] = encodeDigitBase64URL((i >>> 6) & 0x3f); - out[d++] = encodeDigitBase64URL(i & 0x3f); - } else { - out[d++] = encodeDigitBase64((i >>> 18) & 0x3f); - out[d++] = encodeDigitBase64((i >>> 12) & 0x3f); - out[d++] = encodeDigitBase64((i >>> 6) & 0x3f); - out[d++] = encodeDigitBase64(i & 0x3f); - } - } - - // Pad and encode last bits if source isn't even 24 bits - // according to URL-safe switch - final int left = sLen - eLen; // 0 - 2. - if (left > 0) { - // Prepare the int - final int i = ((byteArray[eLen] & 0xff) << 10) | (left == 2 ? ((byteArray[sLen - 1] & 0xff) << 2) : 0); - - // Set last four chars - if (urlSafe) { - - if (left == 2) { - out[dLen - 3] = encodeDigitBase64URL(i >> 12); - out[dLen - 2] = encodeDigitBase64URL((i >>> 6) & 0x3f); - out[dLen - 1] = encodeDigitBase64URL(i & 0x3f); - } else { - out[dLen - 2] = encodeDigitBase64URL(i >> 12); - out[dLen - 1] = encodeDigitBase64URL((i >>> 6) & 0x3f); - } - } else { - // Original Mig code with padding - out[dLen - 4] = encodeDigitBase64(i >> 12); - out[dLen - 3] = encodeDigitBase64((i >>> 6) & 0x3f); - out[dLen - 2] = left == 2 ? encodeDigitBase64(i & 0x3f) : (byte) '='; - out[dLen - 1] = (byte) '='; - } - } - - return new String(out, StandardCharset.UTF_8); - } - - - /** - * Decodes a base 64 or base 64 URL-safe encoded string. May contain - * line separators. Any illegal characters are ignored. - * - * @param b64String The base 64 or base 64 URL-safe encoded string. May - * be empty or {@code null}. - * - * @return The decoded byte array, empty if the input base 64 encoded - * string is empty, {@code null} or corrupted. - */ - public static byte[] decode(final String b64String) { - - // Check special case - if (b64String == null || b64String.isEmpty()) { - return new byte[0]; - } - - final byte[] srcBytes = b64String.getBytes(StandardCharset.UTF_8); - final int sLen = srcBytes.length; - - // Calculate output length assuming zero bytes are padding or separators - final int maxOutputLen = sLen * 6 >> 3; - - // Allocate output array (may be too large) - final byte[] dstBytes = new byte[maxOutputLen]; - - // Process all input bytes - int d = 0; - for (int s = 0; s < srcBytes.length; ) { - // Assemble three bytes into an int from four base 64 - // characters - int i = 0; - - int j = 0; - while (j < 4 && s < sLen) { - // j only increased if a valid char was found - final int c = decodeDigit(srcBytes[s++]); - if (c >= 0) { - i |= c << (18 - j * 6); - j++; - } - } - - // j is now the number of valid digits decoded - - // Add output bytes - if (j >= 2) { - dstBytes[d++] = (byte) (i >> 16); - if (j >= 3) { - dstBytes[d++] = (byte) (i >> 8); - if (j >= 4) { - dstBytes[d++] = (byte) i; - } - } - } - } - - // d is now the number of output bytes written - - // Copy dstBytes to new array of proper size - return Arrays.copyOf(dstBytes, d); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/Base64URL.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/Base64URL.java deleted file mode 100644 index 0d6efedcf..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/Base64URL.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * 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.util; - - -import java.math.BigInteger; - -import net.jcip.annotations.Immutable; - - -/** - * Base64URL-encoded object. - * - *

Related specifications: - * - *

    - *
  • RFC 4648. - *
- * - * @author Vladimir Dzhuvinov - * @version 2018-01-04 - */ -@Immutable -public class Base64URL extends Base64 { - - - /** - * Creates a new Base64URL-encoded object. - * - * @param base64URL The Base64URL-encoded object value. The value is - * not validated for having characters from the - * Base64URL alphabet. Must not be {@code null}. - */ - public Base64URL(final String base64URL) { - - super(base64URL); - } - - - /** - * 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 Base64URL && - this.toString().equals(object.toString()); - } - - - /** - * Base64URL-encodes the specified byte array. - * - * @param bytes The byte array to encode. Must not be {@code null}. - * - * @return The resulting Base64URL object. - */ - public static Base64URL encode(final byte[] bytes) { - - return new Base64URL(Base64Codec.encodeToString(bytes, true)); - } - - - /** - * Base64URL-encodes the specified big integer, without the sign bit. - * - * @param bigInt The big integer to encode. Must not be {@code null}. - * - * @return The resulting Base64URL object. - */ - public static Base64URL encode(final BigInteger bigInt) { - - return encode(BigIntegerUtils.toBytesUnsigned(bigInt)); - } - - - /** - * Base64URL-encodes the specified string. - * - * @param text The string to encode. Must be in the UTF-8 character set - * and not {@code null}. - * - * @return The resulting Base64URL object. - */ - public static Base64URL encode(final String text) { - - return encode(text.getBytes(StandardCharset.UTF_8)); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/BigIntegerUtils.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/BigIntegerUtils.java deleted file mode 100644 index 765e5e8b8..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/BigIntegerUtils.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * 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.util; - - -import java.math.BigInteger; - - -/** - * Big integer utilities. - * - * @author Vladimir Dzhuvinov - * @version 2013-03-21 - */ -public class BigIntegerUtils { - - - /** - * Returns a byte array representation of the specified big integer - * without the sign bit. - * - * @param bigInt The big integer to be converted. Must not be - * {@code null}. - * - * @return A byte array representation of the big integer, without the - * sign bit. - */ - public static byte[] toBytesUnsigned(final BigInteger bigInt) { - - // Copied from Apache Commons Codec 1.8 - - int bitlen = bigInt.bitLength(); - - // round bitlen - bitlen = ((bitlen + 7) >> 3) << 3; - final byte[] bigBytes = bigInt.toByteArray(); - - if (((bigInt.bitLength() % 8) != 0) && (((bigInt.bitLength() / 8) + 1) == (bitlen / 8))) { - - return bigBytes; - - } - - // set up params for copying everything but sign bit - int startSrc = 0; - int len = bigBytes.length; - - // if bigInt is exactly byte-aligned, just skip signbit in copy - if ((bigInt.bitLength() % 8) == 0) { - - startSrc = 1; - len--; - } - - final int startDst = bitlen / 8 - len; // to pad w/ nulls as per spec - final byte[] resizedBytes = new byte[bitlen / 8]; - System.arraycopy(bigBytes, startSrc, resizedBytes, startDst, len); - return resizedBytes; - } - - - /** - * Prevents public instantiation. - */ - private BigIntegerUtils() { - - } -} \ No newline at end of file diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/BoundedInputStream.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/BoundedInputStream.java deleted file mode 100644 index 3c197a8ac..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/BoundedInputStream.java +++ /dev/null @@ -1,213 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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.util; - - -import java.io.IOException; -import java.io.InputStream; - - -/** - * Size-bounded input stream. Adapted from Apache Commons IO. Throws an - * {@link IOException} if the input size limit is exceeded. - * - * @version 2016-11-28 - */ -public class BoundedInputStream extends InputStream { - - - /** - * The wrapped input stream. - */ - private final InputStream in; - - - /** - * The limit, -1 if none. - */ - private final long max; - - - /** - * The current input stream position. - */ - private long pos; - - - /** - * Marks the input stream. - */ - private long mark; - - - /** - * If {@link #close()} is to be propagated to the underlying input - * stream. - */ - private boolean propagateClose; - - - /** - * Creates a new bounded input stream. - * - * @param in The input stream to wrap. - * @param size The maximum number of bytes to return, -1 if no limit. - */ - public BoundedInputStream(final InputStream in, final long size) { - this.pos = 0L; - this.mark = -1L; - this.propagateClose = true; - this.max = size; - this.in = in; - } - - - /** - * Creates a new unbounded input stream. - * - * @param in The input stream to wrap. - */ - public BoundedInputStream(final InputStream in) { - this(in, -1L); - } - - - /** - * Returns the maximum number of bytes to return. - * - * @return The maximum number of bytes to return, -1 if no limit. - */ - public long getLimitBytes() { - return max; - } - - - @Override - public int read() throws IOException { - if (this.max >= 0L && this.pos >= this.max) { - throw new IOException("Exceeded configured input limit of " + this.max + " bytes"); - } else { - int result = this.in.read(); - ++this.pos; - return result; // data or -1 on EOF - } - } - - - @Override - public int read(byte[] b) throws IOException { - return this.read(b, 0, b.length); - } - - - @Override - public int read(byte[] b, int off, int len) throws IOException { - if(this.max >= 0L && this.pos >= this.max) { - throw new IOException("Exceeded configured input limit of " + this.max + " bytes"); - } else { - int bytesRead = this.in.read(b, off, len); - - if(bytesRead == -1) { - return -1; - } else { - this.pos += (long)bytesRead; - - if (this.max >= 0L && this.pos >= this.max) - throw new IOException("Exceeded configured input limit of " + this.max + " bytes"); - - return bytesRead; - } - } - } - - - @Override - public long skip(long n) throws IOException { - long toSkip = this.max >= 0L?Math.min(n, this.max - this.pos):n; - long skippedBytes = this.in.skip(toSkip); - this.pos += skippedBytes; - return skippedBytes; - } - - - @Override - public int available() throws IOException { - return this.max >= 0L && this.pos >= this.max?0:this.in.available(); - } - - - @Override - public String toString() { - return this.in.toString(); - } - - - @Override - public void close() throws IOException { - if(this.propagateClose) { - this.in.close(); - } - } - - - @Override - public synchronized void reset() throws IOException { - this.in.reset(); - this.pos = this.mark; - } - - - @Override - public synchronized void mark(int readlimit) { - this.in.mark(readlimit); - this.mark = this.pos; - } - - - @Override - public boolean markSupported() { - return this.in.markSupported(); - } - - - /** - * Indicates whether the {@link #close()} method should propagate to - * the underling InputStream. - * - * @return {@code true} if calling {@link #close()} propagates to the - * {@link #close()} method of the underlying stream or - * {@code false} if it does not. - */ - public boolean isPropagateClose() { - return this.propagateClose; - } - - - /** - * Set whether the {@link #close()} method should propagate to the - * underling InputStream. - * - * @param propagateClose {@code true} if calling {@link #close()} - * propagates to the {@link #close()} method of - * the underlying stream or {@code false} if it - * does not. - */ - public void setPropagateClose(boolean propagateClose) { - this.propagateClose = propagateClose; - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/ByteUtils.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/ByteUtils.java deleted file mode 100644 index f76b8ec72..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/ByteUtils.java +++ /dev/null @@ -1,166 +0,0 @@ -/* - * 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.util; - - -import java.io.ByteArrayOutputStream; -import java.io.IOException; - - -/** - * Byte utilities. - * - * @author Vladimir Dzhuvinov - * @version 2017-06-01 - */ -public class ByteUtils { - - - /** - * Concatenates the specified byte arrays. - * - * @param byteArrays The byte arrays to concatenate, may be - * {@code null}. - * - * @return The resulting byte array. - */ - public static byte[] concat(byte[]... byteArrays) { - - try { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - - for (byte[] bytes : byteArrays) { - - if (bytes == null) { - continue; // skip - } - - baos.write(bytes); - } - return baos.toByteArray(); - - } catch (IOException e) { - // Should never happen - throw new IllegalStateException(e.getMessage(), e); - } - } - - - /** - * Returns a portion of the specified byte array. - * - * @param byteArray The byte array. Must not be {@code null}. - * @param beginIndex The beginning index, inclusive. Must be zero or - * positive. - * @param length The length. Must be zero or positive. - * - * @return The byte array portion. - */ - public static byte[] subArray(byte[] byteArray, int beginIndex, int length) { - - byte[] subArray = new byte[length]; - System.arraycopy(byteArray, beginIndex, subArray, 0, subArray.length); - return subArray; - } - - - /** - * Returns the bit length of the specified byte length. - * - * @param byteLength The byte length. - * - * @return The bit length. - */ - public static int bitLength(final int byteLength) { - - return byteLength * 8; - } - - - /** - * Returns the bit length of the specified byte length, preventing - * integer overflow. - * - * @param byteLength The byte length. - * - * @return The bit length. - * - * @throws IntegerOverflowException On a integer overflow. - */ - public static int safeBitLength(final int byteLength) - throws IntegerOverflowException { - - long longResult = (long)byteLength * (long)8; - if((long)((int)longResult) != longResult) { - throw new IntegerOverflowException(); - } else { - return (int)longResult; - } - } - - - /** - * Returns the byte length of the specified byte array. - * - * @param byteArray The byte array. May be {@code null}. - * - * @return The bite length, zero if the array is {@code null}. - */ - public static int bitLength(final byte[] byteArray) { - - if (byteArray == null) { - return 0; - } else { - return bitLength(byteArray.length); - } - } - - - /** - * Returns the byte length of the specified byte array, preventing - * integer overflow. - * - * @param byteArray The byte array. May be {@code null}. - * - * @return The bite length, zero if the array is {@code null}. - * - * @throws IntegerOverflowException On a integer overflow. - */ - public static int safeBitLength(final byte[] byteArray) - throws IntegerOverflowException { - - if (byteArray == null) { - return 0; - } else { - return safeBitLength(byteArray.length); - } - } - - - /** - * Returns the byte length of the specified bit length. - * - * @param bitLength The bit length. - * - * @return The byte byte length. - */ - public static int byteLength(final int bitLength) { - - return bitLength / 8; - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/Container.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/Container.java deleted file mode 100644 index c9b60bbae..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/Container.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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.util; - -import net.jcip.annotations.NotThreadSafe; - - -/** - * Generic container of items of any type. - * - *

This class is not thread-safe, if thread safety is required it should be - * done externally to the class. - * - *

The author believes he borrowed the idea for such a class many years ago - * from a man called Boris Karadjov. - * - * @param the type of the item in this container. - * - * @author Dimitar A. Stoikov - * @version 2016-10-13 - */ -@NotThreadSafe -public class Container { - - - /** - * The item. - */ - private T item; - - - /** - * Creates a new container with no item. - */ - public Container() { - } - - - /** - * Creates a new container with the specified item. - * - * @param item The item, may be {@code null}. - */ - public Container(final T item) { - this.item = item; - } - - - /** - * Gets the contained item. - * - * @return The item, {@code null} if none. - */ - public T get() { - return item; - } - - - /** - * Sets the contained item. - * - * @param item The item, may be {@code null}. - */ - public void set(final T item) { - this.item = item; - } -} \ No newline at end of file diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/DateUtils.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/DateUtils.java deleted file mode 100644 index bafad3dcd..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/DateUtils.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * 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.util; - - -import java.util.Date; - - -/** - * Date utilities. Use {@link com.nimbusds.jwt.util.DateUtils} instead. - */ -@Deprecated -public class DateUtils { - - - /** - * Converts the specified date object to a Unix epoch time in seconds. - * - * @param date The date. Must not be {@code null}. - * - * @return The Unix epoch time, in seconds. - */ - public static long toSecondsSinceEpoch(final Date date) { - - return date.getTime() / 1000L; - } - - - /** - * Converts the specified Unix epoch time in seconds to a date object. - * - * @param time The Unix epoch time, in seconds. Must not be negative. - * - * @return The date. - */ - public static Date fromSecondsSinceEpoch(final long time) { - - return new Date(time * 1000L); - } - - - /** - * Check if the specified date is after the specified reference, given - * the maximum accepted negative clock skew. - * - *

Formula: - * - *

-	 * return date + clock_skew > reference
-	 * 
- * - * Example: Ensure a JWT expiration (exp) timestamp is after the - * current time, with a minute of acceptable clock skew. - * - *
-	 * boolean valid = DateUtils.isAfter(exp, new Date(), 60);
-	 * 
- * - * @param date The date to check. Must not be - * {@code null}. - * @param reference The reference date (e.g. the current - * time). Must not be {@code null}. - * @param maxClockSkewSeconds The maximum acceptable negative clock - * skew of the date value to check, in - * seconds. - * - * @return {@code true} if the date is before the reference, plus the - * maximum accepted clock skew, else {@code false}. - */ - public static boolean isAfter(final Date date, - final Date reference, - final long maxClockSkewSeconds) { - - return new Date(date.getTime() + maxClockSkewSeconds*1000L).after(reference); - } - - - /** - * Checks if the specified date is before the specified reference, - * given the maximum accepted positive clock skew. - * - *

Formula: - * - *

-	 * return date - clock_skew < reference
-	 * 
- * - * Example: Ensure a JWT issued-at (iat) timestamp is before the - * current time, with a minute of acceptable clock skew. - * - *
-	 * boolean valid = DateUtils.isBefore(iat, new Date(), 60);
-	 * 
- * - * @param date The date to check. Must not be - * {@code null}. - * @param reference The reference date (e.g. the current - * time). Must not be {@code null}. - * @param maxClockSkewSeconds The maximum acceptable clock skew of the - * date value to check, in seconds. - * - * @return {@code true} if the date is before the reference, minus the - * maximum accepted clock skew, else {@code false}. - */ - public static boolean isBefore(final Date date, - final Date reference, - final long maxClockSkewSeconds) { - - return new Date(date.getTime() - maxClockSkewSeconds*1000L).before(reference); - } - - - /** - * Prevents instantiation. - */ - private DateUtils() { } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/DefaultResourceRetriever.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/DefaultResourceRetriever.java deleted file mode 100644 index 000075f24..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/DefaultResourceRetriever.java +++ /dev/null @@ -1,197 +0,0 @@ -/* - * 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.util; - - -import java.io.IOException; -import java.io.InputStream; -import java.net.HttpURLConnection; -import java.net.URL; -import java.nio.charset.Charset; - -import net.jcip.annotations.ThreadSafe; - - -/** - * The default retriever of resources specified by URL. Provides setting of - * HTTP connect and read timeouts as well as a size limit of the retrieved - * entity. Caching header directives are not honoured. - * - * @author Vladimir Dzhuvinov - * @version 2018-01-04 - */ -@ThreadSafe -public class DefaultResourceRetriever extends AbstractRestrictedResourceRetriever implements RestrictedResourceRetriever { - - - /** - * If {@code true} the disconnect method of the underlying - * HttpURLConnection is called after a successful or failed retrieval. - */ - private boolean disconnectAfterUse; - - - /** - * Creates a new resource retriever. The HTTP timeouts and entity size - * limit are set to zero (infinite). - */ - public DefaultResourceRetriever() { - - this(0, 0); - } - - - /** - * Creates a new resource retriever. The HTTP entity size limit is set - * to zero (infinite). - * - * @param connectTimeout The HTTP connects timeout, in milliseconds, - * zero for infinite. Must not be negative. - * @param readTimeout The HTTP read timeout, in milliseconds, zero - * for infinite. Must not be negative. - */ - public DefaultResourceRetriever(final int connectTimeout, final int readTimeout) { - - this(connectTimeout, readTimeout, 0); - } - - - /** - * Creates a new resource retriever. - * - * @param connectTimeout The HTTP connects timeout, in milliseconds, - * zero for infinite. Must not be negative. - * @param readTimeout The HTTP read timeout, in milliseconds, zero - * for infinite. Must not be negative. - * @param sizeLimit The HTTP entity size limit, in bytes, zero for - * infinite. Must not be negative. - */ - public DefaultResourceRetriever(final int connectTimeout, final int readTimeout, final int sizeLimit) { - - this(connectTimeout, readTimeout, sizeLimit, true); - } - - - /** - * Creates a new resource retriever. - * - * @param connectTimeout The HTTP connects timeout, in - * milliseconds, zero for infinite. Must not - * be negative. - * @param readTimeout The HTTP read timeout, in milliseconds, - * zero for infinite. Must not be negative. - * @param sizeLimit The HTTP entity size limit, in bytes, zero - * for infinite. Must not be negative. - * @param disconnectAfterUse If {@code true} the disconnect method of - * the underlying {@link HttpURLConnection} - * will be called after trying to retrieve - * the resource. Whether the TCP socket is - * actually closed or reused depends on the - * underlying HTTP implementation and the - * setting of the {@code keep.alive} system - * property. - */ - public DefaultResourceRetriever(final int connectTimeout, - final int readTimeout, - final int sizeLimit, - final boolean disconnectAfterUse) { - - super(connectTimeout, readTimeout, sizeLimit); - this.disconnectAfterUse = disconnectAfterUse; - } - - - /** - * Returns {@code true} if the disconnect method of the underlying - * {@link HttpURLConnection} will be called after trying to retrieve - * the resource. Whether the TCP socket is actually closed or reused - * depends on the underlying HTTP implementation and the setting of the - * {@code keep.alive} system property. - * - * @return If {@code true} the disconnect method of the underlying - * {@link HttpURLConnection} will be called after trying to - * retrieve the resource. - */ - public boolean disconnectsAfterUse() { - - return disconnectAfterUse; - } - - - /** - * Controls calling of the disconnect method the underlying - * {@link HttpURLConnection} after trying to retrieve the resource. - * Whether the TCP socket is actually closed or reused depends on the - * underlying HTTP implementation and the setting of the - * {@code keep.alive} system property. - * - * If {@code true} the disconnect method of the underlying - * {@link HttpURLConnection} will be called after trying to - * retrieve the resource. - */ - public void setDisconnectsAfterUse(final boolean disconnectAfterUse) { - - this.disconnectAfterUse = disconnectAfterUse; - } - - - @Override - public Resource retrieveResource(final URL url) - throws IOException { - - HttpURLConnection con = null; - try { - con = (HttpURLConnection)url.openConnection(); - - con.setConnectTimeout(getConnectTimeout()); - con.setReadTimeout(getReadTimeout()); - - final String content; - - InputStream inputStream = con.getInputStream(); - try { - if (getSizeLimit() > 0) { - inputStream = new BoundedInputStream(inputStream, getSizeLimit()); - } - - content = IOUtils.readInputStreamToString(inputStream, Charset.forName("UTF-8")); - - } finally { - inputStream.close(); - } - - // Check HTTP code + message - final int statusCode = con.getResponseCode(); - final String statusMessage = con.getResponseMessage(); - - // Ensure 2xx status code - if (statusCode > 299 || statusCode < 200) { - throw new IOException("HTTP " + statusCode + ": " + statusMessage); - } - - return new Resource(content, con.getContentType()); - - } catch (ClassCastException e) { - throw new IOException("Couldn't open HTTP(S) connection: " + e.getMessage(), e); - } finally { - if (disconnectAfterUse && con != null) { - con.disconnect(); - } - } - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/DeflateUtils.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/DeflateUtils.java deleted file mode 100644 index f6b358c7d..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/DeflateUtils.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * 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.util; - - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.zip.Deflater; -import java.util.zip.DeflaterOutputStream; -import java.util.zip.InflaterInputStream; -import java.util.zip.Inflater; - - -/** - * Deflate (RFC 1951) utilities. - * - * @author Vladimir Dzhuvinov - * @version 2013-04-16 - */ -public class DeflateUtils { - - - /** - * Omit headers and CRC fields from output, as specified by RFC 1950. - * Note that the Deflater JavaDocs are incorrect, see - * http://stackoverflow.com/questions/11076060/decompressing-gzipped-data-with-inflater-in-java - */ - private static final boolean NOWRAP = true; - - - /** - * Compresses the specified byte array according to the DEFLATE - * specification (RFC 1951). - * - * @param bytes The byte array to compress. Must not be {@code null}. - * - * @return The compressed bytes. - * - * @throws IOException If compression failed. - */ - public static byte[] compress(final byte[] bytes) - throws IOException { - - ByteArrayOutputStream out = new ByteArrayOutputStream(); - - - Deflater deflater = null; - DeflaterOutputStream def = null; - try { - deflater = new Deflater(Deflater.DEFLATED, NOWRAP); - def = new DeflaterOutputStream(out, deflater); - def.write(bytes); - } finally { - if(def != null) { - def.close(); - } - if(deflater != null) { - deflater.end(); - } - } - - return out.toByteArray(); - } - - - /** - * Decompresses the specified byte array according to the DEFLATE - * specification (RFC 1951). - * - * @param bytes The byte array to decompress. Must not be {@code null}. - * - * @return The decompressed bytes. - * - * @throws IOException If decompression failed. - */ - public static byte[] decompress(final byte[] bytes) - throws IOException { - - Inflater inflater = null; - InflaterInputStream inf = null; - try { - inflater = new Inflater(NOWRAP); - inf = new InflaterInputStream(new ByteArrayInputStream(bytes), inflater); - - ByteArrayOutputStream out = new ByteArrayOutputStream(); - - // Transfer bytes from the compressed array to the output - byte[] buf = new byte[1024]; - - int len; - - while ((len = inf.read(buf)) > 0) { - - out.write(buf, 0, len); - } - - return out.toByteArray(); - } finally { - if(inf != null) { - inf.close(); - } - if(inflater != null) { - inflater.end(); - } - } - } - - - /** - * Prevents public instantiation. - */ - private DeflateUtils() { - - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/IOUtils.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/IOUtils.java deleted file mode 100644 index 693208cac..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/IOUtils.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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.util; - - -import java.io.*; -import java.nio.charset.Charset; - - -/** - * Input / output utilities. - * - * @author Vladimir Dzhuvinov - * @version 2016-11-28 - */ -public class IOUtils { - - - /** - * Reads the specified input stream into a string. - * - * @param stream The input stream. Must not be {@code null}. - * @param charset The expected character set. Must not be {@code null}. - * - * @return The string. - * - * @throws IOException If an input exception is encountered. - */ - public static String readInputStreamToString(final InputStream stream, final Charset charset) - throws IOException { - - final int bufferSize = 1024; - final char[] buffer = new char[bufferSize]; - final StringBuilder out = new StringBuilder(); - Reader in = new InputStreamReader(stream, charset); - - while (true) { - int rsz = in.read(buffer, 0, buffer.length); - if (rsz < 0) - break; - out.append(buffer, 0, rsz); - } - - return out.toString(); - } - - - /** - * Reads the content of the specified file into a string. - * - * @param file The file. Must not be {@code null}. - * @param charset The expected character set. Must not be {@code null}. - * - * @return The string. - * - * @throws IOException If an input exception is encountered. - */ - public static String readFileToString(final File file, final Charset charset) - throws IOException { - - return readInputStreamToString(new FileInputStream(file), charset); - } - - - /** - * Prevents public instantiation. - */ - private IOUtils() {} -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/IntegerOverflowException.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/IntegerOverflowException.java deleted file mode 100644 index 168232b80..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/IntegerOverflowException.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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.util; - - -import com.nimbusds.jose.JOSEException; - - -/** - * Integer overflow exception. - */ -public class IntegerOverflowException extends JOSEException { - - - /** - * Creates a new integer overflow exception. - */ - public IntegerOverflowException() { - super("Integer overflow"); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/IntegerUtils.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/IntegerUtils.java deleted file mode 100644 index 669a90e0a..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/IntegerUtils.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * 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.util; - - -/** - * Integer utilities. - * - * @author Vladimir Dzhuvinov - * @version 2015-05-12 - */ -public class IntegerUtils { - - - /** - * Returns a four byte array representation of the specified integer. - * - * @param intValue The integer to be converted. - * - * @return The byte array representation of the integer. - */ - public static byte[] toBytes(int intValue) { - - byte[] res = new byte[4]; - res[0] = (byte) (intValue >>> 24); - res[1] = (byte) ((intValue >>> 16) & 0xFF); - res[2] = (byte) ((intValue >>> 8) & 0xFF); - res[3] = (byte) (intValue & 0xFF); - return res; - } - - - /** - * Prevents public instantiation. - */ - private IntegerUtils() { - - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/JSONObjectUtils.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/JSONObjectUtils.java deleted file mode 100644 index 5fcc0c075..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/JSONObjectUtils.java +++ /dev/null @@ -1,390 +0,0 @@ -/* - * 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.util; - - -import java.net.URI; -import java.net.URISyntaxException; -import java.text.ParseException; -import java.util.Arrays; -import java.util.List; - -import net.minidev.json.JSONArray; -import net.minidev.json.JSONObject; -import net.minidev.json.parser.JSONParser; - - -/** - * JSON object helper methods for parsing and typed retrieval of member values. - * - * @author Vladimir Dzhuvinov - * @version 2018-11-06 - */ -public class JSONObjectUtils { - - - /** - * Parses a JSON object. - * - *

Specific JSON to Java entity mapping (as per JSON Smart): - * - *

    - *
  • JSON true|false map to {@code java.lang.Boolean}. - *
  • JSON numbers map to {@code java.lang.Number}. - *
      - *
    • JSON integer numbers map to {@code long}. - *
    • JSON fraction numbers map to {@code double}. - *
    - *
  • JSON strings map to {@code java.lang.String}. - *
  • JSON arrays map to {@code net.minidev.json.JSONArray}. - *
  • JSON objects map to {@code net.minidev.json.JSONObject}. - *
- * - * @param s The JSON object string to parse. Must not be {@code null}. - * - * @return The JSON object. - * - * @throws ParseException If the string cannot be parsed to a valid JSON - * object. - */ - public static JSONObject parse(final String s) - throws ParseException { - - Object o; - - try { - o = new JSONParser(JSONParser.USE_HI_PRECISION_FLOAT | JSONParser.ACCEPT_TAILLING_SPACE).parse(s); - - } catch (net.minidev.json.parser.ParseException e) { - - throw new ParseException("Invalid JSON: " + e.getMessage(), 0); - } - - if (o instanceof JSONObject) { - return (JSONObject)o; - } else { - throw new ParseException("JSON entity is not an object", 0); - } - } - - - /** - * Use {@link #parse(String)} instead. - * - * @param s The JSON object string to parse. Must not be {@code null}. - * - * @return The JSON object. - * - * @throws ParseException If the string cannot be parsed to a valid JSON - * object. - */ - @Deprecated - public static JSONObject parseJSONObject(final String s) - throws ParseException { - - return parse(s); - } - - - /** - * Gets a generic member of a JSON object. - * - * @param o The JSON object. Must not be {@code null}. - * @param key The JSON object member key. Must not be {@code null}. - * @param clazz The expected class of the JSON object member value. Must - * not be {@code null}. - * - * @return The JSON object member value, may be {@code null}. - * - * @throws ParseException If the value is not of the expected type. - */ - @SuppressWarnings("unchecked") - private static T getGeneric(final JSONObject o, final String key, final Class clazz) - throws ParseException { - - if (o.get(key) == null) { - return null; - } - - Object value = o.get(key); - - if (! clazz.isAssignableFrom(value.getClass())) { - throw new ParseException("Unexpected type of JSON object member with key \"" + key + "\"", 0); - } - - return (T)value; - } - - - /** - * Gets a boolean member of a JSON object. - * - * @param o The JSON object. Must not be {@code null}. - * @param key The JSON object member key. Must not be {@code null}. - * - * @return The JSON object member value. - * - * @throws ParseException If the member is missing, the value is - * {@code null} or not of the expected type. - */ - public static boolean getBoolean(final JSONObject o, final String key) - throws ParseException { - - Boolean value = getGeneric(o, key, Boolean.class); - - if (value == null) { - throw new ParseException("JSON object member with key \"" + key + "\" is missing or null", 0); - } - - return value; - } - - - /** - * Gets an number member of a JSON object as {@code int}. - * - * @param o The JSON object. Must not be {@code null}. - * @param key The JSON object member key. Must not be {@code null}. - * - * @return The JSON object member value. - * - * @throws ParseException If the member is missing, the value is - * {@code null} or not of the expected type. - */ - public static int getInt(final JSONObject o, final String key) - throws ParseException { - - Number value = getGeneric(o, key, Number.class); - - if (value == null) { - throw new ParseException("JSON object member with key \"" + key + "\" is missing or null", 0); - } - - return value.intValue(); - } - - - /** - * Gets a number member of a JSON object as {@code long}. - * - * @param o The JSON object. Must not be {@code null}. - * @param key The JSON object member key. Must not be {@code null}. - * - * @return The JSON object member value. - * - * @throws ParseException If the member is missing, the value is - * {@code null} or not of the expected type. - */ - public static long getLong(final JSONObject o, final String key) - throws ParseException { - - Number value = getGeneric(o, key, Number.class); - - if (value == null) { - throw new ParseException("JSON object member with key \"" + key + "\" is missing or null", 0); - } - - return value.longValue(); - } - - - /** - * Gets a number member of a JSON object {@code float}. - * - * @param o The JSON object. Must not be {@code null}. - * @param key The JSON object member key. Must not be {@code null}. - * - * @return The JSON object member value, may be {@code null}. - * - * @throws ParseException If the member is missing, the value is - * {@code null} or not of the expected type. - */ - public static float getFloat(final JSONObject o, final String key) - throws ParseException { - - Number value = getGeneric(o, key, Number.class); - - if (value == null) { - throw new ParseException("JSON object member with key \"" + key + "\" is missing or null", 0); - } - - return value.floatValue(); - } - - - /** - * Gets a number member of a JSON object as {@code double}. - * - * @param o The JSON object. Must not be {@code null}. - * @param key The JSON object member key. Must not be {@code null}. - * - * @return The JSON object member value, may be {@code null}. - * - * @throws ParseException If the member is missing, the value is - * {@code null} or not of the expected type. - */ - public static double getDouble(final JSONObject o, final String key) - throws ParseException { - - Number value = getGeneric(o, key, Number.class); - - if (value == null) { - throw new ParseException("JSON object member with key \"" + key + "\" is missing or null", 0); - } - - return value.doubleValue(); - } - - - /** - * Gets a string member of a JSON object. - * - * @param o The JSON object. Must not be {@code null}. - * @param key The JSON object member key. Must not be {@code null}. - * - * @return The JSON object member value, may be {@code null}. - * - * @throws ParseException If the value is not of the expected type. - */ - public static String getString(final JSONObject o, final String key) - throws ParseException { - - return getGeneric(o, key, String.class); - } - - - /** - * Gets a string member of a JSON object as {@code java.net.URI}. - * - * @param o The JSON object. Must not be {@code null}. - * @param key The JSON object member key. Must not be {@code null}. - * - * @return The JSON object member value, may be {@code null}. - * - * @throws ParseException If the value is not of the expected type. - */ - public static URI getURI(final JSONObject o, final String key) - throws ParseException { - - String value = getString(o, key); - - if (value == null) { - return null; - } - - try { - return new URI(value); - - } catch (URISyntaxException e) { - - throw new ParseException(e.getMessage(), 0); - } - } - - - /** - * Gets a JSON array member of a JSON object. - * - * @param o The JSON object. Must not be {@code null}. - * @param key The JSON object member key. Must not be {@code null}. - * - * @return The JSON object member value, may be {@code null}. - * - * @throws ParseException If the value is not of the expected type. - */ - public static JSONArray getJSONArray(final JSONObject o, final String key) - throws ParseException { - - return getGeneric(o, key, JSONArray.class); - } - - - /** - * Gets a string array member of a JSON object. - * - * @param o The JSON object. Must not be {@code null}. - * @param key The JSON object member key. Must not be {@code null}. - * - * @return The JSON object member value, may be {@code null}. - * - * @throws ParseException If the value is not of the expected type. - */ - public static String[] getStringArray(final JSONObject o, final String key) - throws ParseException { - - JSONArray jsonArray = getJSONArray(o, key); - - if (jsonArray == null) { - return null; - } - - try { - return jsonArray.toArray(new String[0]); - - } catch (ArrayStoreException e) { - - throw new ParseException("JSON object member with key \"" + key + "\" is not an array of strings", 0); - } - } - - - /** - * Gets a string list member of a JSON object - * - * @param o The JSON object. Must not be {@code null}. - * @param key The JSON object member key. Must not be {@code null}. - * - * @return The JSON object member value, may be {@code null}. - * - * @throws ParseException If the value is not of the expected type. - */ - public static List getStringList(final JSONObject o, final String key) throws ParseException { - - String[] array = getStringArray(o, key); - - if (array == null) { - return null; - } - - return Arrays.asList(array); - } - - - /** - * Gets a JSON object member of a JSON object. - * - * @param o The JSON object. Must not be {@code null}. - * @param key The JSON object member key. Must not be {@code null}. - * - * @return The JSON object member value, may be {@code null}. - * - * @throws ParseException If the value is not of the expected type. - */ - public static JSONObject getJSONObject(final JSONObject o, final String key) - throws ParseException { - - return getGeneric(o, key, JSONObject.class); - } - - - /** - * Prevents public instantiation. - */ - private JSONObjectUtils() { } -} - diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/KeyUtils.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/KeyUtils.java deleted file mode 100644 index 320bfd322..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/KeyUtils.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * nimbus-jose-jwt - * - * Copyright 2012-2016, Connect2id Ltd and contributors. - * - * 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.util; - - -import javax.crypto.SecretKey; -import javax.crypto.spec.SecretKeySpec; - - -/** - * JCA key utilities. - * - * @author Vladimir Dzhuvinov - * @version 2018-02-11 - */ -public class KeyUtils { - - - /** - * Returns the specified secret key as a secret key with its algorithm - * set to "AES". - * - * @param secretKey The secret key, {@code null} if not specified. - * - * @return The AES secret key, {@code null} if not specified. - */ - public static SecretKey toAESKey(final SecretKey secretKey) { - - if (secretKey == null) { - return null; - } - - return new SecretKeySpec(secretKey.getEncoded(), "AES"); - } - - - /** - * Prevents public instantiation. - */ - private KeyUtils() {} -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/Resource.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/Resource.java deleted file mode 100644 index 8c71ba62f..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/Resource.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * 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.util; - - -import net.jcip.annotations.Immutable; - - -/** - * Resource with optional associated content type. - */ -@Immutable -public class Resource { - - - /** - * The content. - */ - private final String content; - - - /** - * The content type. - */ - private final String contentType; - - - /** - * Creates a new resource with optional associated content type. - * - * @param content The resource content, empty string if none. Must - * not be {@code null}. - * @param contentType The resource content type, {@code null} if not - * specified. - */ - public Resource(final String content, final String contentType) { - - if (content == null) { - throw new IllegalArgumentException("The resource content must not be null"); - } - - this.content = content; - this.contentType = contentType; - } - - - /** - * Gets the content of this resource. - * - * @return The content, empty string if none. - */ - public String getContent() { - - return content; - } - - - /** - * Gets the content type of this resource. - * - * @return The content type, {@code null} if not specified. - */ - public String getContentType() { - - return contentType; - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/ResourceRetriever.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/ResourceRetriever.java deleted file mode 100644 index 3715b428b..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/ResourceRetriever.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * 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.util; - - -import java.io.IOException; -import java.net.URL; - - -/** - * Retriever of resources specified by URL. - */ -public interface ResourceRetriever { - - - /** - * Retrieves the resource from the specified HTTP(S) URL. - * - * @param url The URL of the resource. Its scheme must be HTTP or - * HTTPS. Must not be {@code null}. - * - * @return The retrieved resource. - * - * @throws IOException If the HTTP connection to the specified URL - * failed or the resource couldn't be retrieved. - */ - Resource retrieveResource(final URL url) - throws IOException; -} \ No newline at end of file diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/RestrictedResourceRetriever.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/RestrictedResourceRetriever.java deleted file mode 100644 index a4b993d04..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/RestrictedResourceRetriever.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * 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.util; - - -/** - * Retriever of resources specified by URL which permits setting of HTTP - * connect and read timeouts as well as a size limit. - */ -public interface RestrictedResourceRetriever extends ResourceRetriever { - - - /** - * Gets the HTTP connect timeout. - * - * @return The HTTP connect timeout, in milliseconds, zero for - * infinite. - */ - int getConnectTimeout(); - - - /** - * Sets the HTTP connect timeout. - * - * @param connectTimeoutMs The HTTP connect timeout, in milliseconds, - * zero for infinite. Must not be negative. - */ - void setConnectTimeout(final int connectTimeoutMs); - - - /** - * Gets the HTTP read timeout. - * - * @return The HTTP read timeout, in milliseconds, zero for infinite. - */ - int getReadTimeout(); - - - /** - * Sets the HTTP read timeout. - * - * @param readTimeoutMs The HTTP read timeout, in milliseconds, zero - * for infinite. Must not be negative. - */ - void setReadTimeout(final int readTimeoutMs); - - - /** - * Gets the HTTP entity size limit. - * - * @return The HTTP entity size limit, in bytes, zero for infinite. - */ - int getSizeLimit(); - - - /** - * Sets the HTTP entity size limit. - * - * @param sizeLimitBytes The HTTP entity size limit, in bytes, zero for - * infinite. Must not be negative. - */ - void setSizeLimit(int sizeLimitBytes); -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/StandardCharset.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/StandardCharset.java deleted file mode 100644 index b6214872d..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/StandardCharset.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * 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.util; - - -import java.nio.charset.Charset; - - -/** - * UTF-8 is the standard charset in JOSE. Works around missing - * {@link java.nio.charset.StandardCharsets} in Android below API level 19. - */ -public final class StandardCharset { - - - /** - * UTF-8 - */ - public static final Charset UTF_8 = Charset.forName("UTF-8"); - - - /** - * Prevents public instantiation. - */ - private StandardCharset() {} -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/X509CertChainUtils.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/X509CertChainUtils.java deleted file mode 100644 index 34f255de6..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/X509CertChainUtils.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * 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.util; - - -import java.security.cert.X509Certificate; -import java.text.ParseException; -import java.util.LinkedList; -import java.util.List; - -import net.minidev.json.JSONArray; - - -/** - * X.509 certificate chain utilities. - * - * @author Vladimir Dzhuvinov - * @version 2018-02-27 - */ -public class X509CertChainUtils { - - - /** - * Converts the specified JSON array of strings to a list of Base64 - * encoded objects. - * - * @param jsonArray The JSON array of string, {@code null} if not - * specified. - * - * @return The Base64 list, {@code null} if not specified. - * - * @throws ParseException If parsing failed. - */ - public static List toBase64List(final JSONArray jsonArray) - throws ParseException { - - if (jsonArray == null) - return null; - - List chain = new LinkedList<>(); - - for (int i=0; i < jsonArray.size(); i++) { - - Object item = jsonArray.get(i); - - if (item == null) { - throw new ParseException("The X.509 certificate at position " + i + " must not be null", 0); - } - - if (! (item instanceof String)) { - throw new ParseException("The X.509 certificate at position " + i + " must be encoded as a Base64 string", 0); - } - - chain.add(new Base64((String)item)); - } - - return chain; - } - - - /** - * Parses a X.509 certificate chain from the specified Base64-encoded - * DER-encoded representation. - * - * @param b64List The Base64-encoded DER-encoded X.509 certificate - * chain, {@code null} if not specified. - * - * @return The X.509 certificate chain, {@code null} if not specified. - * - * @throws ParseException If parsing failed. - */ - public static List parse(final List b64List) - throws ParseException { - - if (b64List == null) - return null; - - List out = new LinkedList<>(); - - for (int i=0; i < b64List.size(); i++) { - - if (b64List.get(i)== null) continue; // skip - - X509Certificate cert = X509CertUtils.parse(b64List.get(i).decode()); - - if (cert == null) { - throw new ParseException("Invalid X.509 certificate at position " + i, 0); - } - - out.add(cert); - } - - return out; - } - - - /** - * Prevents public instantiation. - */ - private X509CertChainUtils() {} -} \ No newline at end of file diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/X509CertUtils.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/X509CertUtils.java deleted file mode 100644 index ef4914ab1..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/X509CertUtils.java +++ /dev/null @@ -1,178 +0,0 @@ -/* - * 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.util; - - -import java.io.ByteArrayInputStream; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.security.cert.*; - - -/** - * X.509 certificate utilities. - * - * @author Vladimir Dzhuvinov - * @version 2018-06-07 - */ -public class X509CertUtils { - - - /** - * The PEM start marker. - */ - private static final String PEM_BEGIN_MARKER = "-----BEGIN CERTIFICATE-----"; - - - /** - * The PEM end marker. - */ - private static final String PEM_END_MARKER = "-----END CERTIFICATE-----"; - - - /** - * Parses a DER-encoded X.509 certificate. - * - * @param derEncodedCert The DER-encoded X.509 certificate, as a byte - * array. May be {@code null}. - * - * @return The X.509 certificate, {@code null} if parsing failed. - */ - public static X509Certificate parse(final byte[] derEncodedCert) { - - if (derEncodedCert == null || derEncodedCert.length == 0) { - return null; - } - - final Certificate cert; - try { - CertificateFactory cf = CertificateFactory.getInstance("X.509"); - cert = cf.generateCertificate(new ByteArrayInputStream(derEncodedCert)); - } catch (CertificateException e) { - return null; - } - - if (! (cert instanceof X509Certificate)) { - return null; - } - - return (X509Certificate)cert; - } - - - /** - * Parses a PEM-encoded X.509 certificate. - * - * @param pemEncodedCert The PEM-encoded X.509 certificate, as a - * string. May be {@code null}. - * - * @return The X.509 certificate, {@code null} if parsing failed. - */ - public static X509Certificate parse(final String pemEncodedCert) { - - if (pemEncodedCert == null || pemEncodedCert.isEmpty()) { - return null; - } - - final int markerStart = pemEncodedCert.indexOf(PEM_BEGIN_MARKER); - - if (markerStart < 0) { - return null; - } - - String buf = pemEncodedCert.substring(markerStart + PEM_BEGIN_MARKER.length()); - - final int markerEnd = buf.indexOf(PEM_END_MARKER); - - if (markerEnd < 0) { - return null; - } - - buf = buf.substring(0, markerEnd); - - buf = buf.replaceAll("\\s", ""); - - return parse(new Base64(buf).decode()); - } - - - /** - * Returns the specified X.509 certificate as PEM-encoded string. - * - * @param cert The X.509 certificate. Must not be {@code null}. - * - * @return The PEM-encoded X.509 certificate, {@code null} if encoding - * failed. - */ - public static String toPEMString(final X509Certificate cert) { - - return toPEMString(cert, true); - } - - - /** - * Returns the specified X.509 certificate as PEM-encoded string. - * - * @param cert The X.509 certificate. Must not be - * {@code null}. - * @param withLineBreaks {@code false} to suppress line breaks. - * - * @return The PEM-encoded X.509 certificate, {@code null} if encoding - * failed. - */ - public static String toPEMString(final X509Certificate cert, final boolean withLineBreaks) { - - StringBuilder sb = new StringBuilder(); - sb.append(PEM_BEGIN_MARKER); - - if (withLineBreaks) - sb.append('\n'); - - try { - sb.append(Base64.encode(cert.getEncoded()).toString()); - } catch (CertificateEncodingException e) { - return null; - } - - if (withLineBreaks) - sb.append('\n'); - - sb.append(PEM_END_MARKER); - return sb.toString(); - } - - - /** - * Computes the X.509 certificate SHA-256 thumbprint ({@code x5t#S256}). - * - * @param cert The X.509 certificate. Must not be {@code null}. - * - * @return The SHA-256 thumbprint, BASE64URL-encoded, {@code null} if - * a certificate encoding exception is encountered. - */ - public static Base64URL computeSHA256Thumbprint(final X509Certificate cert) { - - try { - byte[] derEncodedCert = cert.getEncoded(); - MessageDigest sha256 = MessageDigest.getInstance("SHA-256"); - return Base64URL.encode(sha256.digest(derEncodedCert)); - } catch (NoSuchAlgorithmException | CertificateEncodingException e) { - return null; - } - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/package-info.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/package-info.java deleted file mode 100644 index f0c0cf943..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jose/util/package-info.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * 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. - */ - -/** - * Utility interfaces and classes. - */ -package com.nimbusds.jose.util; diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/EncryptedJWT.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/EncryptedJWT.java deleted file mode 100644 index 383009ca7..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/EncryptedJWT.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * 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.jwt; - - -import java.text.ParseException; - -import net.jcip.annotations.ThreadSafe; - -import net.minidev.json.JSONObject; - -import com.nimbusds.jose.JOSEObject; -import com.nimbusds.jose.JWEHeader; -import com.nimbusds.jose.JWEObject; -import com.nimbusds.jose.Payload; -import com.nimbusds.jose.util.Base64URL; - - -/** - * Encrypted JSON Web Token (JWT). This class is thread-safe. - * - * @author Vladimir Dzhuvinov - * @version 2015-08-19 - */ -@ThreadSafe -public class EncryptedJWT extends JWEObject implements JWT { - - - private static final long serialVersionUID = 1L; - - - /** - * Creates a new to-be-encrypted JSON Web Token (JWT) with the specified - * header and claims set. The initial state will be - * {@link com.nimbusds.jose.JWEObject.State#UNENCRYPTED unencrypted}. - * - * @param header The JWE header. Must not be {@code null}. - * @param claimsSet The JWT claims set. Must not be {@code null}. - */ - public EncryptedJWT(final JWEHeader header, final JWTClaimsSet claimsSet) { - - super(header, new Payload(claimsSet.toJSONObject())); - } - - - /** - * Creates a new encrypted JSON Web Token (JWT) with the specified - * serialised parts. The state will be - * {@link com.nimbusds.jose.JWEObject.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 - * vectory. 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 integrity - * value. Empty of {@code null} if none. - * - * @throws ParseException If parsing of the serialised parts failed. - */ - public EncryptedJWT(final Base64URL firstPart, - final Base64URL secondPart, - final Base64URL thirdPart, - final Base64URL fourthPart, - final Base64URL fifthPart) - throws ParseException { - - super(firstPart, secondPart, thirdPart, fourthPart, fifthPart); - } - - - @Override - public JWTClaimsSet getJWTClaimsSet() - throws ParseException { - - Payload payload = getPayload(); - - if (payload == null) { - return null; - } - - JSONObject json = payload.toJSONObject(); - - if (json == null) { - throw new ParseException("Payload of JWE object is not a valid JSON object", 0); - } - - return JWTClaimsSet.parse(json); - } - - - /** - * Parses an encrypted JSON Web Token (JWT) from the specified string in - * compact format. - * - * @param s The string to parse. Must not be {@code null}. - * - * @return The encrypted JWT. - * - * @throws ParseException If the string couldn't be parsed to a valid - * encrypted JWT. - */ - public static EncryptedJWT 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 EncryptedJWT(parts[0], parts[1], parts[2], parts[3], parts[4]); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/JWT.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/JWT.java deleted file mode 100644 index 6de86aecc..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/JWT.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * 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.jwt; - - -import java.io.Serializable; -import java.text.ParseException; - -import com.nimbusds.jose.Header; -import com.nimbusds.jose.util.Base64URL; - - -/** - * JSON Web Token (JWT) interface. - * - * @author Vladimir Dzhuvinov - * @version 2014-08-19 - */ -public interface JWT extends Serializable { - - - /** - * Gets the JOSE header of the JSON Web Token (JWT). - * - * @return The header. - */ - Header getHeader(); - - - /** - * Gets the claims set of the JSON Web Token (JWT). - * - * @return The claims set, {@code null} if not available (for an - * encrypted JWT that isn't decrypted). - * - * @throws ParseException If the payload of the JWT doesn't represent a - * valid JSON object and a JWT claims set. - */ - JWTClaimsSet getJWTClaimsSet() - throws ParseException; - - - /** - * Gets the original parsed Base64URL parts used to create the JSON Web - * Token (JWT). - * - * @return The original Base64URL parts used to creates the JWT, - * {@code null} if the JWT was created from scratch. The - * individual parts may be empty or {@code null} to indicate a - * missing part. - */ - Base64URL[] getParsedParts(); - - - /** - * Gets the original parsed string used to create the JSON Web Token - * (JWT). - * - * @see #getParsedParts - * - * @return The parsed string used to create the JWT, {@code null} if - * the JWT was created from scratch. - */ - String getParsedString(); - - - /** - * Serialises the JSON Web Token (JWT) to its compact format consisting - * of Base64URL-encoded parts delimited by period ('.') characters. - * - * @return The serialised JWT. - * - * @throws IllegalStateException If the JWT is not in a state that - * permits serialisation. - */ - String serialize(); -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/JWTClaimsSet.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/JWTClaimsSet.java deleted file mode 100644 index a7efcf2b8..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/JWTClaimsSet.java +++ /dev/null @@ -1,979 +0,0 @@ -/* - * 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.jwt; - - -import java.io.Serializable; -import java.net.URI; -import java.net.URISyntaxException; -import java.text.ParseException; -import java.util.*; - -import com.nimbusds.jose.util.DateUtils; -import com.nimbusds.jose.util.JSONObjectUtils; -import net.jcip.annotations.Immutable; -import net.minidev.json.JSONArray; -import net.minidev.json.JSONObject; - - -/** - * JSON Web Token (JWT) claims set. This class is immutable. - * - *

Supports all {@link #getRegisteredNames()} registered claims} of the JWT - * specification: - * - *

    - *
  • iss - Issuer - *
  • sub - Subject - *
  • aud - Audience - *
  • exp - Expiration Time - *
  • nbf - Not Before - *
  • iat - Issued At - *
  • jti - JWT ID - *
- * - *

The set may also contain custom claims; these will be serialised and - * parsed along the registered ones. - * - *

Example JWT claims set: - * - *

- * {
- *   "sub"                        : "joe",
- *   "exp"                        : 1300819380,
- *   "http://example.com/is_root" : true
- * }
- * 
- * - *

Example usage: - * - *

- * JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
- *     .subject("joe")
- *     .expirationDate(new Date(1300819380 * 1000l)
- *     .claim("http://example.com/is_root", true)
- *     .build();
- * 
- * - * @author Vladimir Dzhuvinov - * @author Justin Richer - * @version 2019-04-15 - */ -@Immutable -public final class JWTClaimsSet implements Serializable { - - - private static final long serialVersionUID = 1L; - - - private static final String ISSUER_CLAIM = "iss"; - private static final String SUBJECT_CLAIM = "sub"; - private static final String AUDIENCE_CLAIM = "aud"; - private static final String EXPIRATION_TIME_CLAIM = "exp"; - private static final String NOT_BEFORE_CLAIM = "nbf"; - private static final String ISSUED_AT_CLAIM = "iat"; - private static final String JWT_ID_CLAIM = "jti"; - - - /** - * The registered claim names. - */ - private static final Set REGISTERED_CLAIM_NAMES; - - - /** - * Initialises the registered claim name set. - */ - static { - Set n = new HashSet<>(); - - n.add(ISSUER_CLAIM); - n.add(SUBJECT_CLAIM); - n.add(AUDIENCE_CLAIM); - n.add(EXPIRATION_TIME_CLAIM); - n.add(NOT_BEFORE_CLAIM); - n.add(ISSUED_AT_CLAIM); - n.add(JWT_ID_CLAIM); - - REGISTERED_CLAIM_NAMES = Collections.unmodifiableSet(n); - } - - - /** - * Builder for constructing JSON Web Token (JWT) claims sets. - * - *

Example usage: - * - *

-	 * JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
-	 *     .subject("joe")
-	 *     .expirationDate(new Date(1300819380 * 1000l)
-	 *     .claim("http://example.com/is_root", true)
-	 *     .build();
-	 * 
- */ - public static class Builder { - - - /** - * The claims. - */ - private final Map claims = new LinkedHashMap<>(); - - - /** - * Creates a new builder. - */ - public Builder() { - - // Nothing to do - } - - - /** - * Creates a new builder with the claims from the specified - * set. - * - * @param jwtClaimsSet The JWT claims set to use. Must not be - * {@code null}. - */ - public Builder(final JWTClaimsSet jwtClaimsSet) { - - claims.putAll(jwtClaimsSet.claims); - } - - - /** - * Sets the issuer ({@code iss}) claim. - * - * @param iss The issuer claim, {@code null} if not specified. - * - * @return This builder. - */ - public Builder issuer(final String iss) { - - claims.put(ISSUER_CLAIM, iss); - return this; - } - - - /** - * Sets the subject ({@code sub}) claim. - * - * @param sub The subject claim, {@code null} if not specified. - * - * @return This builder. - */ - public Builder subject(final String sub) { - - claims.put(SUBJECT_CLAIM, sub); - return this; - } - - - /** - * Sets the audience ({@code aud}) claim. - * - * @param aud The audience claim, {@code null} if not - * specified. - * - * @return This builder. - */ - public Builder audience(final List aud) { - - claims.put(AUDIENCE_CLAIM, aud); - return this; - } - - - /** - * Sets a single-valued audience ({@code aud}) claim. - * - * @param aud The audience claim, {@code null} if not - * specified. - * - * @return This builder. - */ - public Builder audience(final String aud) { - - if (aud == null) { - claims.put(AUDIENCE_CLAIM, null); - } else { - claims.put(AUDIENCE_CLAIM, Collections.singletonList(aud)); - } - return this; - } - - - /** - * Sets the expiration time ({@code exp}) claim. - * - * @param exp The expiration time, {@code null} if not - * specified. - * - * @return This builder. - */ - public Builder expirationTime(final Date exp) { - - claims.put(EXPIRATION_TIME_CLAIM, exp); - return this; - } - - - /** - * Sets the not-before ({@code nbf}) claim. - * - * @param nbf The not-before claim, {@code null} if not - * specified. - * - * @return This builder. - */ - public Builder notBeforeTime(final Date nbf) { - - claims.put(NOT_BEFORE_CLAIM, nbf); - return this; - } - - - /** - * Sets the issued-at ({@code iat}) claim. - * - * @param iat The issued-at claim, {@code null} if not - * specified. - * - * @return This builder. - */ - public Builder issueTime(final Date iat) { - - claims.put(ISSUED_AT_CLAIM, iat); - return this; - } - - - /** - * Sets the JWT ID ({@code jti}) claim. - * - * @param jti The JWT ID claim, {@code null} if not specified. - * - * @return This builder. - */ - public Builder jwtID(final String jti) { - - claims.put(JWT_ID_CLAIM, jti); - return this; - } - - - /** - * Sets the specified claim (registered or custom). - * - * @param name The name of the claim to set. Must not be - * {@code null}. - * @param value The value of the claim to set, {@code null} if - * not specified. Should map to a JSON entity. - * - * @return This builder. - */ - public Builder claim(final String name, final Object value) { - - claims.put(name, value); - return this; - } - - public Builder claim(HashMap claimsFields) { - claims.putAll(claimsFields); - return this; - } - - - /** - * Builds a new JWT claims set. - * - * @return The JWT claims set. - */ - public JWTClaimsSet build() { - - return new JWTClaimsSet(claims); - } - } - - - /** - * The claims map. - */ - private final Map claims = new LinkedHashMap<>(); - - - /** - * Creates a new JWT claims set. - * - * @param claims The JWT claims set as a map. Must not be {@code null}. - */ - private JWTClaimsSet(final Map claims) { - - this.claims.putAll(claims); - } - - - /** - * Gets the registered JWT claim names. - * - * @return The registered claim names, as a unmodifiable set. - */ - public static Set getRegisteredNames() { - - return REGISTERED_CLAIM_NAMES; - } - - - /** - * Gets the issuer ({@code iss}) claim. - * - * @return The issuer claim, {@code null} if not specified. - */ - public String getIssuer() { - - try { - return getStringClaim(ISSUER_CLAIM); - } catch (ParseException e) { - return null; - } - } - - - /** - * Gets the subject ({@code sub}) claim. - * - * @return The subject claim, {@code null} if not specified. - */ - public String getSubject() { - - try { - return getStringClaim(SUBJECT_CLAIM); - } catch (ParseException e) { - return null; - } - } - - - /** - * Gets the audience ({@code aud}) claim. - * - * @return The audience claim, empty list if not specified. - */ - public List getAudience() { - - Object audValue = getClaim(AUDIENCE_CLAIM); - - if (audValue instanceof String) { - // Special case - return Collections.singletonList((String)audValue); - } - - List aud; - try { - aud = getStringListClaim(AUDIENCE_CLAIM); - } catch (ParseException e) { - return Collections.emptyList(); - } - return aud != null ? Collections.unmodifiableList(aud) : Collections.emptyList(); - } - - - /** - * Gets the expiration time ({@code exp}) claim. - * - * @return The expiration time, {@code null} if not specified. - */ - public Date getExpirationTime() { - - try { - return getDateClaim(EXPIRATION_TIME_CLAIM); - } catch (ParseException e) { - return null; - } - } - - - /** - * Gets the not-before ({@code nbf}) claim. - * - * @return The not-before claim, {@code null} if not specified. - */ - public Date getNotBeforeTime() { - - try { - return getDateClaim(NOT_BEFORE_CLAIM); - } catch (ParseException e) { - return null; - } - } - - - /** - * Gets the issued-at ({@code iat}) claim. - * - * @return The issued-at claim, {@code null} if not specified. - */ - public Date getIssueTime() { - - try { - return getDateClaim(ISSUED_AT_CLAIM); - } catch (ParseException e) { - return null; - } - } - - - /** - * Gets the JWT ID ({@code jti}) claim. - * - * @return The JWT ID claim, {@code null} if not specified. - */ - public String getJWTID() { - - try { - return getStringClaim(JWT_ID_CLAIM); - } catch (ParseException e) { - return null; - } - } - - - /** - * Gets the specified claim (registered or custom). - * - * @param name The name of the claim. Must not be {@code null}. - * - * @return The value of the claim, {@code null} if not specified. - */ - public Object getClaim(final String name) { - - return claims.get(name); - } - - - /** - * Gets the specified claim (registered or custom) as - * {@link java.lang.String}. - * - * @param name The name of the claim. Must not be {@code null}. - * - * @return The value of the claim, {@code null} if not specified. - * - * @throws ParseException If the claim value is not of the required - * type. - */ - public String getStringClaim(final String name) - throws ParseException { - - Object value = getClaim(name); - - if (value == null || value instanceof String) { - return (String)value; - } else { - throw new ParseException("The \"" + name + "\" claim is not a String", 0); - } - } - - - /** - * Gets the specified claims (registered or custom) as a - * {@link java.lang.String} array. - * - * @param name The name of the claim. Must not be {@code null}. - * - * @return The value of the claim, {@code null} if not specified. - * - * @throws ParseException If the claim value is not of the required - * type. - */ - public String[] getStringArrayClaim(final String name) - throws ParseException { - - Object value = getClaim(name); - - if (value == null) { - return null; - } - - List list; - - try { - list = (List)getClaim(name); - - } catch (ClassCastException e) { - throw new ParseException("The \"" + name + "\" claim is not a list / JSON array", 0); - } - - String[] stringArray = new String[list.size()]; - - for (int i=0; i < stringArray.length; i++) { - - try { - stringArray[i] = (String)list.get(i); - } catch (ClassCastException e) { - throw new ParseException("The \"" + name + "\" claim is not a list / JSON array of strings", 0); - } - } - - return stringArray; - } - - - /** - * Gets the specified claims (registered or custom) as a - * {@link java.util.List} list of strings. - * - * @param name The name of the claim. Must not be {@code null}. - * - * @return The value of the claim, {@code null} if not specified. - * - * @throws ParseException If the claim value is not of the required - * type. - */ - public List getStringListClaim(final String name) - throws ParseException { - - String[] stringArray = getStringArrayClaim(name); - - if (stringArray == null) { - return null; - } - - return Collections.unmodifiableList(Arrays.asList(stringArray)); - } - - - /** - * Gets the specified claim (registered or custom) as a - * {@link java.net.URI}. - * - * @param name The name of the claim. Must not be {@code null}. - * - * @return The value of the claim, {@code null} if not specified. - * - * @throws ParseException If the claim couldn't be parsed to a URI. - */ - public URI getURIClaim(final String name) - throws ParseException { - - String uriString = getStringClaim(name); - - if (uriString == null) { - return null; - } - - try { - return new URI(uriString); - } catch (URISyntaxException e) { - throw new ParseException("The \"" + name + "\" claim is not a URI: " + e.getMessage(), 0); - } - } - - - /** - * Gets the specified claim (registered or custom) as - * {@link java.lang.Boolean}. - * - * @param name The name of the claim. Must not be {@code null}. - * - * @return The value of the claim, {@code null} if not specified. - * - * @throws ParseException If the claim value is not of the required - * type. - */ - public Boolean getBooleanClaim(final String name) - throws ParseException { - - Object value = getClaim(name); - - if (value == null || value instanceof Boolean) { - return (Boolean)value; - } else { - throw new ParseException("The \"" + name + "\" claim is not a Boolean", 0); - } - } - - - /** - * Gets the specified claim (registered or custom) as - * {@link java.lang.Integer}. - * - * @param name The name of the claim. Must not be {@code null}. - * - * @return The value of the claim, {@code null} if not specified. - * - * @throws ParseException If the claim value is not of the required - * type. - */ - public Integer getIntegerClaim(final String name) - throws ParseException { - - Object value = getClaim(name); - - if (value == null) { - return null; - } else if (value instanceof Number) { - return ((Number)value).intValue(); - } else { - throw new ParseException("The \"" + name + "\" claim is not an Integer", 0); - } - } - - - /** - * Gets the specified claim (registered or custom) as - * {@link java.lang.Long}. - * - * @param name The name of the claim. Must not be {@code null}. - * - * @return The value of the claim, {@code null} if not specified. - * - * @throws ParseException If the claim value is not of the required - * type. - */ - public Long getLongClaim(final String name) - throws ParseException { - - Object value = getClaim(name); - - if (value == null) { - return null; - } else if (value instanceof Number) { - return ((Number)value).longValue(); - } else { - throw new ParseException("The \"" + name + "\" claim is not a Number", 0); - } - } - - - /** - * Gets the specified claim (registered or custom) as - * {@link java.util.Date}. The claim may be represented by a Date - * object or a number of a seconds since the Unix epoch. - * - * @param name The name of the claim. Must not be {@code null}. - * - * @return The value of the claim, {@code null} if not specified. - * - * @throws ParseException If the claim value is not of the required - * type. - */ - public Date getDateClaim(final String name) - throws ParseException { - - Object value = getClaim(name); - - if (value == null) { - return null; - } else if (value instanceof Date) { - return (Date)value; - } else if (value instanceof Number) { - return DateUtils.fromSecondsSinceEpoch(((Number)value).longValue()); - } else { - throw new ParseException("The \"" + name + "\" claim is not a Date", 0); - } - } - - - /** - * Gets the specified claim (registered or custom) as - * {@link java.lang.Float}. - * - * @param name The name of the claim. Must not be {@code null}. - * - * @return The value of the claim, {@code null} if not specified. - * - * @throws ParseException If the claim value is not of the required - * type. - */ - public Float getFloatClaim(final String name) - throws ParseException { - - Object value = getClaim(name); - - if (value == null) { - return null; - } else if (value instanceof Number) { - return ((Number)value).floatValue(); - } else { - throw new ParseException("The \"" + name + "\" claim is not a Float", 0); - } - } - - - /** - * Gets the specified claim (registered or custom) as - * {@link java.lang.Double}. - * - * @param name The name of the claim. Must not be {@code null}. - * - * @return The value of the claim, {@code null} if not specified. - * - * @throws ParseException If the claim value is not of the required - * type. - */ - public Double getDoubleClaim(final String name) - throws ParseException { - - Object value = getClaim(name); - - if (value == null) { - return null; - } else if (value instanceof Number) { - return ((Number)value).doubleValue(); - } else { - throw new ParseException("The \"" + name + "\" claim is not a Double", 0); - } - } - - - /** - * Gets the specified claim (registered or custom) as a - * {@link net.minidev.json.JSONObject}. - * - * @param name The name of the claim. Must not be {@code null}. - * - * @return The value of the claim, {@code null} if not specified. - * - * @throws ParseException If the claim value is not of the required - * type. - */ - public JSONObject getJSONObjectClaim(final String name) - throws ParseException { - - Object value = getClaim(name); - - if (value == null) { - return null; - } else if (value instanceof JSONObject) { - return (JSONObject)value; - } else if (value instanceof Map) { - JSONObject jsonObject = new JSONObject(); - Map map = (Map)value; - for (Map.Entry entry: map.entrySet()) { - if (entry.getKey() instanceof String) { - jsonObject.put((String)entry.getKey(), entry.getValue()); - } - } - return jsonObject; - } else { - throw new ParseException("The \"" + name + "\" claim is not a JSON object or Map", 0); - } - } - - - /** - * Gets the claims (registered and custom). - * - *

Note that the registered claims Expiration-Time ({@code exp}), - * Not-Before-Time ({@code nbf}) and Issued-At ({@code iat}) will be - * returned as {@code java.util.Date} instances. - * - * @return The claims, as an unmodifiable map, empty map if none. - */ - public Map getClaims() { - - return Collections.unmodifiableMap(claims); - } - - - /** - * Returns the JSON object representation of the claims set. The claims - * are serialised according to their insertion order. Claims with - * {@code null} values are not output. - * - * @return The JSON object representation. - */ - public JSONObject toJSONObject() { - - return toJSONObject(false); - } - - - /** - * Returns the JSON object representation of the claims set. The claims - * are serialised according to their insertion order. - * - * @param includeClaimsWithNullValues If {@code true} claims with - * {@code null} values will also be - * output. - * - * @return The JSON object representation. - */ - public JSONObject toJSONObject(final boolean includeClaimsWithNullValues) { - - JSONObject o = new JSONObject(); - - for (Map.Entry claim: claims.entrySet()) { - - if (claim.getValue() instanceof Date) { - - // Transform dates to Unix timestamps - Date dateValue = (Date) claim.getValue(); - o.put(claim.getKey(), DateUtils.toSecondsSinceEpoch(dateValue)); - - } else if (AUDIENCE_CLAIM.equals(claim.getKey())) { - - // Serialise single audience list and string - List audList = getAudience(); - - if (audList != null && ! audList.isEmpty()) { - if (audList.size() == 1) { - o.put(AUDIENCE_CLAIM, audList.get(0)); - } else { - JSONArray audArray = new JSONArray(); - audArray.addAll(audList); - o.put(AUDIENCE_CLAIM, audArray); - } - } else if (includeClaimsWithNullValues) { - o.put(AUDIENCE_CLAIM, null); - } - - } else if (claim.getValue() != null) { - o.put(claim.getKey(), claim.getValue()); - } else if (includeClaimsWithNullValues) { - o.put(claim.getKey(), null); - } - } - - return o; - } - - - @Override - public String toString() { - - return toJSONObject().toJSONString(); - } - - - /** - * Returns a transformation of this JWT claims set. - * - * @param Type of the result. - * @param transformer The JWT claims set transformer. Must not be - * {@code null}. - * - * @return The transformed JWT claims set. - */ - public T toType(final JWTClaimsSetTransformer transformer) { - - return transformer.transform(this); - } - - - /** - * Parses a JSON Web Token (JWT) claims set from the specified JSON - * object representation. - * - * @param json The JSON object to parse. Must not be {@code null}. - * - * @return The JWT claims set. - * - * @throws ParseException If the specified JSON object doesn't - * represent a valid JWT claims set. - */ - public static JWTClaimsSet parse(final JSONObject json) - throws ParseException { - - JWTClaimsSet.Builder builder = new JWTClaimsSet.Builder(); - - // Parse registered + custom params - for (final String name: json.keySet()) { - - if (name.equals(ISSUER_CLAIM)) { - - builder.issuer(JSONObjectUtils.getString(json, ISSUER_CLAIM)); - - } else if (name.equals(SUBJECT_CLAIM)) { - - builder.subject(JSONObjectUtils.getString(json, SUBJECT_CLAIM)); - - } else if (name.equals(AUDIENCE_CLAIM)) { - - Object audValue = json.get(AUDIENCE_CLAIM); - - if (audValue instanceof String) { - List singleAud = new ArrayList<>(); - singleAud.add(JSONObjectUtils.getString(json, AUDIENCE_CLAIM)); - builder.audience(singleAud); - } else if (audValue instanceof List) { - builder.audience(JSONObjectUtils.getStringList(json, AUDIENCE_CLAIM)); - } else if (audValue == null) { - builder.audience((String)null); - } - - } else if (name.equals(EXPIRATION_TIME_CLAIM)) { - - builder.expirationTime(new Date(JSONObjectUtils.getLong(json, EXPIRATION_TIME_CLAIM) * 1000)); - - } else if (name.equals(NOT_BEFORE_CLAIM)) { - - builder.notBeforeTime(new Date(JSONObjectUtils.getLong(json, NOT_BEFORE_CLAIM) * 1000)); - - } else if (name.equals(ISSUED_AT_CLAIM)) { - - builder.issueTime(new Date(JSONObjectUtils.getLong(json, ISSUED_AT_CLAIM) * 1000)); - - } else if (name.equals(JWT_ID_CLAIM)) { - - builder.jwtID(JSONObjectUtils.getString(json, JWT_ID_CLAIM)); - - } else { - builder.claim(name, json.get(name)); - } - } - - return builder.build(); - } - - - /** - * Parses a JSON Web Token (JWT) claims set from the specified JSON - * object string representation. - * - * @param s The JSON object string to parse. Must not be {@code null}. - * - * @return The JWT claims set. - * - * @throws ParseException If the specified JSON object string doesn't - * represent a valid JWT claims set. - */ - public static JWTClaimsSet parse(final String s) - throws ParseException { - - return parse(JSONObjectUtils.parse(s)); - } - - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof JWTClaimsSet)) return false; - JWTClaimsSet that = (JWTClaimsSet) o; - return Objects.equals(claims, that.claims); - } - - - @Override - public int hashCode() { - return Objects.hash(claims); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/JWTClaimsSetTransformer.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/JWTClaimsSetTransformer.java deleted file mode 100644 index a8b9f787e..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/JWTClaimsSetTransformer.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * 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.jwt; - - -/** - * Generic JWT claims set type transformer. Implementations should be - * tread-safe. - */ -public interface JWTClaimsSetTransformer { - - - /** - * Transforms the specified JWT claims set into the desired type. - * - * @param claimsSet The JWT claims set. Not {@code null}. - * - * @return The desired type. - */ - T transform(final JWTClaimsSet claimsSet); -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/JWTParser.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/JWTParser.java deleted file mode 100644 index b8a0cbb7f..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/JWTParser.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * 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.jwt; - - -import java.text.ParseException; - -import net.minidev.json.JSONObject; - -import com.nimbusds.jose.Algorithm; -import com.nimbusds.jose.Header; -import com.nimbusds.jose.JWEAlgorithm; -import com.nimbusds.jose.JWSAlgorithm; -import com.nimbusds.jose.util.Base64URL; -import com.nimbusds.jose.util.JSONObjectUtils; - - -/** - * Parser for unsecured (plain), signed and encrypted JSON Web Tokens (JWTs). - * - * @author Vladimir Dzhuvinov - * @author Junya Hayashi - * @version 2015-06-14 - */ -public final class JWTParser { - - - /** - * Parses an unsecured (plain), signed or encrypted JSON Web Token - * (JWT) from the specified string in compact format. - * - * @param s The string to parse. Must not be {@code null}. - * - * @return The corresponding {@link PlainJWT}, {@link SignedJWT} or - * {@link EncryptedJWT} instance. - * - * @throws ParseException If the string couldn't be parsed to a valid - * unsecured, signed or encrypted JWT. - */ - public static JWT parse(final String s) - throws ParseException { - - final int firstDotPos = s.indexOf("."); - - if (firstDotPos == -1) - throw new ParseException("Invalid JWT serialization: Missing dot delimiter(s)", 0); - - Base64URL header = new Base64URL(s.substring(0, firstDotPos)); - - JSONObject jsonObject; - - try { - jsonObject = JSONObjectUtils.parse(header.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 PlainJWT.parse(s); - } else if (alg instanceof JWSAlgorithm) { - return SignedJWT.parse(s); - } else if (alg instanceof JWEAlgorithm) { - return EncryptedJWT.parse(s); - } else { - throw new AssertionError("Unexpected algorithm type: " + alg); - } - } - - - /** - * Prevents instantiation. - */ - private JWTParser() { - - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/PlainJWT.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/PlainJWT.java deleted file mode 100644 index 9eb4a7213..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/PlainJWT.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * 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.jwt; - - -import java.text.ParseException; - -import net.jcip.annotations.ThreadSafe; - -import net.minidev.json.JSONObject; - -import com.nimbusds.jose.JOSEObject; -import com.nimbusds.jose.Payload; -import com.nimbusds.jose.PlainHeader; -import com.nimbusds.jose.PlainObject; -import com.nimbusds.jose.util.Base64URL; - - -/** - * Unsecured (plain) JSON Web Token (JWT). - * - * @author Vladimir Dzhuvinov - * @version 2015-08-19 - */ -@ThreadSafe -public class PlainJWT extends PlainObject implements JWT { - - - private static final long serialVersionUID = 1L; - - - /** - * Creates a new unsecured (plain) JSON Web Token (JWT) with a default - * {@link com.nimbusds.jose.PlainHeader} and the specified claims - * set. - * - * @param claimsSet The JWT claims set. Must not be {@code null}. - */ - public PlainJWT(final JWTClaimsSet claimsSet) { - - super(new Payload(claimsSet.toJSONObject())); - } - - - /** - * Creates a new unsecured (plain) JSON Web Token (JWT) with the - * specified header and claims set. - * - * @param header The unsecured header. Must not be {@code null}. - * @param claimsSet The JWT claims set. Must not be {@code null}. - */ - public PlainJWT(final PlainHeader header, final JWTClaimsSet claimsSet) { - - super(header, new Payload(claimsSet.toJSONObject())); - } - - - /** - * Creates a new unsecured (plain) JSON Web Token (JWT) with the - * specified Base64URL-encoded parts. - * - * @param firstPart The first part, corresponding to the unsecured - * header. Must not be {@code null}. - * @param secondPart The second part, corresponding to the claims set - * (payload). Must not be {@code null}. - * - * @throws ParseException If parsing of the serialised parts failed. - */ - public PlainJWT(final Base64URL firstPart, final Base64URL secondPart) - throws ParseException { - - super(firstPart, secondPart); - } - - - @Override - public JWTClaimsSet getJWTClaimsSet() - throws ParseException { - - JSONObject json = getPayload().toJSONObject(); - - if (json == null) { - - throw new ParseException("Payload of unsecured JOSE object is not a valid JSON object", 0); - } - - return JWTClaimsSet.parse(json); - } - - - /** - * Parses an unsecured (plain) JSON Web Token (JWT) from the specified - * string in compact format. - * - * @param s The string to parse. Must not be {@code null}. - * - * @return The unsecured JWT. - * - * @throws ParseException If the string couldn't be parsed to a valid - * unsecured JWT. - */ - public static PlainJWT parse(final String s) - throws ParseException { - - Base64URL[] parts = JOSEObject.split(s); - - if (! parts[2].toString().isEmpty()) { - - throw new ParseException("Unexpected third Base64URL part in the unsecured JWT object", 0); - } - - return new PlainJWT(parts[0], parts[1]); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/SignedJWT.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/SignedJWT.java deleted file mode 100644 index 9fbd1b09c..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/SignedJWT.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * 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.jwt; - - -import java.text.ParseException; - -import net.jcip.annotations.ThreadSafe; - -import net.minidev.json.JSONObject; - -import com.nimbusds.jose.JOSEObject; -import com.nimbusds.jose.JWSHeader; -import com.nimbusds.jose.JWSObject; -import com.nimbusds.jose.Payload; -import com.nimbusds.jose.util.Base64URL; - - -/** - * Signed JSON Web Token (JWT). - * - * @author Vladimir Dzhuvinov - * @version 2015-08-19 - */ -@ThreadSafe -public class SignedJWT extends JWSObject implements JWT { - - - private static final long serialVersionUID = 1L; - - - /** - * Creates a new to-be-signed JSON Web Token (JWT) with the specified - * header and claims set. The initial state will be - * {@link com.nimbusds.jose.JWSObject.State#UNSIGNED unsigned}. - * - * @param header The JWS header. Must not be {@code null}. - * @param claimsSet The JWT claims set. Must not be {@code null}. - */ - public SignedJWT(final JWSHeader header, final JWTClaimsSet claimsSet) { - - super(header, new Payload(claimsSet.toJSONObject())); - } - - - /** - * Creates a new signed JSON Web Token (JWT) with the specified - * serialised parts. The state will be - * {@link com.nimbusds.jose.JWSObject.State#SIGNED signed}. - * - * @param firstPart The first part, corresponding to the JWS header. - * Must not be {@code null}. - * @param secondPart The second part, corresponding to the claims set - * (payload). Must not be {@code null}. - * @param thirdPart The third part, corresponding to the signature. - * Must not be {@code null}. - * - * @throws ParseException If parsing of the serialised parts failed. - */ - public SignedJWT(final Base64URL firstPart, final Base64URL secondPart, final Base64URL thirdPart) - throws ParseException { - - super(firstPart, secondPart, thirdPart); - } - - - @Override - public JWTClaimsSet getJWTClaimsSet() - throws ParseException { - - JSONObject json = getPayload().toJSONObject(); - - if (json == null) { - throw new ParseException("Payload of JWS object is not a valid JSON object", 0); - } - - return JWTClaimsSet.parse(json); - } - - - /** - * Parses a signed JSON Web Token (JWT) from the specified string in - * compact format. - * - * @param s The string to parse. Must not be {@code null}. - * - * @return The signed JWT. - * - * @throws ParseException If the string couldn't be parsed to a valid - * signed JWT. - */ - public static SignedJWT parse(final String s) - throws ParseException { - - Base64URL[] parts = JOSEObject.split(s); - - if (parts.length != 3) { - throw new ParseException("Unexpected number of Base64URL parts, must be three", 0); - } - - return new SignedJWT(parts[0], parts[1], parts[2]); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/package-info.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/package-info.java deleted file mode 100644 index 553891d19..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/package-info.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * 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. - */ - -/** - * JSON Web Token (JWT) classes. - * - *

This package provides representation, compact serialisation and parsing - * for the following JWT objects: - * - *

    - *
  • {@link com.nimbusds.jwt.PlainJWT Unsecured (plain) JWTs}. - *
  • {@link com.nimbusds.jwt.SignedJWT Signed JWTs}. - *
  • {@link com.nimbusds.jwt.EncryptedJWT Encrypted JWTs}. - *
- * - *

References: - * - *

    - *
  • RFC 7519 (JWT) - *
- */ -package com.nimbusds.jwt; diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/proc/BadJWTException.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/proc/BadJWTException.java deleted file mode 100644 index 34c3916f5..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/proc/BadJWTException.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * 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.jwt.proc; - - -import com.nimbusds.jose.proc.BadJOSEException; - - -/** - * Bad JSON Web Token (JWT) exception. - * - * @author Vladimir Dzhuvinov - * @version 2015-06-29 - */ -public class BadJWTException extends BadJOSEException { - - - /** - * Creates a new bad JWT exception. - * - * @param message The exception message. - */ - public BadJWTException(final String message) { - - super(message); - } - - - /** - * Creates a new bad JWT exception. - * - * @param message The exception message. - * @param cause The exception cause. - */ - public BadJWTException(final String message, final Throwable cause) { - - super(message, cause); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/proc/ClockSkewAware.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/proc/ClockSkewAware.java deleted file mode 100644 index 3891561f6..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/proc/ClockSkewAware.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * 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.jwt.proc; - - -import com.nimbusds.jose.util.DateUtils; - - -/** - * Clock skew aware interface. - * - * @see DateUtils - */ -public interface ClockSkewAware { - - - /** - * Gets the maximum acceptable clock skew. - * - * @return The maximum acceptable clock skew, in seconds. Zero if none. - */ - int getMaxClockSkew(); - - - /** - * Sets the maximum acceptable clock skew. - * - * @param maxClockSkewSeconds The maximum acceptable clock skew, in - * seconds. Zero if none. - */ - void setMaxClockSkew(final int maxClockSkewSeconds); -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/proc/ConfigurableJWTProcessor.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/proc/ConfigurableJWTProcessor.java deleted file mode 100644 index edc868757..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/proc/ConfigurableJWTProcessor.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * 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.jwt.proc; - - -import com.nimbusds.jose.proc.SecurityContext; - - -/** - * Configurable processor of {@link com.nimbusds.jwt.PlainJWT - * unsecured} (plain), {@link com.nimbusds.jwt.SignedJWT signed} and - * {@link com.nimbusds.jwt.EncryptedJWT encrypted} JSON Web Tokens (JWT). - * - * @author Vladimir Dzhuvinov - * @version 2015-08-22 - */ -public interface ConfigurableJWTProcessor - extends JWTProcessor, JWTProcessorConfiguration { - -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/proc/DefaultJWTClaimsVerifier.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/proc/DefaultJWTClaimsVerifier.java deleted file mode 100644 index 2ec25013e..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/proc/DefaultJWTClaimsVerifier.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * 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.jwt.proc; - - -import java.util.Date; - -import com.nimbusds.jose.proc.SecurityContext; -import com.nimbusds.jwt.JWTClaimsSet; -import com.nimbusds.jwt.util.DateUtils; -import net.jcip.annotations.ThreadSafe; - - -/** - * Default JWT claims verifier. This class is thread-safe. - * - *

Performs the following checks: - * - *

    - *
  1. If an expiration time (exp) claim is present, makes sure it is - * ahead of the current time, else the JWT claims set is rejected. - *
  2. If a not-before-time (nbf) claim is present, makes sure it is - * before the current time, else the JWT claims set is rejected. - *
- * - *

This class may be extended to perform additional checks. - * - * @author Vladimir Dzhuvinov - * @version 2016-07-25 - */ -@ThreadSafe -public class DefaultJWTClaimsVerifier implements JWTClaimsSetVerifier, JWTClaimsVerifier, ClockSkewAware { - - - /** - * The default maximum acceptable clock skew, in seconds (60). - */ - public static final int DEFAULT_MAX_CLOCK_SKEW_SECONDS = 60; - - - // Cache exceptions - - - /** - * Expired JWT. - */ - private static final BadJWTException EXPIRED_JWT_EXCEPTION = new BadJWTException("Expired JWT"); - - - /** - * JWT before use time. - */ - private static final BadJWTException JWT_BEFORE_USE_EXCEPTION = new BadJWTException("JWT before use time"); - - - /** - * The maximum acceptable clock skew, in seconds. - */ - private int maxClockSkew = DEFAULT_MAX_CLOCK_SKEW_SECONDS; - - - @Override - public int getMaxClockSkew() { - return maxClockSkew; - } - - - @Override - public void setMaxClockSkew(int maxClockSkewSeconds) { - maxClockSkew = maxClockSkewSeconds; - } - - - @Override - public void verify(final JWTClaimsSet claimsSet) - throws BadJWTException { - - verify(claimsSet, null); - } - - - @Override - public void verify(final JWTClaimsSet claimsSet, final C context) - throws BadJWTException { - - final Date now = new Date(); - - final Date exp = claimsSet.getExpirationTime(); - - if (exp != null) { - - if (! DateUtils.isAfter(exp, now, maxClockSkew)) { - throw EXPIRED_JWT_EXCEPTION; - } - } - - final Date nbf = claimsSet.getNotBeforeTime(); - - if (nbf != null) { - - if (! DateUtils.isBefore(nbf, now, maxClockSkew)) { - throw JWT_BEFORE_USE_EXCEPTION; - } - } - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/proc/DefaultJWTProcessor.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/proc/DefaultJWTProcessor.java deleted file mode 100644 index df081ec50..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/proc/DefaultJWTProcessor.java +++ /dev/null @@ -1,416 +0,0 @@ -/* - * 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.jwt.proc; - - -import java.security.Key; -import java.text.ParseException; -import java.util.List; -import java.util.ListIterator; - -import com.nimbusds.jose.JOSEException; -import com.nimbusds.jose.JWEDecrypter; -import com.nimbusds.jose.JWSVerifier; -import com.nimbusds.jose.crypto.factories.DefaultJWEDecrypterFactory; -import com.nimbusds.jose.crypto.factories.DefaultJWSVerifierFactory; -import com.nimbusds.jose.proc.*; -import com.nimbusds.jwt.*; - - -/** - * Default processor of {@link com.nimbusds.jwt.PlainJWT unsecured} (plain), - * {@link com.nimbusds.jwt.SignedJWT signed} and - * {@link com.nimbusds.jwt.EncryptedJWT encrypted} JSON Web Tokens (JWTs). - * - *

Must be configured with the following: - * - *

    - *
  1. To process signed JWTs: A {@link JWSKeySelector JWS key selector} - * to determine the key candidate(s) for the signature verification. The - * key selection procedure is application-specific and may involve key ID - * lookup, a certificate check and / or other information supplied in the - * message {@link SecurityContext context}.
  2. - * - *
  3. To process encrypted JWTs: A {@link JWEKeySelector JWE key selector} - * to determine the key candidate(s) for decryption. The key selection - * procedure is application-specific and may involve key ID lookup, a - * certificate check and / or other information supplied in the message - * {@link SecurityContext context}.
  4. - *
- * - *

An optional context parameter is available to facilitate passing of - * additional data between the caller and the underlying selector of key - * candidates (in both directions). - * - *

See sections 6 of RFC 7515 (JWS) and RFC 7516 (JWE) for guidelines on key - * selection. - * - *

This processor comes with the default {@link DefaultJWSVerifierFactory - * JWS verifier factory} and the default {@link DefaultJWEDecrypterFactory - * JWE decrypter factory}; they can construct verifiers / decrypters for all - * standard JOSE algorithms implemented by the library. - * - *

Note that for security reasons this processor is hardwired to reject - * unsecured (plain) JWTs. Override the {@link #process(PlainJWT, SecurityContext)} - * if you need to handle plain JWTs as well. - * - *

A {@link DefaultJWTClaimsVerifier default JWT claims verifier} is - * provided, to perform a minimal check of the claims after a successful JWS - * verification / JWE decryption. It checks the token expiration (exp) and - * not-before (nbf) timestamps if these are present. The default JWT claims - * verifier may be extended to perform additional checks, such as issuer and - * subject acceptance. - * - *

To process generic JOSE objects (with arbitrary payloads) use the - * {@link com.nimbusds.jose.proc.DefaultJOSEProcessor} class. - * - * @author Vladimir Dzhuvinov - * @version 2017-05-05 - */ -public class DefaultJWTProcessor - implements ConfigurableJWTProcessor { - - // Cache exceptions - private static final BadJOSEException PLAIN_JWT_REJECTED_EXCEPTION = - new BadJOSEException("Unsecured (plain) JWTs are rejected, extend class to handle"); - private static final BadJOSEException NO_JWS_KEY_SELECTOR_EXCEPTION = - new BadJOSEException("Signed JWT rejected: No JWS key selector is configured"); - private static final BadJOSEException NO_JWE_KEY_SELECTOR_EXCEPTION = - new BadJOSEException("Encrypted JWT rejected: No JWE key selector is configured"); - private static final JOSEException NO_JWS_VERIFIER_FACTORY_EXCEPTION = - new JOSEException("No JWS verifier is configured"); - private static final JOSEException NO_JWE_DECRYPTER_FACTORY_EXCEPTION = - new JOSEException("No JWE decrypter is configured"); - private static final BadJOSEException NO_JWS_KEY_CANDIDATES_EXCEPTION = - new BadJOSEException("Signed JWT rejected: Another algorithm expected, or no matching key(s) found"); - private static final BadJOSEException NO_JWE_KEY_CANDIDATES_EXCEPTION = - new BadJOSEException("Encrypted JWT rejected: Another algorithm expected, or no matching key(s) found"); - private static final BadJOSEException INVALID_SIGNATURE = - new BadJWSException("Signed JWT rejected: Invalid signature"); - private static final BadJWTException INVALID_NESTED_JWT_EXCEPTION = - new BadJWTException("The payload is not a nested signed JWT"); - private static final BadJOSEException NO_MATCHING_VERIFIERS_EXCEPTION = - new BadJOSEException("JWS object rejected: No matching verifier(s) found"); - private static final BadJOSEException NO_MATCHING_DECRYPTERS_EXCEPTION = - new BadJOSEException("Encrypted JWT rejected: No matching decrypter(s) found"); - - /** - * The JWS key selector. - */ - private JWSKeySelector jwsKeySelector; - - - /** - * The JWE key selector. - */ - private JWEKeySelector jweKeySelector; - - - /** - * The JWS verifier factory. - */ - private JWSVerifierFactory jwsVerifierFactory = new DefaultJWSVerifierFactory(); - - - /** - * The JWE decrypter factory. - */ - private JWEDecrypterFactory jweDecrypterFactory = new DefaultJWEDecrypterFactory(); - - - /** - * The claims verifier. - */ - private JWTClaimsSetVerifier claimsVerifier = new DefaultJWTClaimsVerifier<>(); - - - /** - * The deprecated claims verifier. - */ - private JWTClaimsVerifier deprecatedClaimsVerifier = null; - - - @Override - public JWSKeySelector getJWSKeySelector() { - - return jwsKeySelector; - } - - - @Override - public void setJWSKeySelector(final JWSKeySelector jwsKeySelector) { - - this.jwsKeySelector = jwsKeySelector; - } - - - @Override - public JWEKeySelector getJWEKeySelector() { - - return jweKeySelector; - } - - - @Override - public void setJWEKeySelector(final JWEKeySelector jweKeySelector) { - - this.jweKeySelector = jweKeySelector; - } - - - @Override - public JWSVerifierFactory getJWSVerifierFactory() { - - return jwsVerifierFactory; - } - - - @Override - public void setJWSVerifierFactory(final JWSVerifierFactory factory) { - - jwsVerifierFactory = factory; - } - - - @Override - public JWEDecrypterFactory getJWEDecrypterFactory() { - - return jweDecrypterFactory; - } - - - @Override - public void setJWEDecrypterFactory(final JWEDecrypterFactory factory) { - - jweDecrypterFactory = factory; - } - - - @Override - public JWTClaimsSetVerifier getJWTClaimsSetVerifier() { - - return claimsVerifier; - } - - - @Override - public void setJWTClaimsSetVerifier(final JWTClaimsSetVerifier claimsVerifier) { - - this.claimsVerifier = claimsVerifier; - this.deprecatedClaimsVerifier = null; // clear other verifier - } - - - @Override - @Deprecated - public JWTClaimsVerifier getJWTClaimsVerifier() { - - return deprecatedClaimsVerifier; - } - - - @Override - @Deprecated - public void setJWTClaimsVerifier(final JWTClaimsVerifier claimsVerifier) { - - this.claimsVerifier = null; // clear official verifier - this.deprecatedClaimsVerifier = claimsVerifier; - } - - - /** - * Verifies the claims of the specified JWT. - * - * @param jwt The JWT. Must be in a state which allows the claims - * to be extracted. - * @param context Optional context, {@code null} if not required. - * - * @return The JWT claims set. - * - * @throws BadJWTException If the JWT claims are invalid or rejected. - */ - private JWTClaimsSet verifyAndReturnClaims(final JWT jwt, final C context) - throws BadJWTException { - - JWTClaimsSet claimsSet; - - try { - claimsSet = jwt.getJWTClaimsSet(); - - } catch (ParseException e) { - // Payload not a JSON object - throw new BadJWTException(e.getMessage(), e); - } - - if (getJWTClaimsSetVerifier() != null) { - getJWTClaimsSetVerifier().verify(claimsSet, context); - } else if (getJWTClaimsVerifier() != null) { - // Fall back to deprecated claims verifier - getJWTClaimsVerifier().verify(claimsSet); - } - - return claimsSet; - } - - - @Override - public JWTClaimsSet process(final String jwtString, final C context) - throws ParseException, BadJOSEException, JOSEException { - - return process(JWTParser.parse(jwtString), context); - } - - - @Override - public JWTClaimsSet process(final JWT jwt, final C context) - throws BadJOSEException, JOSEException { - - if (jwt instanceof SignedJWT) { - return process((SignedJWT)jwt, context); - } - - if (jwt instanceof EncryptedJWT) { - return process((EncryptedJWT)jwt, context); - } - - if (jwt instanceof PlainJWT) { - return process((PlainJWT)jwt, context); - } - - // Should never happen - throw new JOSEException("Unexpected JWT object type: " + jwt.getClass()); - } - - - @Override - public JWTClaimsSet process(final PlainJWT plainJWT, final C context) - throws BadJOSEException, JOSEException { - - verifyAndReturnClaims(plainJWT, context); // just check claims, no return - - throw PLAIN_JWT_REJECTED_EXCEPTION; - } - - - @Override - public JWTClaimsSet process(final SignedJWT signedJWT, final C context) - throws BadJOSEException, JOSEException { - - if (getJWSKeySelector() == null) { - // JWS key selector may have been deliberately omitted - throw NO_JWS_KEY_SELECTOR_EXCEPTION; - } - - if (getJWSVerifierFactory() == null) { - throw NO_JWS_VERIFIER_FACTORY_EXCEPTION; - } - - List keyCandidates = getJWSKeySelector().selectJWSKeys(signedJWT.getHeader(), context); - - if (keyCandidates == null || keyCandidates.isEmpty()) { - throw NO_JWS_KEY_CANDIDATES_EXCEPTION; - } - - ListIterator it = keyCandidates.listIterator(); - - while (it.hasNext()) { - - JWSVerifier verifier = getJWSVerifierFactory().createJWSVerifier(signedJWT.getHeader(), it.next()); - - if (verifier == null) { - continue; - } - - final boolean validSignature = signedJWT.verify(verifier); - - if (validSignature) { - return verifyAndReturnClaims(signedJWT, context); - } - - if (! it.hasNext()) { - // No more keys to try out - throw INVALID_SIGNATURE; - } - } - - throw NO_MATCHING_VERIFIERS_EXCEPTION; - } - - - @Override - public JWTClaimsSet process(final EncryptedJWT encryptedJWT, final C context) - throws BadJOSEException, JOSEException { - - if (getJWEKeySelector() == null) { - // JWE key selector may have been deliberately omitted - throw NO_JWE_KEY_SELECTOR_EXCEPTION; - } - - if (getJWEDecrypterFactory() == null) { - throw NO_JWE_DECRYPTER_FACTORY_EXCEPTION; - } - - List keyCandidates = getJWEKeySelector().selectJWEKeys(encryptedJWT.getHeader(), context); - - if (keyCandidates == null || keyCandidates.isEmpty()) { - throw NO_JWE_KEY_CANDIDATES_EXCEPTION; - } - - ListIterator it = keyCandidates.listIterator(); - - while (it.hasNext()) { - - JWEDecrypter decrypter = getJWEDecrypterFactory().createJWEDecrypter(encryptedJWT.getHeader(), it.next()); - - if (decrypter == null) { - continue; - } - - try { - encryptedJWT.decrypt(decrypter); - - } catch (JOSEException e) { - - if (it.hasNext()) { - // Try next key - continue; - } - - // No more keys to try - throw new BadJWEException("Encrypted JWT rejected: " + e.getMessage(), e); - } - - if ("JWT".equalsIgnoreCase(encryptedJWT.getHeader().getContentType())) { - - // Handle nested signed JWT, see http://tools.ietf.org/html/rfc7519#section-5.2 - SignedJWT signedJWTPayload = encryptedJWT.getPayload().toSignedJWT(); - - if (signedJWTPayload == null) { - // Cannot parse payload to signed JWT - throw INVALID_NESTED_JWT_EXCEPTION; - } - - return process(signedJWTPayload, context); - } - - return verifyAndReturnClaims(encryptedJWT, context); - } - - throw NO_MATCHING_DECRYPTERS_EXCEPTION; - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/proc/JWTClaimsSetVerifier.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/proc/JWTClaimsSetVerifier.java deleted file mode 100644 index f460e816d..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/proc/JWTClaimsSetVerifier.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * 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.jwt.proc; - - -import com.nimbusds.jose.proc.SecurityContext; -import com.nimbusds.jwt.JWTClaimsSet; - - -/** - * JWT claims set verifier. Ensures the claims set of a JWT that is being - * {@link JWTProcessor processed} complies with an application's requirements. - * - *

An application may implement JWT claims checks such as: - * - *

    - *
  • The JWT is within the required validity time window; - *
  • has a specific issuer; - *
  • has a specific audience; - *
  • has a specific subject; - *
  • etc. - *
- * - * @author Vladimir Dzhuvinov - * @version 2016-07-25 - * @since 4.23 - */ -public interface JWTClaimsSetVerifier { - - - /** - * Verifies selected or all claims from the specified JWT claims set. - * - * @param claimsSet The JWT claims set. Not {@code null}. - * @param context Optional context, {@code null} if not required. - * - * @throws BadJWTException If the JWT claims set is rejected. - */ - void verify(final JWTClaimsSet claimsSet, final C context) - throws BadJWTException; -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/proc/JWTClaimsVerifier.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/proc/JWTClaimsVerifier.java deleted file mode 100644 index 531537951..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/proc/JWTClaimsVerifier.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * 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.jwt.proc; - - -import com.nimbusds.jwt.JWTClaimsSet; - - -/** - * @see JWTClaimsSetVerifier - */ -@Deprecated -public interface JWTClaimsVerifier { - - - /** - * Performs verification of selected or all claims in the specified JWT - * claims set. - * - * @param claimsSet The JWT claims set. Not {@code null}. - * - * @throws BadJWTException If the JWT claims set is rejected. - */ - @Deprecated - void verify(final JWTClaimsSet claimsSet) - throws BadJWTException; -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/proc/JWTProcessor.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/proc/JWTProcessor.java deleted file mode 100644 index cdf651186..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/proc/JWTProcessor.java +++ /dev/null @@ -1,136 +0,0 @@ -/* - * 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.jwt.proc; - - -import java.text.ParseException; - -import com.nimbusds.jose.JOSEException; -import com.nimbusds.jose.proc.BadJOSEException; -import com.nimbusds.jose.proc.SecurityContext; -import com.nimbusds.jwt.*; - - -/** - * Interface for parsing and processing {@link com.nimbusds.jwt.PlainJWT - * unsecured} (plain), {@link com.nimbusds.jwt.SignedJWT signed} and - * {@link com.nimbusds.jwt.EncryptedJWT encrypted} JSON Web Tokens (JWTs). - * An optional context parameter is available to facilitate passing of - * additional data between the caller and the underlying JOSE processor (in - * both directions). - * - * @author Vladimir Dzhuvinov - * @version 2015-08-20 - */ -public interface JWTProcessor { - - - /** - * Parses and processes the specified JWT (unsecured, signed or - * encrypted). - * - * @param jwtString The JWT, compact-encoded to a URL-safe string. Must - * not be {@code null}. - * @param context Optional context, {@code null} if not required. - * - * @return The JWT claims set on success. - * - * @throws ParseException If the string couldn't be parsed to a valid - * JWT. - * @throws BadJOSEException If the JWT is rejected. - * @throws JOSEException If an internal processing exception is - * encountered. - */ - JWTClaimsSet process(final String jwtString, final C context) - throws ParseException, BadJOSEException, JOSEException; - - - /** - * Processes the specified JWT (unsecured, signed or encrypted). - * - * @param jwt The JWT. Must not be {@code null}. - * @param context Optional context, {@code null} if not required. - * - * @return The JWT claims set on success. - * - * @throws BadJOSEException If the JWT is rejected. - * @throws JOSEException If an internal processing exception is - * encountered. - */ - JWTClaimsSet process(final JWT jwt, final C context) - throws BadJOSEException, JOSEException; - - - /** - * Processes the specified unsecured (plain) JWT, typically by checking - * its context. - * - * @param plainJWT The unsecured (plain) JWT. Not {@code null}. - * @param context Optional context, {@code null} if not required. - * - * @return The JWT claims set on success. - * - * @throws BadJOSEException If the unsecured (plain) JWT is rejected, - * after examining the context or due to the - * payload not being a JSON object. - * @throws JOSEException If an internal processing exception is - * encountered. - */ - JWTClaimsSet process(final PlainJWT plainJWT, final C context) - throws BadJOSEException, JOSEException; - - - /** - * Processes the specified signed JWT by verifying its signature. The - * key candidate(s) are selected by examining the JWS header and / or - * the message context. - * - * @param signedJWT The signed JWT. Not {@code null}. - * @param context Optional context, {@code null} if not required. - * - * @return The JWT claims set on success. - * - * @throws BadJOSEException If the signed JWT is rejected, typically - * due to a bad signature or the payload not - * being a JSON object. - * @throws JOSEException If an internal processing exception is - * encountered. - */ - JWTClaimsSet process(final SignedJWT signedJWT, final C context) - throws BadJOSEException, JOSEException; - - - /** - * Processes the specified encrypted JWT by decrypting it. The key - * candidate(s) are selected by examining the JWS header and / or the - * message context. - * - * @param encryptedJWT The encrypted JWT. Not {@code null}. - * @param context Optional context, {@code null} if not required. - * - * @return The JWT claims set on success. - * - * @throws BadJOSEException If the encrypted JWT is rejected, typically - * due to failed decryption or the payload not - * being a JSON object. - * @throws JOSEException If an internal processing exception is - * encountered. - */ - JWTClaimsSet process(final EncryptedJWT encryptedJWT, final C context) - throws BadJOSEException, JOSEException; -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/proc/JWTProcessorConfiguration.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/proc/JWTProcessorConfiguration.java deleted file mode 100644 index ff0a7c2b5..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/proc/JWTProcessorConfiguration.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * 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.jwt.proc; - - -import com.nimbusds.jose.crypto.factories.DefaultJWEDecrypterFactory; -import com.nimbusds.jose.crypto.factories.DefaultJWSVerifierFactory; -import com.nimbusds.jose.proc.JOSEProcessorConfiguration; -import com.nimbusds.jose.proc.SecurityContext; - - -/** - * JWT processor configuration. - * - *

Specifies the required components to process JWTs: - * - *

    - *
  • To verify signed JWTs: - *
      - *
    • Key selector to determine key candidate(s) for JWS - * verification based on the JWS header and application- - * specific context information. - *
    • Factory to construct a JWS verifier for a given key - * candidate and JWS header information. A - * {@link DefaultJWSVerifierFactory default factory} - * implementation is provided. - *
    - *
  • To decrypt encrypted JWTs: - *
      - *
    • Key selector to determine key candidate(s) for JWE - * decryption based on the JWS header and application-specific - * context information. - *
    • Factory to construct a JWE decrypter for a given key - * candidate and JWE header information. A - * {@link DefaultJWEDecrypterFactory default factory} - * implementation is provided. - *
    - *
  • Optional JWT claims set verifier. Ensures that the claims set of a - * JWT complies with an application's requirements. - *
- * - * @author Vladimir Dzhuvinov - * @version 2016-07-25 - */ -public interface JWTProcessorConfiguration extends JOSEProcessorConfiguration { - - - /** - * Gets the optional JWT claims set verifier. Ensures that the claims - * set of a JWT complies with an application's requirements. - * - * @return The JWT claims set verifier, {@code null} if not specified. - */ - JWTClaimsSetVerifier getJWTClaimsSetVerifier(); - - - /** - * Sets the optional JWT claims set verifier. Ensures that the claims - * set of a JWT complies with an application's requirements. - * - * @param claimsVerifier The JWT claims set verifier, {@code null} if - * not specified. - */ - void setJWTClaimsSetVerifier(final JWTClaimsSetVerifier claimsVerifier); - - - /** - * Use {@link #getJWTClaimsVerifier()} instead. - * - * @return The JWT claims set verifier, {@code null} if not specified. - */ - @Deprecated - JWTClaimsVerifier getJWTClaimsVerifier(); - - - /** - * Use {@link #setJWTClaimsSetVerifier} instead. - * - * @param claimsVerifier The JWT claims set verifier, {@code null} if - * not specified. - */ - @Deprecated - void setJWTClaimsVerifier(final JWTClaimsVerifier claimsVerifier); -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/proc/package-info.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/proc/package-info.java deleted file mode 100644 index 7eb41937d..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/proc/package-info.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * 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. - */ - -/** - * Secure framework for application-specific verification and decryption of - * JSON Web Tokens (JWTs). Provides a core - * {@link com.nimbusds.jwt.proc.JWTProcessor interface} for processing signed, - * encrypted and unsecured (plain) JWTs, with a - * {@link com.nimbusds.jwt.proc.DefaultJWTProcessor default implementation} - * which can be configured and extended as required. - * - *

To process generic JOSE objects refer to the - * {@link com.nimbusds.jose.proc} package. - * - *

References: - * - *

- */ -package com.nimbusds.jwt.proc; \ No newline at end of file diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/util/DateUtils.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/util/DateUtils.java deleted file mode 100644 index 59e160d58..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/util/DateUtils.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * 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.jwt.util; - - -import java.util.Date; - - -/** - * Date utilities. - */ -public class DateUtils { - - - /** - * Converts the specified date object to a Unix epoch time in seconds. - * - * @param date The date. Must not be {@code null}. - * - * @return The Unix epoch time, in seconds. - */ - public static long toSecondsSinceEpoch(final Date date) { - - return date.getTime() / 1000L; - } - - - /** - * Converts the specified Unix epoch time in seconds to a date object. - * - * @param time The Unix epoch time, in seconds. Must not be negative. - * - * @return The date. - */ - public static Date fromSecondsSinceEpoch(final long time) { - - return new Date(time * 1000L); - } - - - /** - * Check if the specified date is after the specified reference, given - * the maximum accepted negative clock skew. - * - *

Formula: - * - *

-	 * return date + clock_skew > reference
-	 * 
- * - * Example: Ensure a JWT expiration (exp) timestamp is after the - * current time, with a minute of acceptable clock skew. - * - *
-	 * boolean valid = DateUtils.isAfter(exp, new Date(), 60);
-	 * 
- * - * @param date The date to check. Must not be - * {@code null}. - * @param reference The reference date (e.g. the current - * time). Must not be {@code null}. - * @param maxClockSkewSeconds The maximum acceptable negative clock - * skew of the date value to check, in - * seconds. - * - * @return {@code true} if the date is before the reference, plus the - * maximum accepted clock skew, else {@code false}. - */ - public static boolean isAfter(final Date date, - final Date reference, - final long maxClockSkewSeconds) { - - return new Date(date.getTime() + maxClockSkewSeconds*1000L).after(reference); - } - - - /** - * Checks if the specified date is before the specified reference, - * given the maximum accepted positive clock skew. - * - *

Formula: - * - *

-	 * return date - clock_skew < reference
-	 * 
- * - * Example: Ensure a JWT issued-at (iat) timestamp is before the - * current time, with a minute of acceptable clock skew. - * - *
-	 * boolean valid = DateUtils.isBefore(iat, new Date(), 60);
-	 * 
- * - * @param date The date to check. Must not be - * {@code null}. - * @param reference The reference date (e.g. the current - * time). Must not be {@code null}. - * @param maxClockSkewSeconds The maximum acceptable clock skew of the - * date value to check, in seconds. - * - * @return {@code true} if the date is before the reference, minus the - * maximum accepted clock skew, else {@code false}. - */ - public static boolean isBefore(final Date date, - final Date reference, - final long maxClockSkewSeconds) { - - return new Date(date.getTime() - maxClockSkewSeconds*1000L).before(reference); - } - - - /** - * Prevents instantiation. - */ - private DateUtils() { } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/util/package-info.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/util/package-info.java deleted file mode 100644 index 79a0455d3..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/jwt/util/package-info.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * 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. - */ - -/** - * Utility interfaces and classes. - */ -package com.nimbusds.jwt.util; \ No newline at end of file diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/langtag/LangTag.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/langtag/LangTag.java deleted file mode 100644 index 17bc886dc..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/langtag/LangTag.java +++ /dev/null @@ -1,715 +0,0 @@ -/* - * lang-tag - * - * 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.langtag; - - -import java.util.LinkedList; -import java.util.List; - - -/** - * Language tag according to RFC 5646. - * - *

Supports normal language tags. Special private language tags beginning - * with "x" and grandfathered tags beginning with "i" are not supported. - * - *

To construct a new language tag from scratch: - * - *

- * // English as used in the United States
- * LangTag tag = new LangTag("en");
- * tag.setRegion("US");
- *
- * // Returns "en-US"
- * tag.toString();
- * 
- * - *

To parse a language tag: - * - *

- * // Chinese, Mandarin, Simplified script, as used in China
- * LangTag tag = LangTag.parse("zh-cmn-Hans-CN");
- *
- * // Returns "zh"
- * tag.getPrimaryLanguage();
- *
- * // Returns "cmn"
- * tag.getExtendedLanguageSubtags()[0];
- *
- * // Returns "zh-cmn"
- * tag.getLanguage();
- *
- * // Returns "Hans"
- * tag.getScript();
- *
- * // Returns "CN"
- * tag.getRegion();
- * 
- * - *

See RFC 5646. - */ -public class LangTag implements ReadOnlyLangTag { - - - /** - * The primary language, as the shortest ISO 639 code (2*3ALPHA). Must - * always be defined, unless sufficient language subtags exist. - */ - private String primaryLanguage; - - - /** - * Optional extended language subtags, as three-letter ISO-639-3 codes. - */ - private String[] languageSubtags; - - - /** - * Optional script, (4ALPHA) ISO 15924 code. - */ - private String script = null; - - - /** - * Optional region, (2ALPHA) ISO 3166-1 code or (3DIGIT) UN M.49 code. - */ - private String region = null; - - - /** - * Optional variants, (5*8alphanum) or (DIGIT 3alphanum). - */ - private String[] variants = null; - - - /** - * Optional extensions. - */ - private String[] extensions = null; - - - /** - * Optional private use subtag. - */ - private String privateUse = null; - - - /** - * Ensures the specified subtag has a valid maximum length of eight - * characters. - * - * @param subtag The sub tag to check. Must not be {@code null}. - * - * @throws LangTagException If the subtag has length greater than eight - * characters. - */ - private static void ensureMaxLength(final String subtag) - throws LangTagException { - - if (subtag.length() > 8) - - // extension or private use subtag? - if (subtag.charAt(1) != '-' && subtag.length() > 10) - - throw new LangTagException("Invalid subtag syntax: Max character length exceeded"); - } - - - /** - * Creates a new simple language tag. - * - *

Use for simple language tags such as "en" (English), "fr" - * (French) or "pt" (Portuguese). - * - * @param primaryLanguage The primary language, as the shortest two or - * three-letter ISO 639 code. Must not be - * {@code null}. - * - * @throws LangTagException If the primary language syntax is invalid. - */ - public LangTag(final String primaryLanguage) - throws LangTagException { - - this(primaryLanguage, new String[]{}); - } - - - /** - * Creates a new extended language tag. - * - *

Use for extended language tags such as "zh-cmn" (Mandarin - * Chinese) or "zh-yue" (Cantonese Chinese). - * - * @param primaryLanguage The primary language, as the shortest two or - * three-letter ISO 639 code. May be {@code null} - * if the subtags are sufficient to identify the - * language. - * @param languageSubtags One or more extended language subtags, as - * three-letter ISO 639-3 codes. {@code null} if - * none. - * - * @throws LangTagException If the primary or extended language syntax - * is invalid. - */ - public LangTag(final String primaryLanguage, final String... languageSubtags) - throws LangTagException { - - if (primaryLanguage == null && - (languageSubtags == null || languageSubtags.length == 0)) - throw new LangTagException("Either the primary language or the extended language subtags, or both must be defined"); - - setPrimaryLanguage(primaryLanguage); - setExtendedLanguageSubtags(languageSubtags); - } - - - @Override - public String getLanguage() { - - StringBuilder sb = new StringBuilder(); - - if (primaryLanguage != null) - sb.append(primaryLanguage); - - if (languageSubtags != null && languageSubtags.length > 0) { - - for (String tag: languageSubtags) { - - if (sb.length() > 0) - sb.append('-'); - - sb.append(tag); - } - } - - return sb.toString(); - } - - - @Override - public String getPrimaryLanguage() { - - return primaryLanguage; - } - - - /** - * Checks if the specified string has a valid primary language subtag - * syntax. - * - * @param s The string to check. Must not be {@code null}. - * - * @return {@code true} if the syntax is correct, else {@code false}. - */ - private static boolean isPrimaryLanguage(final String s) { - - return s.matches("[a-zA-Z]{2,3}"); - } - - - /** - * Sets the primary language subtag. - * - *

See RFC 5646 section 2.2.1. - * - * @param primaryLanguage The primary language, as the shortest two or - * three-letter ISO 639 code. May be - * {@code null}. - * - * @throws LangTagException If the primary language syntax is invalid. - */ - private void setPrimaryLanguage(final String primaryLanguage) - throws LangTagException { - - if (primaryLanguage == null) { - this.primaryLanguage = null; - return; - } - - ensureMaxLength(primaryLanguage); - - if (! isPrimaryLanguage(primaryLanguage)) - throw new LangTagException("Invalid primary language subtag: Must be a two or three-letter ISO 639 code"); - - this.primaryLanguage = primaryLanguage.toLowerCase(); - } - - - @Override - public String[] getExtendedLanguageSubtags() { - - return languageSubtags; - } - - - /** - * Checks if the specified string has a valid extended language subtag - * syntax. - * - * @param s The string to check. Must not be {@code null}. - * - * @return {@code true} if the syntax is correct, else {@code false}. - */ - private static boolean isExtendedLanguageSubtag(final String s) { - - return s.matches("[a-zA-Z]{3}"); - } - - - /** - * Sets the extended language subtags. - * - *

See RFC 5646 section 2.2.2. - * - * @param languageSubtags The extended language subtags, as three-letter - * ISO 639-3 codes. {@code null} if none. - */ - private void setExtendedLanguageSubtags(final String... languageSubtags) - throws LangTagException { - - if (languageSubtags == null || languageSubtags.length == 0) { - this.languageSubtags = null; - return; - } - - this.languageSubtags = new String[languageSubtags.length]; - - for (int i=0; i < languageSubtags.length; i++) { - - ensureMaxLength(languageSubtags[i]); - - if (! isExtendedLanguageSubtag(languageSubtags[i])) - throw new LangTagException("Invalid extended language subtag: Must be a three-letter ISO 639-3 code"); - - this.languageSubtags[i] = languageSubtags[i].toLowerCase(); - } - } - - - @Override - public String getScript() { - - return script; - } - - - /** - * Checks if the specified string has a valid script subtag syntax. - * - * @param s The string to check. Must not be {@code null}. - * - * @return {@code true} if the syntax is correct, else {@code false}. - */ - private static boolean isScript(final String s) { - - return s.matches("[a-zA-Z]{4}"); - } - - - /** - * Sets the script. - * - *

See RFC 5646 section 2.2.3. - * - * @param script The script, as a four-letter ISO 15924 code. - * {@code null} if not defined. - * - * @throws LangTagException If the script syntax is invalid. - */ - public void setScript(final String script) - throws LangTagException { - - if (script == null) { - this.script = null; - return; - } - - ensureMaxLength(script); - - if (! isScript(script)) - throw new LangTagException("Invalid script subtag: Must be a four-letter ISO 15924 code"); - - this.script = script.substring(0, 1).toUpperCase() + - script.substring(1).toLowerCase(); - } - - - @Override - public String getRegion() { - - return region; - } - - - /** - * Checks if the specified string has a valid region subtag syntax. - * - * @param s The string to check. Must not be {@code null}. - * - * @return {@code true} if the syntax is correct, else {@code false}. - */ - private static boolean isRegion(final String s) { - - return s.matches("[a-zA-Z]{2}|\\d{3}"); - } - - - /** - * Sets the region. - * - *

See RFC 5646 section 2.2.4. - * - * @param region The region, as a two-letter ISO 3166-1 code or a three- - * digit UN M.49 code. {@code null} if not defined. - * - * @throws LangTagException If the region syntax is invalid. - */ - public void setRegion(final String region) - throws LangTagException { - - if (region == null) { - this.region = null; - return; - } - - ensureMaxLength(region); - - if (! isRegion(region)) - throw new LangTagException("Invalid region subtag: Must be a two-letter ISO 3166-1 code or a three-digit UN M.49 code"); - - this.region = region.toUpperCase(); - } - - - @Override - public String[] getVariants() { - - return variants; - } - - - /** - * Checks if the specified string has a valid variant subtag syntax. - * - * @param s The string to check. Must not be {@code null}. - * - * @return {@code true} if the syntax is correct, else {@code false}. - */ - private static boolean isVariant(final String s) { - - return s.matches("[a-zA-Z][a-zA-Z0-9]{4,}|[0-9][a-zA-Z0-9]{3,}"); - } - - - /** - * Sets the variants. - * - *

See RFC 5646 section 2.2.5. - * - * @param variants The variants. {@code null} if not defined. - * - * @throws LangTagException If the variant syntax is invalid. - */ - public void setVariants(final String... variants) - throws LangTagException { - - if (variants == null || variants.length == 0) { - this.variants = null; - return; - } - - this.variants = new String[variants.length]; - - for (int i=0; i < variants.length; i++) { - - ensureMaxLength(variants[i]); - - if (! isVariant(variants[i])) - throw new LangTagException("Invalid variant subtag"); - - this.variants[i] = variants[i].toLowerCase(); - } - } - - - @Override - public String[] getExtensions() { - - return extensions; - } - - - /** - * Checks if the specified string has a valid extension singleton - * syntax. - * - * @param s The string to check. Must not be {@code null}. - * - * @return {@code true} if the syntax is correct, else {@code false}. - */ - private static boolean isExtensionSingleton(final String s) { - - return s.matches("[0-9a-wA-Wy-zY-Z]"); - } - - - /** - * Checks if the specified string has a valid extension subtag syntax. - * - * @param s The string to check. Must not be {@code null}. - * - * @return {@code true} if the syntax is correct, else {@code false}. - */ - private static boolean isExtension(final String s) { - - return s.matches("[0-9a-wA-Wy-zY-Z]-[0-9a-zA-Z]+"); - } - - - /** - * Sets the extensions. - * - *

See RFC 5646 section 2.2.6. - * - * @param extensions The extensions. {@code null} if not defined. - * - * @throws LangTagException If the extension syntax is invalid. - */ - public void setExtensions(final String... extensions) - throws LangTagException { - - if (extensions == null || extensions.length == 0) { - this.extensions = null; - return; - } - - this.extensions = new String[extensions.length]; - - for (int i=0; i < extensions.length; i++) { - - ensureMaxLength(extensions[i]); - - if (! isExtension(extensions[i])) - throw new LangTagException("Invalid extension subtag"); - - this.extensions[i] = extensions[i].toLowerCase(); - } - } - - - @Override - public String getPrivateUse() { - - return privateUse; - } - - - /** - * Checks if the specified string has a valid private use subtag syntax. - * - * @param s The string to check. Must not be {@code null}. - * - * @return {@code true} if the syntax is correct, else {@code false}. - */ - private static boolean isPrivateUse(final String s) { - - return s.matches("x-[0-9a-zA-Z]+"); - } - - - /** - * Sets the private use. - * - *

See RFC 5646 section 2.2.7. - * - * @param privateUse The private use. {@code null} if not defined. - * - * @throws LangTagException If the extension syntax is invalid. - */ - public void setPrivateUse(final String privateUse) - throws LangTagException { - - if (privateUse == null) { - this.privateUse = null; - return; - } - - ensureMaxLength(privateUse); - - if (! isPrivateUse(privateUse)) - throw new LangTagException("Invalid private use subtag"); - - this.privateUse = privateUse.toLowerCase(); - } - - - @Override - public String toString() { - - StringBuilder sb = new StringBuilder(getLanguage()); - - if (script != null) { - sb.append('-'); - sb.append(script); - } - - if (region != null) { - sb.append('-'); - sb.append(region); - } - - if (variants != null) { - - for (String v: variants) { - sb.append('-'); - sb.append(v); - } - } - - if (extensions != null) { - - for (String e: extensions) { - sb.append('-'); - sb.append(e); - } - } - - if (privateUse != null) { - - sb.append('-'); - sb.append(privateUse); - } - - return sb.toString(); - } - - - /** - * Overrides {@code Object.hashCode()}. - * - * @return The object hash code. - */ - @Override - public int hashCode() { - - return toString().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(Object object) { - - return object != null && - object instanceof LangTag && - this.toString().equals(object.toString()); - } - - - /** - * Parses the specified string representation of a language tag. - * - * @param s The string to parse. May be {@code null}. - * - * @return The language tag. {@code null} if the string was empty or - * {@code null}. - * - * @throws LangTagException If the string has invalid language tag - * syntax. - */ - public static LangTag parse(final String s) - throws LangTagException { - - if (s == null || s.trim().isEmpty()) - return null; - - final String[] subtags = s.split("-"); - - int pos = 0; - - // Parse primary lang + ext lang subtags - String primaryLang = null; - List extLangSubtags = new LinkedList(); - - if (isPrimaryLanguage(subtags[0])) - primaryLang = subtags[pos++]; - - // Multiple ext lang subtags possible - while (pos < subtags.length && isExtendedLanguageSubtag(subtags[pos])) - extLangSubtags.add(subtags[pos++]); - - LangTag langTag = new LangTag(primaryLang, extLangSubtags.toArray(new String[]{})); - - - // Parse script - if (pos < subtags.length && isScript(subtags[pos])) - langTag.setScript(subtags[pos++]); - - // Parse region - if (pos < subtags.length && isRegion(subtags[pos])) - langTag.setRegion(subtags[pos++]); - - // Parse variants - List variantSubtags = new LinkedList(); - - while (pos < subtags.length && isVariant(subtags[pos])) - variantSubtags.add(subtags[pos++]); - - if (! variantSubtags.isEmpty()) - langTag.setVariants(variantSubtags.toArray(new String[]{})); - - // Parse extensions, e.g. u-usercal - List extSubtags = new LinkedList(); - - while (pos < subtags.length && isExtensionSingleton(subtags[pos])) { - - String singleton = subtags[pos++]; - - if (pos == subtags.length) - throw new LangTagException("Invalid extension subtag"); - - extSubtags.add(singleton + "-" + subtags[pos++]); - } - - if (! extSubtags.isEmpty()) - langTag.setExtensions(extSubtags.toArray(new String[]{})); - - - // Parse private use, e.g. x-abc - if (pos < subtags.length && subtags[pos].equals("x")) { - - if (++pos == subtags.length) - throw new LangTagException("Invalid private use subtag"); - - langTag.setPrivateUse("x-" + subtags[pos++]); - } - - // End of tag? - if (pos < subtags.length) - throw new LangTagException("Invalid language tag: Unexpected subtag"); - - return langTag; - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/langtag/LangTagException.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/langtag/LangTagException.java deleted file mode 100644 index 5fd30669b..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/langtag/LangTagException.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * lang-tag - * - * 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.langtag; - - -/** - * Language tag exception. - */ -public class LangTagException extends Exception { - - - /** - * Creates a new language tag exception with the specified message. - * - * @param message The exception message. - */ - public LangTagException(final String message) { - - super(message); - } -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/langtag/LangTagUtils.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/langtag/LangTagUtils.java deleted file mode 100644 index 7b463b81a..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/langtag/LangTagUtils.java +++ /dev/null @@ -1,367 +0,0 @@ -/* - * lang-tag - * - * 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.langtag; - - -import java.util.*; - - -/** - * Language tag utilities. - */ -public final class LangTagUtils { - - - /** - * Strips the language tag, if any is found, from the specified string. - * This method is {@code null} safe. - * - *

Example: - * - *

-	 * "name#bg-BG" => "name"
-	 * "name"       => "name"
-	 * 
- * - * @param s The string. May contain a language tag. May be - * {@code null}. - * - * @return The string with no language tag. - */ - public static String strip(final String s) { - - if (s == null) - return null; - - final int pos = s.indexOf('#'); - - if (pos < 0) - return s; - - return s.substring(0, pos); - } - - - /** - * Strips the language tags, if any are found, from the specified - * string set. This method is {@code null} safe. - * - *

Example: - * - *

-	 * "name#bg-BG" => "name"
-	 * "name"       => "name"
-	 * 
- * - * @param set The string set. May contain strings with language tags. - * May be {@code null}. - * - * @return The string set with no language tags. - */ - public static Set strip(final Set set) { - - if (set == null) - return null; - - Set out = new HashSet(); - - for (String s: set) - out.add(strip(s)); - - return out; - } - - - /** - * Strips the language tags, if any are found, from the specified - * string list. This method is {@code null} safe. - * - *

Example: - * - *

-	 * "name#bg-BG" => "name"
-	 * "name"       => "name"
-	 * 
- * - * @param list The string list. May contain strings with language tags. - * May be {@code null}. - * - * @return The string list with no language tags. - */ - public static List strip(final List list) { - - if (list == null) - return null; - - List out = new ArrayList(list.size()); - - for (String s: list) - out.add(strip(s)); - - return out; - } - - - /** - * Extracts the language tag, if any is found, from the specified - * string. - * - *

Example: - * - *

-	 * "name#bg-BG" => "bg-BG"
-	 * "name#"      => null
-	 * "name"       => null
-	 * 
- * - * @param s The string. May contain a language tag. May be - * {@code null}. - * - * @return The extracted language tag, {@code null} if not found. - * - * @throws LangTagException If the language tag is invalid. - */ - public static LangTag extract(final String s) - throws LangTagException { - - if (s == null) - return null; - - final int pos = s.indexOf('#'); - - if (pos < 0 || s.length() < pos + 1) - return null; - - return LangTag.parse(s.substring(pos + 1)); - } - - - /** - * Finds all language-tagged entries with the specified base name. - * Entries with invalid language tags will be skipped. - * - *

Example: - * - *

Map to search for base name "month": - * - *

-	 * "month"    => "January"
-	 * "month#de" => "Januar"
-	 * "month#fr" => "janvier"
-	 * "month#pt" => "janeiro"
-	 * 
- * - *

Result: - * - *

-	 * null => "January"
-	 * "de" => "Januar"
-	 * "fr" => "janvier"
-	 * "pt" => "janeiro"
-	 * 
- * - * @param baseName The base name to look for (without a language tag) - * in the map keys. Must not be {@code null}. - * @param map The map to search. Must not be {@code null}. - * - * @return A map of all language-tagged entries with the specified - * base name. A {@code null} keyed entry will indicate no - * language tag (base name only). - */ - public static Map find(final String baseName, final Map map) { - - Map result = new HashMap(); - - // Walk through each map entry, checking for entry keys that - // start with "baseName" - for (Map.Entry entry: map.entrySet()) { - - T value; - - try { - value = entry.getValue(); - - } catch (ClassCastException e) { - - continue; // skip - } - - if (entry.getKey().equals(baseName)) { - - // Claim name matches, no tag - result.put(null, value); - } - else if (entry.getKey().startsWith(baseName + '#')) { - - // Claim name matches, has tag - String[] parts = entry.getKey().split("#", 2); - - LangTag langTag = null; - - if (parts.length == 2) { - - try { - langTag = LangTag.parse(parts[1]); - - } catch (LangTagException e) { - - // ignore - } - } - - result.put(langTag, value); - } - } - - return result; - } - - - /** - * Returns a string list representation of the specified language tags - * collection. - * - * @param langTags The language tags list. May be {@code null}. - * - * @return The string list, or {@code null} if the original list is - * {@code null}. - */ - public static List toStringList(final Collection langTags) { - - if (langTags == null) - return null; - - List out = new ArrayList(langTags.size()); - - for (LangTag lt: langTags) { - out.add(lt.toString()); - } - - return out; - } - - - /** - * Returns a string array representation of the specified language tags - * collection. - * - * @param langTags The language tags list. May be {@code null}. - * - * @return The string list, or {@code null} if the original list is - * {@code null}. - */ - public static String[] toStringArray(final Collection langTags) { - - if (langTags == null) - return null; - - String[] out = new String[langTags.size()]; - - int i=0; - - for (LangTag lt: langTags) { - out[i++] = lt.toString(); - } - - return out; - } - - - /** - * Parses a language tag list from the specified string collection. - * - * @param collection The string collection. May be {@code null}. - * - * @return The language tag list, or {@code null} if the parsed string - * collection is null. - * - * @throws LangTagException If parsing failed. - */ - public static List parseLangTagList(final Collection collection) - throws LangTagException { - - if (collection == null) - return null; - - List out = new ArrayList(collection.size()); - - for (String s: collection) { - out.add(LangTag.parse(s)); - } - - return out; - } - - - /** - * Parses a language tag list from the specified string values. - * - * @param values The string values. May be {@code null}. - * - * @return The language tag list, or {@code null} if the parsed string - * array is null. - * - * @throws LangTagException If parsing failed. - */ - public static List parseLangTagList(final String ... values) - throws LangTagException { - - if (values == null) - return null; - - List out = new ArrayList(values.length); - - for (String s: values) { - out.add(LangTag.parse(s)); - } - - return out; - } - - - /** - * Parses a language tag array from the specified string values. - * - * @param values The string values. May be {@code null}. - * - * @return The language tag array, or {@code null} if the parsed string - * array is null. - * - * @throws LangTagException If parsing failed. - */ - public static LangTag[] parseLangTagArray(final String ... values) - throws LangTagException { - - if (values == null) - return null; - - LangTag[] out = new LangTag[values.length]; - - for (int i=0; i < values.length; i++) { - out[i] = LangTag.parse(values[i]); - } - - return out; - } - - - /** - * Prevents public instantiation. - */ - private LangTagUtils() { } -} \ No newline at end of file diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/langtag/ReadOnlyLangTag.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/langtag/ReadOnlyLangTag.java deleted file mode 100644 index 3cba7c4b6..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/langtag/ReadOnlyLangTag.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * lang-tag - * - * 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.langtag; - - -/** - * Read-only view of a {@link LangTag Language tag}. - */ -public interface ReadOnlyLangTag { - - - /** - * Gets the language (primary language plus extended language subtags). - * - *

See RFC 5646 section 2.2.1. - * - *

Examples: - * - *

-	 * en
-	 * de
-	 * zh-cmn
-	 * cmn
-	 * 
- * - * @return The language, consisting of the primary and/or extended - * language subtags. - */ - public String getLanguage(); - - - /** - * Gets the primary language. - * - *

See RFC 5646 section 2.2.1. - * - * @return The primary language, as a two or three-letter ISO 639 code, - * in canonical lower case format. - */ - public String getPrimaryLanguage(); - - - /** - * Gets the extended language subtags. - * - *

See RFC 5646 section 2.2.2. - * - * @return The extended language subtags, as three-letter ISO 639-3 - * codes. {@code null} if none. - */ - public String[] getExtendedLanguageSubtags(); - - - /** - * Gets the script. - * - *

See RFC 5646 section 2.2.3. - * - * @return The script, as an ISO 15924 code, in canonical title case - * format. {@code null} if not defined. - */ - public String getScript(); - - - /** - * Gets the region. - * - *

See RFC 5646 section 2.2.4. - * - * @return The region, as a two-letter ISO 3166-1 code or a three-digit - * UN M.49 code. {@code null} if not defined. - */ - public String getRegion(); - - - /** - * Gets the variants. - * - *

See RFC 5646 section 2.2.5. - * - * @return The variants. {@code null} if not defined. - */ - public String[] getVariants(); - - - /** - * Gets the extensions. - * - *

See RFC 5646 section 2.2.6. - * - * @return The extensions. {@code null} if not defined. - */ - public String[] getExtensions(); - - - /** - * Gets the private use. - * - *

See RFC 5646 section 2.2.7. - * - * @return The private use. {@code null} if not defined. - */ - public String getPrivateUse(); - - - /** - * Returns the canonical string representation of this language tag. - * - * @return The canonical string representation. - */ - public String toString(); -} diff --git a/maxkey-jose-jwt/src/main/java/com/nimbusds/langtag/package-info.java b/maxkey-jose-jwt/src/main/java/com/nimbusds/langtag/package-info.java deleted file mode 100644 index 5ae935a5e..000000000 --- a/maxkey-jose-jwt/src/main/java/com/nimbusds/langtag/package-info.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * lang-tag - * - * 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. - */ - -/** - * Language tags (RFC-5646) for Java. - * - *

Implementation of "Tags for Identifying Languages", - * RFC-5646. - * - *

Supports normal language tags. Special private language tags beginning - * with "x" and grandfathered tags beginning with "i" are not supported. - * - *

See {@link com.nimbusds.langtag.LangTag} for details. - * - *

This package has no dependencies. - */ -package com.nimbusds.langtag; diff --git a/maxkey-jose-jwt/src/main/java/net/jcip/annotations/GuardedBy.java b/maxkey-jose-jwt/src/main/java/net/jcip/annotations/GuardedBy.java deleted file mode 100644 index 7a9739556..000000000 --- a/maxkey-jose-jwt/src/main/java/net/jcip/annotations/GuardedBy.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright 2013 Stephen Connolly. - * - * 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 net.jcip.annotations; - -import java.lang.annotation.Documented; -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import static java.lang.annotation.ElementType.FIELD; -import static java.lang.annotation.ElementType.METHOD; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -/** - * The presence of this annotation indicates that the field or method must only be accessed when holding the specified - * lock. - */ -@Documented -@Target(value = {FIELD, METHOD}) -@Retention(RUNTIME) -public @interface GuardedBy { - /** - * The specified lock that guards the annotated field or method. Valid values are: - *

    - *
  • {@code this} indicates the intrinsic lock of the instance containing the field or method.
  • - *
  • class-name.this which allows for disambiguation of which {@code this} when dealing - * with inner classes
  • - *
  • {@code itself} which is valid for reference fields only, and indicates that the referenced instance's - * own intrinsic lock should be used as the guard
  • - *
  • field-name indicates the named instance or static field is to be used as the guard. If - * the field type is not a sub-type of {@link java.util.concurrent.locks.Lock} then the intrinsic lock of - * the referenced instance is to be used
  • - *
  • class-name.field-name indicates the named static field is to be used as the - * guard. If the field type is not a sub-type of {@link java.util.concurrent.locks.Lock} then the intrinsic lock of - * the referenced instance is to be used
  • - *
  • method-name() indicates that the zero-argument method should be called to obtain the - * lock object. If the return type is not a sub-type of {@link java.util.concurrent.locks.Lock} then the intrinsic - * lock of the returned instance is to be used
  • - *
  • class-name.class indicates that the intrinsic lock of the specified class should be used - * as the guard
  • - *
- * - * @return The specified lock that guards the annotated field or method - */ - String value(); -} diff --git a/maxkey-jose-jwt/src/main/java/net/jcip/annotations/Immutable.java b/maxkey-jose-jwt/src/main/java/net/jcip/annotations/Immutable.java deleted file mode 100644 index 4862b4d9a..000000000 --- a/maxkey-jose-jwt/src/main/java/net/jcip/annotations/Immutable.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 2013 Stephen Connolly. - * - * 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 net.jcip.annotations; - -import java.lang.annotation.Documented; -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import static java.lang.annotation.ElementType.TYPE; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -/** - * The presence of this annotation indicates that the author believes the class to be immutable and hence inherently - * thread-safe. An immutable class is one where the state of an instance cannot be seen to change. As a result - *
    - *
  • All public fields must be {@code final}
  • - *
  • All public final reference fields are either {@code null} or refer to other immutable objects
  • - *
  • Constructors and methods do not publish references to any potentially mutable internal state.
  • - *
- * Performance optimization may mean that instances of an immutable class may have mutable internal state. The - * critical point is that callers cannot tell the difference. For example {@link String} is an immutable class, despite - * having an internal int that is non-final but used as a cache for {@link String#hashCode()}. - *

- * Immutable objects are inherently thread-safe; they may be passed between threads or published without - * synchronization. - */ -@Documented -@Target(TYPE) -@Retention(RUNTIME) -public @interface Immutable { -} diff --git a/maxkey-jose-jwt/src/main/java/net/jcip/annotations/NotThreadSafe.java b/maxkey-jose-jwt/src/main/java/net/jcip/annotations/NotThreadSafe.java deleted file mode 100644 index df50194dd..000000000 --- a/maxkey-jose-jwt/src/main/java/net/jcip/annotations/NotThreadSafe.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2013 Stephen Connolly. - * - * 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 net.jcip.annotations; - -import java.lang.annotation.Documented; -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import static java.lang.annotation.ElementType.TYPE; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -/** - * The presence of this annotation indicates that the author believes the class is not thread-safe. - * The absence of this annotation does not indicate that the class is thread-safe, instead this annotation is for - * cases where a naïve assumption could be easily made that the class is thread-safe. In general, it is a bad plan - * to assume a class is thread safe without good reason. - */ -@Documented -@Target(TYPE) -@Retention(RUNTIME) -public @interface NotThreadSafe { -} diff --git a/maxkey-jose-jwt/src/main/java/net/jcip/annotations/ThreadSafe.java b/maxkey-jose-jwt/src/main/java/net/jcip/annotations/ThreadSafe.java deleted file mode 100644 index 63503450d..000000000 --- a/maxkey-jose-jwt/src/main/java/net/jcip/annotations/ThreadSafe.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2013 Stephen Connolly. - * - * 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 net.jcip.annotations; - -import java.lang.annotation.Documented; -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import static java.lang.annotation.ElementType.TYPE; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -/** - * The presence of this annotation indicates that the author believes the class to be thread-safe. As such, there should - * be no sequence of accessing the public methods or fields that could put an instance of this class into an invalid - * state, irrespective of any rearrangement of those operations by the Java Runtime and without introducing any - * requirements for synchronization or coordination by the caller/accessor. - */ -@Documented -@Target(TYPE) -@Retention(RUNTIME) -public @interface ThreadSafe { -} diff --git a/maxkey-jose-jwt/src/main/java/net/minidev/asm/ASMUtil.java b/maxkey-jose-jwt/src/main/java/net/minidev/asm/ASMUtil.java deleted file mode 100644 index 6cf07d890..000000000 --- a/maxkey-jose-jwt/src/main/java/net/minidev/asm/ASMUtil.java +++ /dev/null @@ -1,253 +0,0 @@ -package net.minidev.asm; - -/* - * Copyright 2011 JSON-SMART authors - * - * 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. - */ -import static org.objectweb.asm.Opcodes.CHECKCAST; -import static org.objectweb.asm.Opcodes.INVOKESTATIC; -import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL; - -import java.lang.reflect.Field; -import java.util.HashMap; - -import org.objectweb.asm.Label; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Type; - -/** - * ASM Utils used to simplify class generation - * - * @author uriel Chemouni - */ -public class ASMUtil { - /** - * Append the call of proper autoboxing method for the given primitif type. - */ - public static void autoBoxing(MethodVisitor mv, Class clz) { - autoBoxing(mv, Type.getType(clz)); - } - - /** - * Extract all Accessor for the field of the given class. - * - * @param type - * @return all Accessor available - */ - static public Accessor[] getAccessors(Class type, FieldFilter filter) { - Class nextClass = type; - HashMap map = new HashMap(); - if (filter == null) - filter = BasicFiledFilter.SINGLETON; - while (nextClass != Object.class) { - Field[] declaredFields = nextClass.getDeclaredFields(); - - for (Field field : declaredFields) { - String fn = field.getName(); - if (map.containsKey(fn)) - continue; - Accessor acc = new Accessor(nextClass, field, filter); - if (!acc.isUsable()) - continue; - map.put(fn, acc); - } - nextClass = nextClass.getSuperclass(); - } - return map.values().toArray(new Accessor[map.size()]); - } - - /** - * Append the call of proper autoboxing method for the given primitif type. - */ - protected static void autoBoxing(MethodVisitor mv, Type fieldType) { - switch (fieldType.getSort()) { - case Type.BOOLEAN: - mv.visitMethodInsn(INVOKESTATIC, "java/lang/Boolean", "valueOf", "(Z)Ljava/lang/Boolean;"); - break; - case Type.BYTE: - mv.visitMethodInsn(INVOKESTATIC, "java/lang/Byte", "valueOf", "(B)Ljava/lang/Byte;"); - break; - case Type.CHAR: - mv.visitMethodInsn(INVOKESTATIC, "java/lang/Character", "valueOf", "(C)Ljava/lang/Character;"); - break; - case Type.SHORT: - mv.visitMethodInsn(INVOKESTATIC, "java/lang/Short", "valueOf", "(S)Ljava/lang/Short;"); - break; - case Type.INT: - mv.visitMethodInsn(INVOKESTATIC, "java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;"); - break; - case Type.FLOAT: - mv.visitMethodInsn(INVOKESTATIC, "java/lang/Float", "valueOf", "(F)Ljava/lang/Float;"); - break; - case Type.LONG: - mv.visitMethodInsn(INVOKESTATIC, "java/lang/Long", "valueOf", "(J)Ljava/lang/Long;"); - break; - case Type.DOUBLE: - mv.visitMethodInsn(INVOKESTATIC, "java/lang/Double", "valueOf", "(D)Ljava/lang/Double;"); - break; - } - } - - /** - * Append the call of proper extract primitive type of an boxed object. - */ - protected static void autoUnBoxing1(MethodVisitor mv, Type fieldType) { - switch (fieldType.getSort()) { - case Type.BOOLEAN: - mv.visitTypeInsn(CHECKCAST, "java/lang/Boolean"); - mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Boolean", "booleanValue", "()Z"); - break; - case Type.BYTE: - mv.visitTypeInsn(CHECKCAST, "java/lang/Byte"); - mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Byte", "byteValue", "()B"); - break; - case Type.CHAR: - mv.visitTypeInsn(CHECKCAST, "java/lang/Character"); - mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Character", "charValue", "()C"); - break; - case Type.SHORT: - mv.visitTypeInsn(CHECKCAST, "java/lang/Short"); - mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Short", "shortValue", "()S"); - break; - case Type.INT: - mv.visitTypeInsn(CHECKCAST, "java/lang/Integer"); - mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Integer", "intValue", "()I"); - break; - case Type.FLOAT: - mv.visitTypeInsn(CHECKCAST, "java/lang/Float"); - mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Float", "floatValue", "()F"); - break; - case Type.LONG: - mv.visitTypeInsn(CHECKCAST, "java/lang/Long"); - mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Long", "longValue", "()J"); - break; - case Type.DOUBLE: - mv.visitTypeInsn(CHECKCAST, "java/lang/Double"); - mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Double", "doubleValue", "()D"); - break; - case Type.ARRAY: - mv.visitTypeInsn(CHECKCAST, fieldType.getInternalName()); - break; - default: - mv.visitTypeInsn(CHECKCAST, fieldType.getInternalName()); - } - } - - /** - * Append the call of proper extract primitive type of an boxed object. this - * methode use Number interface to unbox object - */ - protected static void autoUnBoxing2(MethodVisitor mv, Type fieldType) { - switch (fieldType.getSort()) { - case Type.BOOLEAN: - mv.visitTypeInsn(CHECKCAST, "java/lang/Boolean"); - mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Boolean", "booleanValue", "()Z"); - break; - case Type.BYTE: - mv.visitTypeInsn(CHECKCAST, "java/lang/Number"); - mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Number", "byteValue", "()B"); - break; - case Type.CHAR: - mv.visitTypeInsn(CHECKCAST, "java/lang/Character"); - mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Character", "charValue", "()C"); - break; - case Type.SHORT: - mv.visitTypeInsn(CHECKCAST, "java/lang/Number"); - mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Number", "shortValue", "()S"); - break; - case Type.INT: - mv.visitTypeInsn(CHECKCAST, "java/lang/Number"); - mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Number", "intValue", "()I"); - break; - case Type.FLOAT: - mv.visitTypeInsn(CHECKCAST, "java/lang/Number"); - mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Number", "floatValue", "()F"); - break; - case Type.LONG: - mv.visitTypeInsn(CHECKCAST, "java/lang/Number"); - mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Number", "longValue", "()J"); - break; - case Type.DOUBLE: - mv.visitTypeInsn(CHECKCAST, "java/lang/Number"); - mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Number", "doubleValue", "()D"); - break; - case Type.ARRAY: - mv.visitTypeInsn(CHECKCAST, fieldType.getInternalName()); - break; - default: - mv.visitTypeInsn(CHECKCAST, fieldType.getInternalName()); - } - } - - /** - * return a array of new Label (used for switch/case generation) - * - * @param cnt - * number of label to return - */ - public static Label[] newLabels(int cnt) { - Label[] r = new Label[cnt]; - for (int i = 0; i < cnt; i++) - r[i] = new Label(); - return r; - } - - public static String getSetterName(String key) { - int len = key.length(); - char[] b = new char[len + 3]; - b[0] = 's'; - b[1] = 'e'; - b[2] = 't'; - char c = key.charAt(0); - if (c >= 'a' && c <= 'z') - c += 'A' - 'a'; - b[3] = c; - for (int i = 1; i < len; i++) { - b[i + 3] = key.charAt(i); - } - return new String(b); - } - - public static String getGetterName(String key) { - int len = key.length(); - char[] b = new char[len + 3]; - b[0] = 'g'; - b[1] = 'e'; - b[2] = 't'; - char c = key.charAt(0); - if (c >= 'a' && c <= 'z') - c += 'A' - 'a'; - b[3] = c; - for (int i = 1; i < len; i++) { - b[i + 3] = key.charAt(i); - } - return new String(b); - } - - public static String getIsName(String key) { - int len = key.length(); - char[] b = new char[len + 2]; - b[0] = 'i'; - b[1] = 's'; - char c = key.charAt(0); - if (c >= 'a' && c <= 'z') - c += 'A' - 'a'; - b[2] = c; - for (int i = 1; i < len; i++) { - b[i + 2] = key.charAt(i); - } - return new String(b); - } - -} diff --git a/maxkey-jose-jwt/src/main/java/net/minidev/asm/Accessor.java b/maxkey-jose-jwt/src/main/java/net/minidev/asm/Accessor.java deleted file mode 100644 index 0914772c2..000000000 --- a/maxkey-jose-jwt/src/main/java/net/minidev/asm/Accessor.java +++ /dev/null @@ -1,187 +0,0 @@ -package net.minidev.asm; - -/* - * Copyright 2011 JSON-SMART authors - * - * 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. - */ -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.lang.reflect.Type; - -/** - * Contains all information needed to access a java field. - * - * field, getter setter - * - * this object is used internally by BeansAcces - * - * @see BeansAccess - * - * @author Uriel Chemouni - */ -public class Accessor { - /** - * Field to access - */ - protected Field field; - /** - * Setter Methods if available - */ - protected Method setter; - /** - * getter Methods if available - */ - protected Method getter; - /** - * Filed index in object - */ - protected int index; - /** - * Filed Class - */ - protected Class type; - /** - * Filed Type using JDK 5+ generics if available - */ - protected Type genericType; - - protected String fieldName; - - /** - * getter for index - * @return Index - */ - public int getIndex() { - return index; - } - - /** - * is the field access using Field access type - * @return if Accessor is public - */ - public boolean isPublic() { - return setter == null; - } - - /** - * is the field is an enum field - * @return if Accessor return an Enum Class - */ - public boolean isEnum() { - return type.isEnum(); - } - - /** - * return the field name - * @return the field name - */ - public String getName() { - return fieldName; - } - - /** - * return field Class - * @return field Class - */ - public Class getType() { - return type; - } - - /** - * return generics field Type. - * @return generics field Type. - */ - public Type getGenericType() { - return genericType; - } - - /** - * @return true if the field can be read or write - */ - public boolean isUsable() { - return field != null || getter != null || setter != null; - } - - /** - * @return true if the field can be read - */ - public boolean isReadable() { - return field != null || getter != null; - } - - /** - * @return true if the field can be write - */ - public boolean isWritable() { - return field != null || getter != null; - } - - /** - * build accessor for a field - * - * @param c - * the handled class - * @param field - * the field to access - */ - public Accessor(Class c, Field field, FieldFilter filter) { - this.fieldName = field.getName(); - int m = field.getModifiers(); - - if ((m & (Modifier.STATIC | Modifier.TRANSIENT)) > 0) - return; - - if ((m & Modifier.PUBLIC) > 0) - this.field = field; - - String name = ASMUtil.getSetterName(field.getName()); - try { - setter = c.getDeclaredMethod(name, field.getType()); - } catch (Exception e) { - } - boolean isBool = field.getType().equals(Boolean.TYPE); - if (isBool) { - name = ASMUtil.getIsName(field.getName()); - } else { - name = ASMUtil.getGetterName(field.getName()); - } - try { - getter = c.getDeclaredMethod(name); - } catch (Exception e) { - } - if (getter == null && isBool) { - try { - getter = c.getDeclaredMethod(ASMUtil.getGetterName(field.getName())); - } catch (Exception e) { - } - } - - if (this.field == null && getter == null && setter == null) - return; - - if (getter != null && !filter.canUse(field, getter)) - getter = null; - - if (setter != null && !filter.canUse(field, setter)) - setter = null; - - // disable - if (getter == null && setter == null && this.field == null) - return; - - this.type = field.getType(); - this.genericType = field.getGenericType(); - } -} diff --git a/maxkey-jose-jwt/src/main/java/net/minidev/asm/BasicFiledFilter.java b/maxkey-jose-jwt/src/main/java/net/minidev/asm/BasicFiledFilter.java deleted file mode 100644 index f878bd333..000000000 --- a/maxkey-jose-jwt/src/main/java/net/minidev/asm/BasicFiledFilter.java +++ /dev/null @@ -1,29 +0,0 @@ -package net.minidev.asm; - -import java.lang.reflect.Field; -import java.lang.reflect.Method; - -public class BasicFiledFilter implements FieldFilter { - public final static BasicFiledFilter SINGLETON = new BasicFiledFilter(); - - @Override - public boolean canUse(Field field) { - return true; - } - - @Override - public boolean canUse(Field field, Method method) { - return true; - } - - @Override - public boolean canRead(Field field) { - return true; - } - - @Override - public boolean canWrite(Field field) { - return true; - } - -} diff --git a/maxkey-jose-jwt/src/main/java/net/minidev/asm/BeansAccess.java b/maxkey-jose-jwt/src/main/java/net/minidev/asm/BeansAccess.java deleted file mode 100644 index e42ad92b1..000000000 --- a/maxkey-jose-jwt/src/main/java/net/minidev/asm/BeansAccess.java +++ /dev/null @@ -1,197 +0,0 @@ -package net.minidev.asm; - -/* - * Copyright 2011 JSON-SMART authors - * - * 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. - */ -import java.util.HashMap; -import java.util.LinkedList; -import java.util.Map.Entry; -import java.util.concurrent.ConcurrentHashMap; - -/** - * Allow access reflect field using runtime generated accessor. BeansAccessor is - * faster than java.lang.reflect.Method.invoke() - * - * @author uriel Chemouni - */ -public abstract class BeansAccess { - private HashMap map; - private Accessor[] accs; - - protected void setAccessor(Accessor[] accs) { - int i = 0; - this.accs = accs; - map = new HashMap(); - for (Accessor acc : accs) { - acc.index = i++; - map.put(acc.getName(), acc); - } - } - - public HashMap getMap() { - return map; - } - - public Accessor[] getAccessors() { - return accs; - } - - /** - * cache used to store built BeansAccess - */ - private static ConcurrentHashMap, BeansAccess> cache = new ConcurrentHashMap, BeansAccess>(); - - // private final static ConcurrentHashMap> cache; - - /** - * return the BeansAccess corresponding to a type - * - * @param type - * to be access - * @return the BeansAccess - */ - static public

BeansAccess

get(Class

type) { - return get(type, null); - } - - /** - * return the BeansAccess corresponding to a type - * - * @param type - * to be access - * @return the BeansAccess - */ - static public

BeansAccess

get(Class

type, FieldFilter filter) { - { - @SuppressWarnings("unchecked") - BeansAccess

access = (BeansAccess

) cache.get(type); - if (access != null) - return access; - } - // extract all access methodes - Accessor[] accs = ASMUtil.getAccessors(type, filter); - - - // create new class name - String className = type.getName(); - String accessClassName; - if (className.startsWith("java.util.")) - accessClassName = "net.minidev.asm." + className + "AccAccess"; - else - accessClassName = className.concat("AccAccess"); - - // extend class base loader - DynamicClassLoader loader = new DynamicClassLoader(type.getClassLoader()); - // try to load existing class - Class accessClass = null; - try { - accessClass = loader.loadClass(accessClassName); - } catch (ClassNotFoundException ignored) { - } - - LinkedList> parentClasses = getParents(type); - - // if the class do not exists build it - if (accessClass == null) { - BeansAccessBuilder builder = new BeansAccessBuilder(type, accs, loader); - for (Class c : parentClasses) - builder.addConversion(BeansAccessConfig.classMapper.get(c)); - accessClass = builder.bulid(); - } - try { - @SuppressWarnings("unchecked") - BeansAccess

access = (BeansAccess

) accessClass.newInstance(); - access.setAccessor(accs); - cache.putIfAbsent(type, access); - // add fieldname alias - for (Class c : parentClasses) - addAlias(access, BeansAccessConfig.classFiledNameMapper.get(c)); - return access; - } catch (Exception ex) { - throw new RuntimeException("Error constructing accessor class: " + accessClassName, ex); - } - } - - private static LinkedList> getParents(Class type) { - LinkedList> m = new LinkedList>(); - while (type != null && !type.equals(Object.class)) { - m.addLast(type); - for (Class c : type.getInterfaces()) - m.addLast(c); - type = type.getSuperclass(); - } - m.addLast(Object.class); - return m; - } - - /** - * - */ - private static void addAlias(BeansAccess access, HashMap m) { - // HashMap m = - // BeansAccessConfig.classFiledNameMapper.get(type); - if (m == null) - return; - HashMap changes = new HashMap(); - for (Entry e : m.entrySet()) { - Accessor a1 = access.map.get(e.getValue()); - if (a1 != null) - changes.put(e.getValue(), a1); - } - access.map.putAll(changes); - } - - /** - * set field value by field index - */ - abstract public void set(T object, int methodIndex, Object value); - - /** - * get field value by field index - */ - abstract public Object get(T object, int methodIndex); - - /** - * create a new targeted object - */ - abstract public T newInstance(); - - /** - * set field value by fieldname - */ - public void set(T object, String methodName, Object value) { - int i = getIndex(methodName); - if (i == -1) - throw new net.minidev.asm.ex.NoSuchFieldException(methodName + " in " + object.getClass() + " to put value : " + value); - set(object, i, value); - } - - /** - * get field value by fieldname - */ - public Object get(T object, String methodName) { - return get(object, getIndex(methodName)); - } - - /** - * Returns the index of the field accessor. - */ - public int getIndex(String name) { - Accessor ac = map.get(name); - if (ac == null) - return -1; - return ac.index; - } -} diff --git a/maxkey-jose-jwt/src/main/java/net/minidev/asm/BeansAccessBuilder.java b/maxkey-jose-jwt/src/main/java/net/minidev/asm/BeansAccessBuilder.java deleted file mode 100644 index f1a6cd6bb..000000000 --- a/maxkey-jose-jwt/src/main/java/net/minidev/asm/BeansAccessBuilder.java +++ /dev/null @@ -1,463 +0,0 @@ -package net.minidev.asm; - -import static org.objectweb.asm.Opcodes.ACC_PUBLIC; -import static org.objectweb.asm.Opcodes.ACONST_NULL; -import static org.objectweb.asm.Opcodes.ALOAD; -import static org.objectweb.asm.Opcodes.ARETURN; -import static org.objectweb.asm.Opcodes.ASTORE; -import static org.objectweb.asm.Opcodes.ATHROW; -import static org.objectweb.asm.Opcodes.BIPUSH; -import static org.objectweb.asm.Opcodes.CHECKCAST; -import static org.objectweb.asm.Opcodes.DUP; -import static org.objectweb.asm.Opcodes.F_SAME; -import static org.objectweb.asm.Opcodes.GETFIELD; -import static org.objectweb.asm.Opcodes.ICONST_1; -import static org.objectweb.asm.Opcodes.ICONST_2; -import static org.objectweb.asm.Opcodes.ICONST_3; -import static org.objectweb.asm.Opcodes.ICONST_4; -import static org.objectweb.asm.Opcodes.ICONST_5; -import static org.objectweb.asm.Opcodes.IFEQ; -import static org.objectweb.asm.Opcodes.IFNE; -import static org.objectweb.asm.Opcodes.IFNULL; -import static org.objectweb.asm.Opcodes.IF_ICMPNE; -import static org.objectweb.asm.Opcodes.ILOAD; -import static org.objectweb.asm.Opcodes.INVOKESPECIAL; -import static org.objectweb.asm.Opcodes.INVOKESTATIC; -import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL; -import static org.objectweb.asm.Opcodes.NEW; -import static org.objectweb.asm.Opcodes.PUTFIELD; -import static org.objectweb.asm.Opcodes.RETURN; - -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.HashMap; - -import org.objectweb.asm.ClassWriter; -import org.objectweb.asm.Label; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Opcodes; -import org.objectweb.asm.Type; - -public class BeansAccessBuilder { - static private String METHOD_ACCESS_NAME = Type.getInternalName(BeansAccess.class); - - final Class type; - final Accessor[] accs; - final DynamicClassLoader loader; - final String className; - final String accessClassName; - final String accessClassNameInternal; - final String classNameInternal; - final HashMap, Method> convMtds = new HashMap, Method>(); -// Class exeptionClass = net.minidev.asm.ex.NoSuchFieldException.class; - Class exeptionClass = NoSuchFieldException.class; - - /** - * Build reflect bytecode from accessor list. - * - * @param type - * type to be access - * @param accs - * used accessor - * @param loader - * Loader used to store the generated class - */ - public BeansAccessBuilder(Class type, Accessor[] accs, DynamicClassLoader loader) { - this.type = type; - this.accs = accs; - this.loader = loader; - - this.className = type.getName(); - if (className.startsWith("java.")) - this.accessClassName = "net.minidev.asm." + className + "AccAccess"; - else - this.accessClassName = className.concat("AccAccess"); - - this.accessClassNameInternal = accessClassName.replace('.', '/'); - this.classNameInternal = className.replace('.', '/'); - } - - public void addConversion(Iterable> conv) { - if (conv == null) - return; - for (Class c : conv) - addConversion(c); - } - - public void addConversion(Class conv) { - if (conv == null) - return; - for (Method mtd : conv.getMethods()) { - if ((mtd.getModifiers() & Modifier.STATIC) == 0) - continue; - Class[] param = mtd.getParameterTypes(); - if (param.length != 1) - continue; - if (!param[0].equals(Object.class)) - continue; - Class rType = mtd.getReturnType(); - if (rType.equals(Void.TYPE)) - continue; - convMtds.put(rType, mtd); - } - } - - public Class bulid() { - ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); - MethodVisitor mv; - - boolean USE_HASH = accs.length > 10; - int HASH_LIMIT = 14; - - String signature = "Lnet/minidev/asm/BeansAccess;"; - - cw.visit(Opcodes.V1_6, ACC_PUBLIC + Opcodes.ACC_SUPER, accessClassNameInternal, signature, METHOD_ACCESS_NAME, null); - // init - { - mv = cw.visitMethod(ACC_PUBLIC, "", "()V", null, null); - mv.visitCode(); - mv.visitVarInsn(ALOAD, 0); - mv.visitMethodInsn(INVOKESPECIAL, METHOD_ACCESS_NAME, "", "()V"); - mv.visitInsn(RETURN); - mv.visitMaxs(1, 1); - mv.visitEnd(); - } - - // set(Object object, int methodIndex, Object value) - mv = cw.visitMethod(ACC_PUBLIC, "set", "(Ljava/lang/Object;ILjava/lang/Object;)V", null, null); - mv.visitCode(); - // if no Field simply return - if (accs.length == 0) { - // - // mv.visitInsn(RETURN); - } else if (accs.length > HASH_LIMIT) { - // lots of field Use Switch Statement - mv.visitVarInsn(ILOAD, 2); - Label[] labels = ASMUtil.newLabels(accs.length); - Label defaultLabel = new Label(); - - mv.visitTableSwitchInsn(0, labels.length - 1, defaultLabel, labels); - int i = 0; - for (Accessor acc : accs) { - mv.visitLabel(labels[i++]); - if (!acc.isWritable()) { - mv.visitInsn(RETURN); - continue; - } - internalSetFiled(mv, acc); - } - mv.visitLabel(defaultLabel); - } else { - Label[] labels = ASMUtil.newLabels(accs.length); - int i = 0; - for (Accessor acc : accs) { - ifNotEqJmp(mv, 2, i, labels[i]); - internalSetFiled(mv, acc); - mv.visitLabel(labels[i]); - mv.visitFrame(F_SAME, 0, null, 0, null); - i++; - } - } - if (exeptionClass != null) - throwExIntParam(mv, exeptionClass); - else - mv.visitInsn(RETURN); - mv.visitMaxs(0, 0); - mv.visitEnd(); - - // public Object get(Object object, int fieldId) - mv = cw.visitMethod(ACC_PUBLIC, "get", "(Ljava/lang/Object;I)Ljava/lang/Object;", null, null); - mv.visitCode(); - // if (USE_HASH) - if (accs.length == 0) { - mv.visitFrame(F_SAME, 0, null, 0, null); - } else if (accs.length > HASH_LIMIT) { - mv.visitVarInsn(ILOAD, 2); - Label[] labels = ASMUtil.newLabels(accs.length); - Label defaultLabel = new Label(); - mv.visitTableSwitchInsn(0, labels.length - 1, defaultLabel, labels); - int i = 0; - for (Accessor acc : accs) { - mv.visitLabel(labels[i++]); - mv.visitFrame(F_SAME, 0, null, 0, null); - if (!acc.isReadable()) { - mv.visitInsn(ACONST_NULL); - mv.visitInsn(ARETURN); - continue; - } - mv.visitVarInsn(ALOAD, 1); - mv.visitTypeInsn(CHECKCAST, classNameInternal); - Type fieldType = Type.getType(acc.getType()); - if (acc.isPublic()) { - mv.visitFieldInsn(GETFIELD, classNameInternal, acc.getName(), fieldType.getDescriptor()); - } else { - String sig = Type.getMethodDescriptor(acc.getter); - mv.visitMethodInsn(INVOKEVIRTUAL, classNameInternal, acc.getter.getName(), sig); - } - ASMUtil.autoBoxing(mv, fieldType); - mv.visitInsn(ARETURN); - } - mv.visitLabel(defaultLabel); - mv.visitFrame(F_SAME, 0, null, 0, null); - } else { - Label[] labels = ASMUtil.newLabels(accs.length); - int i = 0; - for (Accessor acc : accs) { - ifNotEqJmp(mv, 2, i, labels[i]); - mv.visitVarInsn(ALOAD, 1); - mv.visitTypeInsn(CHECKCAST, classNameInternal); - Type fieldType = Type.getType(acc.getType()); - if (acc.isPublic()) { - mv.visitFieldInsn(GETFIELD, classNameInternal, acc.getName(), fieldType.getDescriptor()); - } else { - if (acc.getter == null) - throw new RuntimeException("no Getter for field " + acc.getName() + " in class " + this.className); - String sig = Type.getMethodDescriptor(acc.getter); - mv.visitMethodInsn(INVOKEVIRTUAL, classNameInternal, acc.getter.getName(), sig); - } - ASMUtil.autoBoxing(mv, fieldType); - mv.visitInsn(ARETURN); - - mv.visitLabel(labels[i]); - mv.visitFrame(F_SAME, 0, null, 0, null); - i++; - } - } - - if (exeptionClass != null) - throwExIntParam(mv, exeptionClass); - else { - mv.visitInsn(ACONST_NULL); - mv.visitInsn(ARETURN); - } - mv.visitMaxs(0, 0); - mv.visitEnd(); - - if (!USE_HASH) { - // Object get(Object object, String methodName) - mv = cw.visitMethod(ACC_PUBLIC, "set", "(Ljava/lang/Object;Ljava/lang/String;Ljava/lang/Object;)V", null, null); - mv.visitCode(); - - Label[] labels = ASMUtil.newLabels(accs.length); - - int i = 0; - for (Accessor acc : accs) { - mv.visitVarInsn(ALOAD, 2); - mv.visitLdcInsn(acc.fieldName); - mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/String", "equals", "(Ljava/lang/Object;)Z"); - mv.visitJumpInsn(IFEQ, labels[i]); - internalSetFiled(mv, acc); - mv.visitLabel(labels[i]); - mv.visitFrame(F_SAME, 0, null, 0, null); - i++; - } - if (exeptionClass != null) - throwExStrParam(mv, exeptionClass); - else - mv.visitInsn(RETURN); - mv.visitMaxs(0, 0); // 2,4 - mv.visitEnd(); - } - - if (!USE_HASH) { - // get(Object object, String methodName) - mv = cw.visitMethod(ACC_PUBLIC, "get", "(Ljava/lang/Object;Ljava/lang/String;)Ljava/lang/Object;", null, null); - mv.visitCode(); - - Label[] labels = ASMUtil.newLabels(accs.length); - - int i = 0; - for (Accessor acc : accs) { - mv.visitVarInsn(ALOAD, 2); // methodName - mv.visitLdcInsn(acc.fieldName); - mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/String", "equals", "(Ljava/lang/Object;)Z"); - mv.visitJumpInsn(IFEQ, labels[i]); - mv.visitVarInsn(ALOAD, 1); // object - mv.visitTypeInsn(CHECKCAST, classNameInternal); - Type fieldType = Type.getType(acc.getType()); - if (acc.isPublic()) { - mv.visitFieldInsn(GETFIELD, classNameInternal, acc.getName(), fieldType.getDescriptor()); - } else { - String sig = Type.getMethodDescriptor(acc.getter); - mv.visitMethodInsn(INVOKEVIRTUAL, classNameInternal, acc.getter.getName(), sig); - } - ASMUtil.autoBoxing(mv, fieldType); - mv.visitInsn(ARETURN); - mv.visitLabel(labels[i]); - mv.visitFrame(F_SAME, 0, null, 0, null); - i++; - } - if (exeptionClass != null) - throwExStrParam(mv, exeptionClass); - else { - mv.visitInsn(ACONST_NULL); - mv.visitInsn(ARETURN); - } - mv.visitMaxs(0, 0); - mv.visitEnd(); - } - - { - mv = cw.visitMethod(ACC_PUBLIC, "newInstance", "()Ljava/lang/Object;", null, null); - mv.visitCode(); - mv.visitTypeInsn(NEW, classNameInternal); - mv.visitInsn(DUP); - mv.visitMethodInsn(INVOKESPECIAL, classNameInternal, "", "()V"); - mv.visitInsn(ARETURN); - mv.visitMaxs(2, 1); - mv.visitEnd(); - } - cw.visitEnd(); - byte[] data = cw.toByteArray(); - // dumpDebug(data, "/tmp/debug-" + accessClassName + ".txt"); - return loader.defineClass(accessClassName, data); - } - - /** - * Dump Generate Code - */ - @SuppressWarnings("unused") - private void dumpDebug(byte[] data, String destFile) { - // try { - // File debug = new File(destFile); - // int flags = ClassReader.SKIP_DEBUG; - // ClassReader cr = new ClassReader(new ByteArrayInputStream(data)); - // cr.accept(new ASMifierClassVisitor(new PrintWriter(debug)), - // ASMifierClassVisitor.getDefaultAttributes(), - // flags); - // } catch (Exception e) { - // } - } - - /** - * Dump Set Field Code - * - * @param mv - * @param acc - */ - private void internalSetFiled(MethodVisitor mv, Accessor acc) { - /** - * FNC params - * - * 1 -> object to alter - * - * 2 -> id of field - * - * 3 -> new value - */ - mv.visitVarInsn(ALOAD, 1); - mv.visitTypeInsn(CHECKCAST, classNameInternal); - // get VELUE - mv.visitVarInsn(ALOAD, 3); - Type fieldType = Type.getType(acc.getType()); - Class type = acc.getType(); - String destClsName = Type.getInternalName(type); - - Method conMtd = convMtds.get(type); - if (conMtd != null) { - // external converion - String clsSig = Type.getInternalName(conMtd.getDeclaringClass()); - String mtdName = conMtd.getName(); - String mtdSig = Type.getMethodDescriptor(conMtd); - mv.visitMethodInsn(INVOKESTATIC, clsSig, mtdName, mtdSig); - } else if (acc.isEnum()) { - // builtIn Enum Conversion - Label isNull = new Label(); - mv.visitJumpInsn(IFNULL, isNull); - mv.visitVarInsn(ALOAD, 3); - // mv.visitTypeInsn(CHECKCAST, "java/lang/String"); - mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Object", "toString", "()Ljava/lang/String;"); - mv.visitMethodInsn(INVOKESTATIC, destClsName, "valueOf", "(Ljava/lang/String;)L" + destClsName + ";"); - mv.visitVarInsn(ASTORE, 3); - mv.visitLabel(isNull); - mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null); - mv.visitVarInsn(ALOAD, 1); - mv.visitTypeInsn(CHECKCAST, this.classNameInternal); // "net/minidev/asm/bean/BEnumPriv" - mv.visitVarInsn(ALOAD, 3); - mv.visitTypeInsn(CHECKCAST, destClsName); - } else if (type.equals(String.class)) { - // built In String Conversion - Label isNull = new Label(); - mv.visitJumpInsn(IFNULL, isNull); - mv.visitVarInsn(ALOAD, 3); - mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Object", "toString", "()Ljava/lang/String;"); - mv.visitVarInsn(ASTORE, 3); - mv.visitLabel(isNull); - mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null); - mv.visitVarInsn(ALOAD, 1); - mv.visitTypeInsn(CHECKCAST, this.classNameInternal); - mv.visitVarInsn(ALOAD, 3); - mv.visitTypeInsn(CHECKCAST, destClsName); - } else { - // just check Cast - mv.visitTypeInsn(CHECKCAST, destClsName); - } - if (acc.isPublic()) { - mv.visitFieldInsn(PUTFIELD, classNameInternal, acc.getName(), fieldType.getDescriptor()); - } else { - String sig = Type.getMethodDescriptor(acc.setter); - mv.visitMethodInsn(INVOKEVIRTUAL, classNameInternal, acc.setter.getName(), sig); - } - mv.visitInsn(RETURN); - } - - /** - * add Throws statement with int param 2 - */ - private void throwExIntParam(MethodVisitor mv, Class exCls) { - String exSig = Type.getInternalName(exCls); - mv.visitTypeInsn(NEW, exSig); - mv.visitInsn(DUP); - mv.visitLdcInsn("mapping " + this.className + " failed to map field:"); - mv.visitVarInsn(ILOAD, 2); - mv.visitMethodInsn(INVOKESTATIC, "java/lang/Integer", "toString", "(I)Ljava/lang/String;"); - mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/String", "concat", "(Ljava/lang/String;)Ljava/lang/String;"); - mv.visitMethodInsn(INVOKESPECIAL, exSig, "", "(Ljava/lang/String;)V"); - mv.visitInsn(ATHROW); - } - - /** - * add Throws statement with String param 2 - */ - private void throwExStrParam(MethodVisitor mv, Class exCls) { - String exSig = Type.getInternalName(exCls); - mv.visitTypeInsn(NEW, exSig); - mv.visitInsn(DUP); - mv.visitLdcInsn("mapping " + this.className + " failed to map field:"); - mv.visitVarInsn(ALOAD, 2); - mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/String", "concat", "(Ljava/lang/String;)Ljava/lang/String;"); - mv.visitMethodInsn(INVOKESPECIAL, exSig, "", "(Ljava/lang/String;)V"); - mv.visitInsn(ATHROW); - } - - /** - * dump a Jump if not EQ - */ - private void ifNotEqJmp(MethodVisitor mv, int param, int value, Label label) { - mv.visitVarInsn(ILOAD, param); - if (value == 0) { - /* notest forvalue 0 */ - mv.visitJumpInsn(IFNE, label); - } else if (value == 1) { - mv.visitInsn(ICONST_1); - mv.visitJumpInsn(IF_ICMPNE, label); - } else if (value == 2) { - mv.visitInsn(ICONST_2); - mv.visitJumpInsn(IF_ICMPNE, label); - } else if (value == 3) { - mv.visitInsn(ICONST_3); - mv.visitJumpInsn(IF_ICMPNE, label); - } else if (value == 4) { - mv.visitInsn(ICONST_4); - mv.visitJumpInsn(IF_ICMPNE, label); - } else if (value == 5) { - mv.visitInsn(ICONST_5); - mv.visitJumpInsn(IF_ICMPNE, label); - } else if (value >= 6) { - mv.visitIntInsn(BIPUSH, value); - mv.visitJumpInsn(IF_ICMPNE, label); - } else { - throw new RuntimeException("non supported negative values"); - } - } -} diff --git a/maxkey-jose-jwt/src/main/java/net/minidev/asm/BeansAccessConfig.java b/maxkey-jose-jwt/src/main/java/net/minidev/asm/BeansAccessConfig.java deleted file mode 100644 index 927a78d7c..000000000 --- a/maxkey-jose-jwt/src/main/java/net/minidev/asm/BeansAccessConfig.java +++ /dev/null @@ -1,74 +0,0 @@ -package net.minidev.asm; - -import java.util.HashMap; -import java.util.LinkedHashSet; - -public class BeansAccessConfig { - /** - * Field type convertor for all classes - * - * Convertor classes should contains mapping method Prototyped as: - * - * public static DestinationType Method(Object data); - * - * @see DefaultConverter - */ - //static protected LinkedHashSet> globalMapper = new LinkedHashSet>(); - - /** - * Field type convertor for custom Class - * - * Convertor classes should contains mapping method Prototyped as: - * - * public static DestinationType Method(Object data); - * - * @see DefaultConverter - */ - static protected HashMap, LinkedHashSet>> classMapper = new HashMap, LinkedHashSet>>(); - - /** - * FiledName remapper for a specific class or interface - */ - static protected HashMap, HashMap> classFiledNameMapper = new HashMap, HashMap>(); - - static { - addTypeMapper(Object.class, DefaultConverter.class); - addTypeMapper(Object.class, ConvertDate.class); - } - -// /** -// * Field type convertor for all classes -// * -// * Convertor classes should contains mapping method Prototyped as: -// * -// * public static DestinationType Method(Object data); -// * -// * @see DefaultConverter -// */ -// public static void addGlobalTypeMapper(Class mapper) { -// synchronized (globalMapper) { -// globalMapper.add(mapper); -// } -// } - - /** - * Field type convertor for all classes - * - * Convertor classes should contains mapping method Prototyped as: - * - * public static DestinationType Method(Object data); - * - * @see DefaultConverter - */ - public static void addTypeMapper(Class clz, Class mapper) { - synchronized (classMapper) { - LinkedHashSet> h = classMapper.get(clz); - if (h == null) { - h = new LinkedHashSet>(); - classMapper.put(clz, h); - } - - h.add(mapper); - } - } -} diff --git a/maxkey-jose-jwt/src/main/java/net/minidev/asm/ConvertDate.java b/maxkey-jose-jwt/src/main/java/net/minidev/asm/ConvertDate.java deleted file mode 100644 index f94e9bd07..000000000 --- a/maxkey-jose-jwt/src/main/java/net/minidev/asm/ConvertDate.java +++ /dev/null @@ -1,290 +0,0 @@ -package net.minidev.asm; - -import java.text.DateFormatSymbols; -import java.util.Calendar; -import java.util.Comparator; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.HashSet; -import java.util.Locale; -import java.util.StringTokenizer; -import java.util.TreeMap; - -public class ConvertDate { - static TreeMap monthsTable = new TreeMap(new StringCmpNS()); // StringCmpNS.COMP - static TreeMap daysTable = new TreeMap(new StringCmpNS()); // StringCmpNS.COMP - private static HashSet voidData = new HashSet(); - - public static class StringCmpNS implements Comparator { - @Override - public int compare(String o1, String o2) { - return o1.compareToIgnoreCase(o2); - } - } - - public static Integer getMonth(String month) { - return monthsTable.get(month); - } - - private static Integer parseMonth(String s1) { - if (Character.isDigit(s1.charAt(0))) { - return Integer.parseInt(s1) - 1; - } else { - Integer month = monthsTable.get(s1); - if (month == null) - throw new NullPointerException("can not parse " + s1 + " as month"); - return month.intValue(); - } - } - - static { - voidData.add("CET"); - voidData.add("MEZ"); - voidData.add("Uhr"); - voidData.add("h"); - voidData.add("pm"); - voidData.add("PM"); - voidData.add("o'clock"); - - // for (int c = 1; c <= 31; c++) { - // String s = Integer.toString(c); - // if (c < 10) - // daysTable.put("0".concat(s), c - 1); - // daysTable.put(s, c - 1); - // } - - // for (int c = 1; c <= 12; c++) { - // String s = Integer.toString(c); - // if (c < 10) - // monthsTable.put("0".concat(s), c - 1); - // monthsTable.put(s, c - 1); - // } - - for (Locale locale : DateFormatSymbols.getAvailableLocales()) { - if ("ja".equals(locale.getLanguage())) - continue; - if ("ko".equals(locale.getLanguage())) - continue; - if ("zh".equals(locale.getLanguage())) - continue; - DateFormatSymbols dfs = DateFormatSymbols.getInstance(locale); - String[] keys = dfs.getMonths(); - for (int i = 0; i < keys.length; i++) { - if (keys[i].length() == 0) - continue; - fillMap(monthsTable, keys[i], Integer.valueOf(i)); - } - keys = dfs.getShortMonths(); - for (int i = 0; i < keys.length; i++) { - String s = keys[i]; - if (s.length() == 0) - continue; - if (Character.isDigit(s.charAt(s.length() - 1))) - continue; - fillMap(monthsTable, keys[i], Integer.valueOf(i)); - fillMap(monthsTable, keys[i].replace(".", ""), Integer.valueOf(i)); - } - keys = dfs.getWeekdays(); - for (int i = 0; i < keys.length; i++) { - String s = keys[i]; - if (s.length() == 0) - continue; - fillMap(daysTable, s, Integer.valueOf(i)); - fillMap(daysTable, s.replace(".", ""), Integer.valueOf(i)); - } - keys = dfs.getShortWeekdays(); - for (int i = 0; i < keys.length; i++) { - String s = keys[i]; - if (s.length() == 0) - continue; - fillMap(daysTable, s, Integer.valueOf(i)); - fillMap(daysTable, s.replace(".", ""), Integer.valueOf(i)); - } - } - } - - private static void fillMap(TreeMap map, String key, Integer value) { - map.put(key, value); - key = key.replace("é", "e"); - key = key.replace("û", "u"); - map.put(key, value); - } - - /** - * try read a Date from a Object - */ - public static Date convertToDate(Object obj) { - if (obj == null) - return null; - if (obj instanceof Date) - return (Date) obj; - if (obj instanceof String) { - StringTokenizer st = new StringTokenizer((String) obj, " -/:,.+"); - String s1 = ""; - if (!st.hasMoreTokens()) - return null; - s1 = st.nextToken(); - if (s1.length() == 4 && Character.isDigit(s1.charAt(0))) - return getYYYYMMDD(st, s1); - // skip Day if present. - if (daysTable.containsKey(s1)) { - if (!st.hasMoreTokens()) - return null; - s1 = st.nextToken(); - } - if (monthsTable.containsKey(s1)) - return getMMDDYYYY(st, s1); - - if (Character.isDigit(s1.charAt(0))) - return getDDMMYYYY(st, s1); - return null; - } - throw new RuntimeException("Primitive: Can not convert " + obj.getClass().getName() + " to int"); - } - - private static Date getYYYYMMDD(StringTokenizer st, String s1) { - GregorianCalendar cal = new GregorianCalendar(2000, 0, 0, 0, 0, 0); - cal.setTimeInMillis(0); - - int year = Integer.parseInt(s1); - cal.set(Calendar.YEAR, year); - if (!st.hasMoreTokens()) - return cal.getTime(); - s1 = st.nextToken(); - - cal.set(Calendar.MONTH, parseMonth(s1)); - if (!st.hasMoreTokens()) - return cal.getTime(); - - s1 = st.nextToken(); - if (Character.isDigit(s1.charAt(0))) { - if (s1.length()==5 && s1.charAt(2) == 'T') { - // TIME + TIMEZONE - int day = Integer.parseInt(s1.substring(0,2)); - cal.set(Calendar.DAY_OF_MONTH, day); - return addHour(st, cal, s1.substring(3)); - } - int day = Integer.parseInt(s1); - cal.set(Calendar.DAY_OF_MONTH, day); - return addHour(st, cal, null); - } - return cal.getTime(); - } - - private static int getYear(String s1) { - int year = Integer.parseInt(s1); - // CET ? - if (year < 100) { - if (year > 23) - year += 2000; - else - year += 1900; - } - return year; - } - - private static Date getMMDDYYYY(StringTokenizer st, String s1) { - GregorianCalendar cal = new GregorianCalendar(2000, 0, 0, 0, 0, 0); - Integer month = monthsTable.get(s1); - if (month == null) - throw new NullPointerException("can not parse " + s1 + " as month"); - cal.set(Calendar.MONTH, month); - if (!st.hasMoreTokens()) - return null; - s1 = st.nextToken(); - // DAY - int day = Integer.parseInt(s1); - cal.set(Calendar.DAY_OF_MONTH, day); - - if (!st.hasMoreTokens()) - return null; - s1 = st.nextToken(); - if (Character.isLetter(s1.charAt(0))) { - if (!st.hasMoreTokens()) - return null; - s1 = st.nextToken(); - } - cal.set(Calendar.YEAR, getYear(s1)); - - // /if (st.hasMoreTokens()) - // return null; - // s1 = st.nextToken(); - return addHour(st, cal, null); - // return cal.getTime(); - } - - private static Date getDDMMYYYY(StringTokenizer st, String s1) { - GregorianCalendar cal = new GregorianCalendar(2000, 0, 0, 0, 0, 0); - int day = Integer.parseInt(s1); - cal.set(Calendar.DAY_OF_MONTH, day); - if (!st.hasMoreTokens()) - return null; - s1 = st.nextToken(); - cal.set(Calendar.MONTH, parseMonth(s1)); - - if (!st.hasMoreTokens()) - return null; - s1 = st.nextToken(); - cal.set(Calendar.YEAR, getYear(s1)); - return addHour(st, cal, null); - } - - private static Date addHour(StringTokenizer st, Calendar cal, String s1) { - // String s1; - if (s1 == null) { - if (!st.hasMoreTokens()) - return cal.getTime(); - s1 = st.nextToken(); - } - cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(s1)); - - if (!st.hasMoreTokens()) - return cal.getTime(); - s1 = st.nextToken(); - - s1 = trySkip(st, s1, cal); - if (s1 == null) - return cal.getTime(); - - // if (s1.equalsIgnoreCase("h")) { - // if (!st.hasMoreTokens()) - // return cal.getTime(); - // s1 = st.nextToken(); - // } - cal.set(Calendar.MINUTE, Integer.parseInt(s1)); - - if (!st.hasMoreTokens()) - return cal.getTime(); - s1 = st.nextToken(); - - s1 = trySkip(st, s1, cal); - if (s1 == null) - return cal.getTime(); - - cal.set(Calendar.SECOND, Integer.parseInt(s1)); - if (!st.hasMoreTokens()) - return cal.getTime(); - s1 = st.nextToken(); - - s1 = trySkip(st, s1, cal); - if (s1 == null) - return cal.getTime(); - // TODO ADD TIME ZONE - s1 = trySkip(st, s1, cal); - // if (s1.equalsIgnoreCase("pm")) - // cal.add(Calendar.HOUR_OF_DAY, 12); - return cal.getTime(); - } - - private static String trySkip(StringTokenizer st, String s1, Calendar cal) { - while (voidData.contains(s1)) { - if (s1.equalsIgnoreCase("pm")) - cal.add(Calendar.HOUR_OF_DAY, 12); - if (!st.hasMoreTokens()) - return null; - s1 = st.nextToken(); - } - return s1; - } - -} diff --git a/maxkey-jose-jwt/src/main/java/net/minidev/asm/DefaultConverter.java b/maxkey-jose-jwt/src/main/java/net/minidev/asm/DefaultConverter.java deleted file mode 100644 index 621c4f245..000000000 --- a/maxkey-jose-jwt/src/main/java/net/minidev/asm/DefaultConverter.java +++ /dev/null @@ -1,183 +0,0 @@ -package net.minidev.asm; - -import net.minidev.asm.ex.ConvertException; - -public class DefaultConverter { - public static int convertToint(Object obj) { - if (obj == null) - return 0; - if (obj instanceof Number) - return ((Number) obj).intValue(); - if (obj instanceof String) - return Integer.parseInt((String) obj); - throw new ConvertException("Primitive: Can not convert " + obj.getClass().getName() + " to int"); - } - - public static Integer convertToInt(Object obj) { - if (obj == null) - return null; - Class c = obj.getClass(); - if (c == Integer.class) - return (Integer) obj; - if (obj instanceof Number) - return Integer.valueOf(((Number) obj).intValue()); - throw new ConvertException("Primitive: Can not convert " + obj.getClass().getName() + " to Integer"); - } - - public static short convertToshort(Object obj) { - if (obj == null) - return 0; - if (obj instanceof Number) - return ((Number) obj).shortValue(); - if (obj instanceof String) - return Short.parseShort((String) obj); - throw new ConvertException("Primitive: Can not convert " + obj.getClass().getName() + " to short"); - } - - public static Short convertToShort(Object obj) { - if (obj == null) - return null; - Class c = obj.getClass(); - if (c == Short.class) - return (Short) obj; - if (obj instanceof Number) - return Short.valueOf(((Number) obj).shortValue()); - throw new ConvertException("Primitive: Can not convert " + obj.getClass().getName() + " to Short"); - } - - public static long convertTolong(Object obj) { - if (obj == null) - return 0; - if (obj instanceof Number) - return ((Number) obj).longValue(); - if (obj instanceof String) - return Long.parseLong((String) obj); - throw new ConvertException("Primitive: Can not convert " + obj.getClass().getName() + " to long"); - } - - public static Long convertToLong(Object obj) { - if (obj == null) - return null; - Class c = obj.getClass(); - if (c == Long.class) - return (Long) obj; - if (obj instanceof Number) - return Long.valueOf(((Number) obj).longValue()); - throw new ConvertException("Primitive: Can not convert value '" + obj+ "' As " + obj.getClass().getName() + " to Long"); - } - - public static byte convertTobyte(Object obj) { - if (obj == null) - return 0; - if (obj instanceof Number) - return ((Number) obj).byteValue(); - if (obj instanceof String) - return Byte.parseByte((String) obj); - throw new ConvertException("Primitive: Can not convert " + obj.getClass().getName() + " to byte"); - } - - public static Byte convertToByte(Object obj) { - if (obj == null) - return null; - Class c = obj.getClass(); - if (c == Byte.class) - return (Byte) obj; - if (obj instanceof Number) - return Byte.valueOf(((Number) obj).byteValue()); - throw new ConvertException("Primitive: Can not convert " + obj.getClass().getName() + " to Byte"); - } - - public static float convertTofloat(Object obj) { - if (obj == null) - return 0f; - if (obj instanceof Number) - return ((Number) obj).floatValue(); - if (obj instanceof String) - return Float.parseFloat((String) obj); - throw new ConvertException("Primitive: Can not convert " + obj.getClass().getName() + " to float"); - } - - public static Float convertToFloat(Object obj) { - if (obj == null) - return null; - Class c = obj.getClass(); - if (c == Float.class) - return (Float) obj; - if (obj instanceof Number) - return Float.valueOf(((Number) obj).floatValue()); - throw new ConvertException("Primitive: Can not convert " + obj.getClass().getName() + " to Float"); - } - - public static double convertTodouble(Object obj) { - if (obj == null) - return 0.0; - if (obj instanceof Number) - return ((Number) obj).doubleValue(); - if (obj instanceof String) - return Double.parseDouble((String) obj); - throw new ConvertException("Primitive: Can not convert " + obj.getClass().getName() + " to float"); - } - - public static Double convertToDouble(Object obj) { - if (obj == null) - return null; - Class c = obj.getClass(); - if (c == Double.class) - return (Double) obj; - if (obj instanceof Number) - return Double.valueOf(((Number) obj).doubleValue()); - throw new ConvertException("Primitive: Can not convert " + obj.getClass().getName() + " to Float"); - } - - public static char convertTochar(Object obj) { - if (obj == null) - return ' '; - if (obj instanceof String) - if (((String) obj).length() > 0) - return ((String) obj).charAt(0); - else - return ' '; - throw new ConvertException("Primitive: Can not convert " + obj.getClass().getName() + " to char"); - } - - public static Character convertToChar(Object obj) { - if (obj == null) - return null; - Class c = obj.getClass(); - if (c == Character.class) - return (Character) obj; - if (obj instanceof String) - if (((String) obj).length() > 0) - return ((String) obj).charAt(0); - else - return ' '; - throw new ConvertException("Primitive: Can not convert " + obj.getClass().getName() + " to Character"); - } - - public static boolean convertTobool(Object obj) { - if (obj == null) - return false; - if (obj.getClass() == Boolean.class) - return ((Boolean) obj).booleanValue(); - if (obj instanceof String) - return Boolean.parseBoolean((String) obj); - if (obj instanceof Number) { - if (obj.toString().equals("0")) - return false; - else - return true; - } - throw new ConvertException("Primitive: Can not convert " + obj.getClass().getName() + " to boolean"); - } - - public static Boolean convertToBool(Object obj) { - if (obj == null) - return null; - Class c = obj.getClass(); - if (c == Boolean.class) - return (Boolean) obj; - if (obj instanceof String) - return Boolean.parseBoolean((String) obj); - throw new ConvertException("Primitive: Can not convert " + obj.getClass().getName() + " to Boolean"); - } -} diff --git a/maxkey-jose-jwt/src/main/java/net/minidev/asm/DynamicClassLoader.java b/maxkey-jose-jwt/src/main/java/net/minidev/asm/DynamicClassLoader.java deleted file mode 100644 index b904a9674..000000000 --- a/maxkey-jose-jwt/src/main/java/net/minidev/asm/DynamicClassLoader.java +++ /dev/null @@ -1,88 +0,0 @@ -package net.minidev.asm; - -/* - * Copyright 2011 JSON-SMART authors - * - * 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. - */ -import java.lang.reflect.Method; - -/** - * Simple extension from ClassLoader overiding the loadClass(String name, - * boolean resolve) method and allowing to register new classes - * - * @author uriel - * - */ -class DynamicClassLoader extends ClassLoader { - DynamicClassLoader(ClassLoader parent) { - super(parent); - } - - private final static String BEAN_AC = BeansAccess.class.getName(); - /** - * Predefined define defineClass method signature (name, bytes, offset, - * length) - */ - private final static Class[] DEF_CLASS_SIG = new Class[] { String.class, byte[].class, int.class, int.class }; - - /** - * - * @param parent used to choose the ClassLoader - * @param clsName C - * @param clsData - * @return - */ - public static Class directLoad(Class parent, String clsName, byte[] clsData) { - DynamicClassLoader loader = new DynamicClassLoader(parent.getClassLoader()); - @SuppressWarnings("unchecked") - Class clzz = (Class) loader.defineClass(clsName, clsData); - return clzz; - } - - public static T directInstance(Class parent, String clsName, byte[] clsData) throws InstantiationException, IllegalAccessException { - Class clzz = directLoad(parent, clsName, clsData); - return clzz.newInstance(); - } - - @Override - protected synchronized java.lang.Class loadClass(String name, boolean resolve) throws ClassNotFoundException { - /* - * check class by fullname as String. - */ - if (name.equals(BEAN_AC)) - return BeansAccess.class; - /* - * Use default class loader - */ - return super.loadClass(name, resolve); - } - - /** - * Call defineClass into the parent classLoader using the - * method.setAccessible(boolean) hack - * - * @see ClassLoader#defineClass(String, byte[], int, int) - */ - Class defineClass(String name, byte[] bytes) throws ClassFormatError { - try { - // Attempt to load the access class in the same loader, which makes - // protected and default access members accessible. - Method method = ClassLoader.class.getDeclaredMethod("defineClass", DEF_CLASS_SIG); - method.setAccessible(true); - return (Class) method.invoke(getParent(), new Object[] { name, bytes, Integer.valueOf(0), Integer.valueOf(bytes.length) }); - } catch (Exception ignored) { - } - return defineClass(name, bytes, 0, bytes.length); - } -} diff --git a/maxkey-jose-jwt/src/main/java/net/minidev/asm/FieldFilter.java b/maxkey-jose-jwt/src/main/java/net/minidev/asm/FieldFilter.java deleted file mode 100644 index baf11d2ef..000000000 --- a/maxkey-jose-jwt/src/main/java/net/minidev/asm/FieldFilter.java +++ /dev/null @@ -1,27 +0,0 @@ -package net.minidev.asm; - -import java.lang.reflect.Field; -import java.lang.reflect.Method; - -/** - * allow to control read/write access to field - * - */ -public interface FieldFilter { - /** - * NOT Implemented YET - */ - public boolean canUse(Field field); - - public boolean canUse(Field field, Method method); - - /** - * NOT Implemented YET - */ - public boolean canRead(Field field); - - /** - * NOT Implemented YET - */ - public boolean canWrite(Field field); -} diff --git a/maxkey-jose-jwt/src/main/java/net/minidev/asm/ex/ConvertException.java b/maxkey-jose-jwt/src/main/java/net/minidev/asm/ex/ConvertException.java deleted file mode 100644 index 8104c5b2a..000000000 --- a/maxkey-jose-jwt/src/main/java/net/minidev/asm/ex/ConvertException.java +++ /dev/null @@ -1,14 +0,0 @@ -package net.minidev.asm.ex; - -public class ConvertException extends RuntimeException { - private static final long serialVersionUID = 1L; - - public ConvertException() { - super(); - } - - public ConvertException(String message) { - super(message); - } - -} diff --git a/maxkey-jose-jwt/src/main/java/net/minidev/asm/ex/NoSuchFieldException.java b/maxkey-jose-jwt/src/main/java/net/minidev/asm/ex/NoSuchFieldException.java deleted file mode 100644 index 49766d226..000000000 --- a/maxkey-jose-jwt/src/main/java/net/minidev/asm/ex/NoSuchFieldException.java +++ /dev/null @@ -1,19 +0,0 @@ -package net.minidev.asm.ex; - -/** - * Same exception as java.lang.NoSuchFieldException but extends RuntimException - * - * @author uriel - * - */ -public class NoSuchFieldException extends RuntimeException { - private static final long serialVersionUID = 1L; - - public NoSuchFieldException() { - super(); - } - - public NoSuchFieldException(String message) { - super(message); - } -} diff --git a/maxkey-jose-jwt/src/main/java/net/minidev/json/JSONArray.java b/maxkey-jose-jwt/src/main/java/net/minidev/json/JSONArray.java deleted file mode 100644 index 9e6edbe95..000000000 --- a/maxkey-jose-jwt/src/main/java/net/minidev/json/JSONArray.java +++ /dev/null @@ -1,133 +0,0 @@ -package net.minidev.json; - -/* - * Copyright 2011 JSON-SMART authors - * - * 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. - */ -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import net.minidev.json.reader.JsonWriter; - -/** - * A JSON array. JSONObject supports java.util.List interface. - * - * @author FangYidong <fangyidong@yahoo.com.cn> - * @author Uriel Chemouni <uchemouni@gmail.com> - */ -public class JSONArray extends ArrayList implements List, JSONAwareEx, JSONStreamAwareEx { - private static final long serialVersionUID = 9106884089231309568L; - - public static String toJSONString(List list) { - return toJSONString(list, JSONValue.COMPRESSION); - } - - /** - * Convert a list to JSON text. The result is a JSON array. If this list is - * also a JSONAware, JSONAware specific behaviours will be omitted at this - * top level. - * - * @see net.minidev.json.JSONValue#toJSONString(Object) - * - * @param list - * @param compression - * Indicate compression level - * @return JSON text, or "null" if list is null. - */ - public static String toJSONString(List list, JSONStyle compression) { - StringBuilder sb = new StringBuilder(); - try { - writeJSONString(list, sb, compression); - } catch (IOException e) { - // Can not append on a string builder - } - return sb.toString(); - } - - /** - * Encode a list into JSON text and write it to out. If this list is also a - * JSONStreamAware or a JSONAware, JSONStreamAware and JSONAware specific - * behaviours will be ignored at this top level. - * - * @see JSONValue#writeJSONString(Object, Appendable) - * - * @param list - * @param out - */ - public static void writeJSONString(Iterable list, Appendable out, JSONStyle compression) - throws IOException { - if (list == null) { - out.append("null"); - return; - } - JsonWriter.JSONIterableWriter.writeJSONString(list, out, compression); - } - - public static void writeJSONString(List list, Appendable out) throws IOException { - writeJSONString(list, out, JSONValue.COMPRESSION); - } - - /** - * Appends the specified element and returns this. - * Handy alternative to add(E e) method. - * - * @param element element to be appended to this array. - * @return this - */ - public JSONArray appendElement(Object element) { - add(element); - return this; - } - - public void merge(Object o2) { - JSONObject.merge(this, o2); - } - - /** - * Explicitely Serialize Object as JSon String - */ - public String toJSONString() { - return toJSONString(this, JSONValue.COMPRESSION); - } - - public String toJSONString(JSONStyle compression) { - return toJSONString(this, compression); - } - - /** - * Override natif toStirng() - */ - public String toString() { - return toJSONString(); - } - - /** - * JSONAwareEx inferface - * - * @param compression - * compression param - */ - public String toString(JSONStyle compression) { - return toJSONString(compression); - } - - public void writeJSONString(Appendable out) throws IOException { - writeJSONString(this, out, JSONValue.COMPRESSION); - } - - public void writeJSONString(Appendable out, JSONStyle compression) throws IOException { - writeJSONString(this, out, compression); - } -} diff --git a/maxkey-jose-jwt/src/main/java/net/minidev/json/JSONAware.java b/maxkey-jose-jwt/src/main/java/net/minidev/json/JSONAware.java deleted file mode 100644 index ba39dfb39..000000000 --- a/maxkey-jose-jwt/src/main/java/net/minidev/json/JSONAware.java +++ /dev/null @@ -1,29 +0,0 @@ -package net.minidev.json; - -/* - * Copyright 2011 JSON-SMART authors - * - * 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. - */ -/** - * Beans that support customized output of JSON text shall implement this - * interface. - * - * @author FangYidong <fangyidong@yahoo.com.cn> - */ -public interface JSONAware { - /** - * @return JSON text - */ - String toJSONString(); -} diff --git a/maxkey-jose-jwt/src/main/java/net/minidev/json/JSONAwareEx.java b/maxkey-jose-jwt/src/main/java/net/minidev/json/JSONAwareEx.java deleted file mode 100644 index 9292e7609..000000000 --- a/maxkey-jose-jwt/src/main/java/net/minidev/json/JSONAwareEx.java +++ /dev/null @@ -1,31 +0,0 @@ -package net.minidev.json; - -/* - * Copyright 2011 JSON-SMART authors - * - * 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. - */ -/** - * Beans that support advanced output of JSON text shall implement this interface. - * - * Adding compressions and formating features - * - * @author Uriel Chemouni <uchemouni@gmail.com> - */ - -public interface JSONAwareEx extends JSONAware{ - /** - * @return JSON text - */ - String toJSONString(JSONStyle compression); -} diff --git a/maxkey-jose-jwt/src/main/java/net/minidev/json/JSONNavi.java b/maxkey-jose-jwt/src/main/java/net/minidev/json/JSONNavi.java deleted file mode 100644 index 7a5b378a7..000000000 --- a/maxkey-jose-jwt/src/main/java/net/minidev/json/JSONNavi.java +++ /dev/null @@ -1,727 +0,0 @@ -package net.minidev.json; - -/* - * Copyright 2011 JSON-SMART authors - * - * 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. - */ -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.Stack; - -import net.minidev.json.writer.JsonReaderI; - -/** - * A JQuery like Json editor, accessor. - * - * @since 1.0.9 - * - * @author Uriel Chemouni <uchemouni@gmail.com> - */ -public class JSONNavi { - private JsonReaderI mapper; - private T root; - - private Stack stack = new Stack(); - private Stack path = new Stack(); - - private Object current; - private boolean failure = false; - private String failureMessage; - - private boolean readonly = false; - private Object missingKey = null; - - public static JSONNavi newInstance() { - return new JSONNavi(JSONValue.defaultReader.DEFAULT_ORDERED); - } - - public static JSONNavi newInstanceObject() { - JSONNavi o = new JSONNavi(JSONValue.defaultReader.getMapper(JSONObject.class)); - o.object(); - return o; - } - - public static JSONNavi newInstanceArray() { - JSONNavi o = new JSONNavi(JSONValue.defaultReader.getMapper(JSONArray.class)); - o.array(); - return o; - } - - public JSONNavi(JsonReaderI mapper) { - this.mapper = mapper; - } - - @SuppressWarnings("unchecked") - public JSONNavi(String json) { - this.root = (T) JSONValue.parse(json); - this.current = this.root; - readonly = true; - } - - public JSONNavi(String json, JsonReaderI mapper) { - this.root = JSONValue.parse(json, mapper); - this.mapper = mapper; - this.current = this.root; - readonly = true; - } - - public JSONNavi(String json, Class mapTo) { - this.root = JSONValue.parse(json, mapTo); - this.mapper = JSONValue.defaultReader.getMapper(mapTo); - this.current = this.root; - readonly = true; - } - - /** - * return to root node - */ - public JSONNavi root() { - this.current = this.root; - this.stack.clear(); - this.path.clear(); - this.failure = false; - this.missingKey = null; - this.failureMessage = null; - return this; - } - - public boolean hasFailure() { - return failure; - } - - public Object getCurrentObject() { - return current; - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - public Collection getKeys() { - if (current instanceof Map) - return ((Map) current).keySet(); - return null; - } - - public int getSize() { - if (current == null) - return 0; - if (isArray()) - return ((List) current).size(); - if (isObject()) - return ((Map) current).size(); - return 1; - } - - public String getString(String key) { - String v = null; - if (!hasKey(key)) - return v; - at(key); - v = asString(); - up(); - return v; - } - - public int getInt(String key) { - int v = 0; - if (!hasKey(key)) - return v; - at(key); - v = asInt(); - up(); - return v; - } - - public Integer getInteger(String key) { - Integer v = null; - if (!hasKey(key)) - return v; - at(key); - v = asIntegerObj(); - up(); - return v; - } - - public double getDouble(String key) { - double v = 0; - if (!hasKey(key)) - return v; - at(key); - v = asDouble(); - up(); - return v; - } - - public boolean hasKey(String key) { - if (!isObject()) - return false; - return o(current).containsKey(key); - } - - public JSONNavi at(String key) { - if (failure) - return this; - if (!isObject()) - object(); - if (!(current instanceof Map)) - return failure("current node is not an Object", key); - if (!o(current).containsKey(key)) { - if (readonly) - return failure("current Object have no key named " + key, key); - stack.add(current); - path.add(key); - current = null; - missingKey = key; - return this; - } - Object next = o(current).get(key); - stack.add(current); - path.add(key); - current = next; - return this; - } - - public Object get(String key) { - if (failure) - return this; - if (!isObject()) - object(); - if (!(current instanceof Map)) - return failure("current node is not an Object", key); - return o(current).get(key); - } - - public Object get(int index) { - if (failure) - return this; - if (!isArray()) - array(); - if (!(current instanceof List)) - return failure("current node is not an List", index); - return a(current).get(index); - } - - public JSONNavi set(String key, String value) { - object(); - if (failure) - return this; - o(current).put(key, value); - return this; - } - - public JSONNavi set(String key, Number value) { - object(); - if (failure) - return this; - o(current).put(key, value); - return this; - } - - /** - * write an value in the current object - * - * @param key - * key to access - * @param value - * new value - * @return this - */ - public JSONNavi set(String key, long value) { - return set(key, Long.valueOf(value)); - } - - /** - * write an value in the current object - * - * @param key - * key to access - * @param value - * new value - * @return this - */ - public JSONNavi set(String key, int value) { - return set(key, Integer.valueOf(value)); - } - - /** - * write an value in the current object - * - * @param key - * key to access - * @param value - * new value - * @return this - */ - public JSONNavi set(String key, double value) { - return set(key, Double.valueOf(value)); - } - - /** - * write an value in the current object - * - * @param key - * key to access - * @param value - * new value - * @return this - */ - public JSONNavi set(String key, float value) { - return set(key, Float.valueOf(value)); - } - - /** - * add value to the current arrays - * - * @param values - * to add - * @return this - */ - public JSONNavi add(Object... values) { - array(); - if (failure) - return this; - List list = a(current); - for (Object o : values) - list.add(o); - return this; - } - - /** - * get the current object value as String if the current Object is null - * return null. - */ - public String asString() { - if (current == null) - return null; - if (current instanceof String) - return (String) current; - return current.toString(); - } - - /** - * get the current value as double if the current Object is null return - * Double.NaN - */ - public double asDouble() { - if (current instanceof Number) - return ((Number) current).doubleValue(); - return Double.NaN; - } - - /** - * get the current object value as Double if the current Double can not be - * cast as Integer return null. - */ - public Double asDoubleObj() { - if (current == null) - return null; - if (current instanceof Number) { - if (current instanceof Double) - return (Double) current; - return Double.valueOf(((Number) current).doubleValue()); - } - return Double.NaN; - } - - /** - * get the current value as float if the current Object is null return - * Float.NaN - */ - public double asFloat() { - if (current instanceof Number) - return ((Number) current).floatValue(); - return Float.NaN; - } - - /** - * get the current object value as Float if the current Float can not be - * cast as Integer return null. - */ - public Float asFloatObj() { - if (current == null) - return null; - if (current instanceof Number) { - if (current instanceof Float) - return (Float) current; - return Float.valueOf(((Number) current).floatValue()); - } - return Float.NaN; - } - - /** - * get the current value as int if the current Object is null return 0 - */ - public int asInt() { - if (current instanceof Number) - return ((Number) current).intValue(); - return 0; - } - - /** - * get the current object value as Integer if the current Object can not be - * cast as Integer return null. - */ - public Integer asIntegerObj() { - if (current == null) - return null; - if (current instanceof Number) { - if (current instanceof Integer) - return (Integer) current; - if (current instanceof Long) { - Long l = (Long) current; - if (l.longValue() == l.intValue()) { - return Integer.valueOf(l.intValue()); - } - } - return null; - } - return null; - } - - /** - * get the current value as long if the current Object is null return 0 - */ - public long asLong() { - if (current instanceof Number) - return ((Number) current).longValue(); - return 0L; - } - - /** - * get the current object value as Long if the current Object can not be - * cast as Long return null. - */ - public Long asLongObj() { - if (current == null) - return null; - if (current instanceof Number) { - if (current instanceof Long) - return (Long) current; - if (current instanceof Integer) - return Long.valueOf(((Number) current).longValue()); - return null; - } - return null; - } - - /** - * get the current value as boolean if the current Object is null or is not - * a boolean return false - */ - public boolean asBoolean() { - if (current instanceof Boolean) - return ((Boolean) current).booleanValue(); - return false; - } - - /** - * get the current object value as Boolean if the current Object is not a - * Boolean return null. - */ - public Boolean asBooleanObj() { - if (current == null) - return null; - if (current instanceof Boolean) - return (Boolean) current; - return null; - } - - /** - * Set current value as Json Object You can also skip this call, Objects can - * be create automatically. - */ - @SuppressWarnings("unchecked") - public JSONNavi object() { - if (failure) - return this; - if (current == null && readonly) - failure("Can not create Object child in readonly", null); - if (current != null) { - if (isObject()) - return this; - if (isArray()) - failure("can not use Object feature on Array.", null); - failure("Can not use current possition as Object", null); - } else { - current = mapper.createObject(); - } - if (root == null) - root = (T) current; - else - store(); - return this; - } - - /** - * Set current value as Json Array You can also skip this call Arrays can be - * create automatically. - */ - @SuppressWarnings("unchecked") - public JSONNavi array() { - if (failure) - return this; - if (current == null && readonly) - failure("Can not create Array child in readonly", null); - if (current != null) { - if (isArray()) - return this; - if (isObject()) - failure("can not use Object feature on Array.", null); - failure("Can not use current possition as Object", null); - } else { - current = mapper.createArray(); - } - if (root == null) - root = (T) current; - else - store(); - return this; - } - - /** - * set current value as Number - */ - public JSONNavi set(Number num) { - if (failure) - return this; - current = num; - store(); - return this; - } - - /** - * set current value as Boolean - */ - public JSONNavi set(Boolean bool) { - if (failure) - return this; - current = bool; - store(); - return this; - } - - /** - * set current value as String - */ - public JSONNavi set(String text) { - if (failure) - return this; - current = text; - store(); - return this; - } - - public T getRoot() { - return root; - } - - /** - * internal store current Object in current non existing localization - */ - private void store() { - Object parent = stack.peek(); - if (isObject(parent)) - o(parent).put((String) missingKey, current); - else if (isArray(parent)) { - int index = ((Number) missingKey).intValue(); - List lst = a(parent); - while (lst.size() <= index) - lst.add(null); - lst.set(index, current); - } - } - - /** - * is the current node is an array - */ - public boolean isArray() { - return isArray(current); - } - - /** - * is the current node is an object - */ - public boolean isObject() { - return isObject(current); - } - - /** - * check if Object is an Array - */ - private boolean isArray(Object obj) { - if (obj == null) - return false; - return (obj instanceof List); - } - - /** - * check if Object is an Map - */ - private boolean isObject(Object obj) { - if (obj == null) - return false; - return (obj instanceof Map); - } - - /** - * internal cast to List - */ - @SuppressWarnings("unchecked") - private List a(Object obj) { - return (List) obj; - } - - /** - * internal cast to Map - */ - @SuppressWarnings("unchecked") - private Map o(Object obj) { - return (Map) obj; - } - - /** - * Access to the index position. - * - * If index is less than 0 access element index from the end like in python. - * - * @param index - * 0 based desired position in Array - */ - public JSONNavi at(int index) { - if (failure) - return this; - if (!(current instanceof List)) - return failure("current node is not an Array", index); - @SuppressWarnings("unchecked") - List lst = ((List) current); - if (index < 0) { - index = lst.size() + index; - if (index < 0) - index = 0; - } - if (index >= lst.size()) - if (readonly) - return failure("Out of bound exception for index", index); - else { - stack.add(current); - path.add(index); - current = null; - missingKey = index; - return this; - } - Object next = lst.get(index); - stack.add(current); - path.add(index); - current = next; - return this; - } - - /** - * Access to last + 1 the index position. - * - * this method can only be used in writing mode. - */ - public JSONNavi atNext() { - if (failure) - return this; - if (!(current instanceof List)) - return failure("current node is not an Array", null); - @SuppressWarnings("unchecked") - List lst = ((List) current); - return at(lst.size()); - } - - /** - * call up() level times. - * - * @param level - * number of parent move. - */ - public JSONNavi up(int level) { - while (level-- > 0) { - if (stack.size() > 0) { - current = stack.pop(); - path.pop(); - } else - break; - } - return this; - } - - /** - * Move one level up in Json tree. if no more level up is available the - * statement had no effect. - */ - public JSONNavi up() { - if (stack.size() > 0) { - current = stack.pop(); - path.pop(); - } - return this; - } - - private final static JSONStyle ERROR_COMPRESS = new JSONStyle(JSONStyle.FLAG_PROTECT_4WEB); - - /** - * return the Object as a Json String - */ - public String toString() { - if (failure) - return JSONValue.toJSONString(failureMessage, ERROR_COMPRESS); - return JSONValue.toJSONString(root); - } - - /** - * return the Object as a Json String - * - * @param compression - */ - public String toString(JSONStyle compression) { - if (failure) - return JSONValue.toJSONString(failureMessage, compression); - return JSONValue.toJSONString(root, compression); - } - - /** - * Internally log errors. - */ - private JSONNavi failure(String err, Object jPathPostfix) { - failure = true; - StringBuilder sb = new StringBuilder(); - sb.append("Error: "); - sb.append(err); - sb.append(" at "); - sb.append(getJPath()); - if (jPathPostfix != null) - if (jPathPostfix instanceof Integer) - sb.append('[').append(jPathPostfix).append(']'); - else - sb.append('/').append(jPathPostfix); - this.failureMessage = sb.toString(); - return this; - } - - /** - * @return JPath to the current position - */ - public String getJPath() { - StringBuilder sb = new StringBuilder(); - for (Object o : path) { - if (o instanceof String) - sb.append('/').append(o.toString()); - else - sb.append('[').append(o.toString()).append(']'); - } - return sb.toString(); - } -} diff --git a/maxkey-jose-jwt/src/main/java/net/minidev/json/JSONObject.java b/maxkey-jose-jwt/src/main/java/net/minidev/json/JSONObject.java deleted file mode 100644 index 721821771..000000000 --- a/maxkey-jose-jwt/src/main/java/net/minidev/json/JSONObject.java +++ /dev/null @@ -1,274 +0,0 @@ -package net.minidev.json; - -/* - * Copyright 2011 JSON-SMART authors - * - * 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. - */ -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -import net.minidev.json.reader.JsonWriter; - -/** - * A JSON object. Key value pairs are unordered. JSONObject supports - * java.util.Map interface. - * - * @author FangYidong <fangyidong@yahoo.com.cn> - * @author Uriel Chemouni <uchemouni@gmail.com> - */ -public class JSONObject extends HashMap implements JSONAware, JSONAwareEx, JSONStreamAwareEx { - private static final long serialVersionUID = -503443796854799292L; - - public JSONObject() { - super(); - } - - // /** - // * Allow simply casting to Map - // */ - // @SuppressWarnings("unchecked") - // public T cast() { - // return (T) this; - // } - - /** - * Escape quotes, \, /, \r, \n, \b, \f, \t and other control characters - * (U+0000 through U+001F). It's the same as JSONValue.escape() only for - * compatibility here. - * - * @see JSONValue#escape(String) - */ - public static String escape(String s) { - return JSONValue.escape(s); - } - - public static String toJSONString(Map map) { - return toJSONString(map, JSONValue.COMPRESSION); - } - - /** - * Convert a map to JSON text. The result is a JSON object. If this map is - * also a JSONAware, JSONAware specific behaviours will be omitted at this - * top level. - * - * @see net.minidev.json.JSONValue#toJSONString(Object) - * - * @param map - * @return JSON text, or "null" if map is null. - */ - public static String toJSONString(Map map, JSONStyle compression) { - StringBuilder sb = new StringBuilder(); - try { - writeJSON(map, sb, compression); - } catch (IOException e) { - // can not append on a StringBuilder - } - return sb.toString(); - } - - /** - * Write a Key : value entry to a stream - */ - public static void writeJSONKV(String key, Object value, Appendable out, JSONStyle compression) throws IOException { - if (key == null) - out.append("null"); - else if (!compression.mustProtectKey(key)) - out.append(key); - else { - out.append('"'); - JSONValue.escape(key, out, compression); - out.append('"'); - } - out.append(':'); - if (value instanceof String) - compression.writeString(out, (String) value); - else - JSONValue.writeJSONString(value, out, compression); - } - - /** - * Puts value to object and returns this. - * Handy alternative to put(String key, Object value) method. - * - * @param fieldName key with which the specified value is to be associated - * @param fieldValue value to be associated with the specified key - * @return this - */ - public JSONObject appendField(String fieldName, Object fieldValue) { - put(fieldName, fieldValue); - return this; - } - - /** - * A Simple Helper object to String - * - * @return a value.toString() or null - */ - public String getAsString(String key) { - Object obj = this.get(key); - if (obj == null) - return null; - return obj.toString(); - } - - /** - * A Simple Helper cast an Object to an Number - * - * @return a Number or null - */ - public Number getAsNumber(String key) { - Object obj = this.get(key); - if (obj == null) - return null; - if (obj instanceof Number) - return (Number)obj; - return Long.valueOf(obj.toString()); - } - - // /** - // * return a Key:value entry as stream - // */ - // public static String toString(String key, Object value) { - // return toString(key, value, JSONValue.COMPRESSION); - // } - - // /** - // * return a Key:value entry as stream - // */ - // public static String toString(String key, Object value, JSONStyle - // compression) { - // StringBuilder sb = new StringBuilder(); - // try { - // writeJSONKV(key, value, sb, compression); - // } catch (IOException e) { - // // can not append on a StringBuilder - // } - // return sb.toString(); - // } - - /** - * Allows creation of a JSONObject from a Map. After that, both the - * generated JSONObject and the Map can be modified independently. - */ - public JSONObject(Map map) { - super(map); - } - - public static void writeJSON(Map map, Appendable out) throws IOException { - writeJSON(map, out, JSONValue.COMPRESSION); - } - - /** - * Encode a map into JSON text and write it to out. If this map is also a - * JSONAware or JSONStreamAware, JSONAware or JSONStreamAware specific - * behaviours will be ignored at this top level. - * - * @see JSONValue#writeJSONString(Object, Appendable) - */ - public static void writeJSON(Map map, Appendable out, JSONStyle compression) - throws IOException { - if (map == null) { - out.append("null"); - return; - } - JsonWriter.JSONMapWriter.writeJSONString(map, out, compression); - } - - /** - * serialize Object as json to an stream - */ - public void writeJSONString(Appendable out) throws IOException { - writeJSON(this, out, JSONValue.COMPRESSION); - } - - /** - * serialize Object as json to an stream - */ - public void writeJSONString(Appendable out, JSONStyle compression) throws IOException { - writeJSON(this, out, compression); - } - - public void merge(Object o2) { - merge(this, o2); - } - - protected static JSONObject merge(JSONObject o1, Object o2) { - if (o2 == null) - return o1; - if (o2 instanceof JSONObject) - return merge(o1, (JSONObject) o2); - throw new RuntimeException("JSON megre can not merge JSONObject with " + o2.getClass()); - } - - private static JSONObject merge(JSONObject o1, JSONObject o2) { - if (o2 == null) - return o1; - for (String key : o1.keySet()) { - Object value1 = o1.get(key); - Object value2 = o2.get(key); - if (value2 == null) - continue; - if (value1 instanceof JSONArray) { - o1.put(key, merge((JSONArray) value1, value2)); - continue; - } - if (value1 instanceof JSONObject) { - o1.put(key, merge((JSONObject) value1, value2)); - continue; - } - if (value1.equals(value2)) - continue; - if (value1.getClass() .equals(value2.getClass())) - throw new RuntimeException("JSON merge can not merge two " + value1.getClass().getName() + " Object together"); - throw new RuntimeException("JSON merge can not merge " + value1.getClass().getName() + " with " + value2.getClass().getName()); - } - for (String key : o2.keySet()) { - if (o1.containsKey(key)) - continue; - o1.put(key, o2.get(key)); - } - return o1; - } - - protected static JSONArray merge(JSONArray o1, Object o2) { - if (o2 == null) - return o1; - if (o1 instanceof JSONArray) - return merge(o1, (JSONArray) o2); - o1.add(o2); - return o1; - } - - private static JSONArray merge(JSONArray o1, JSONArray o2) { - o1.addAll(o2); - return o1; - } - - public String toJSONString() { - return toJSONString(this, JSONValue.COMPRESSION); - } - - public String toJSONString(JSONStyle compression) { - return toJSONString(this, compression); - } - - public String toString(JSONStyle compression) { - return toJSONString(this, compression); - } - - public String toString() { - return toJSONString(this, JSONValue.COMPRESSION); - } -} diff --git a/maxkey-jose-jwt/src/main/java/net/minidev/json/JSONStreamAware.java b/maxkey-jose-jwt/src/main/java/net/minidev/json/JSONStreamAware.java deleted file mode 100644 index 493d99be2..000000000 --- a/maxkey-jose-jwt/src/main/java/net/minidev/json/JSONStreamAware.java +++ /dev/null @@ -1,31 +0,0 @@ -package net.minidev.json; - -/* - * Copyright 2011 JSON-SMART authors - * - * 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. - */ -import java.io.IOException; - -/** - * Beans that support customized output of JSON text to a writer shall implement - * this interface. - * - * @author FangYidong <fangyidong@yahoo.com.cn> - */ -public interface JSONStreamAware { - /** - * write JSON string to out. - */ - void writeJSONString(Appendable out) throws IOException; -} diff --git a/maxkey-jose-jwt/src/main/java/net/minidev/json/JSONStreamAwareEx.java b/maxkey-jose-jwt/src/main/java/net/minidev/json/JSONStreamAwareEx.java deleted file mode 100644 index d4482d39f..000000000 --- a/maxkey-jose-jwt/src/main/java/net/minidev/json/JSONStreamAwareEx.java +++ /dev/null @@ -1,31 +0,0 @@ -package net.minidev.json; - -/* - * Copyright 2011 JSON-SMART authors - * - * 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. - */ -import java.io.IOException; - -/** - * Beans that support customized output of JSON text to a writer shall implement - * this interface. - * - * @author FangYidong <fangyidong@yahoo.com.cn> - */ -public interface JSONStreamAwareEx extends JSONStreamAware { - /** - * write JSON string to out. - */ - void writeJSONString(Appendable out, JSONStyle compression) throws IOException; -} diff --git a/maxkey-jose-jwt/src/main/java/net/minidev/json/JSONStyle.java b/maxkey-jose-jwt/src/main/java/net/minidev/json/JSONStyle.java deleted file mode 100644 index a024c6d5f..000000000 --- a/maxkey-jose-jwt/src/main/java/net/minidev/json/JSONStyle.java +++ /dev/null @@ -1,212 +0,0 @@ -package net.minidev.json; - -/* - * Copyright 2011 JSON-SMART authors - * - * 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. - */ -import java.io.IOException; - -import net.minidev.json.JStylerObj.MustProtect; -import net.minidev.json.JStylerObj.StringProtector; - -/** - * JSONStyle object configure JSonSerializer reducing output size - * - * @author Uriel Chemouni <uchemouni@gmail.com> - */ -public class JSONStyle { - /** - * for advanced usage sample see - * - * #see net.minidev.json.test.TestCompressorFlags - */ - public final static int FLAG_PROTECT_KEYS = 1; - public final static int FLAG_PROTECT_4WEB = 2; - public final static int FLAG_PROTECT_VALUES = 4; - /** - * AGRESSIVE have no effect without PROTECT_KEYS or PROTECT_VALUE - * - * AGRESSIVE mode allows Json-smart to not protect String containing - * special chars - */ - public final static int FLAG_AGRESSIVE = 8; - /** - * @since 2.1 - */ - public final static int FLAG_IGNORE_NULL = 16; - - public final static JSONStyle NO_COMPRESS = new JSONStyle(0); - public final static JSONStyle MAX_COMPRESS = new JSONStyle(-1); - /** - * @since 1.0.9.1 - */ - public final static JSONStyle LT_COMPRESS = new JSONStyle(FLAG_PROTECT_4WEB); - - private boolean _protectKeys; - private boolean _protect4Web; - private boolean _protectValues; - private boolean _ignore_null; - - private MustProtect mpKey; - private MustProtect mpValue; - - private StringProtector esc; - - public JSONStyle(int FLAG) { - _protectKeys = (FLAG & FLAG_PROTECT_KEYS) == 0; - _protectValues = (FLAG & FLAG_PROTECT_VALUES) == 0; - _protect4Web = (FLAG & FLAG_PROTECT_4WEB) == 0; - _ignore_null = (FLAG & FLAG_IGNORE_NULL) > 0; - - MustProtect mp; - if ((FLAG & FLAG_AGRESSIVE) > 0) - mp = JStylerObj.MP_AGGRESIVE; - else - mp = JStylerObj.MP_SIMPLE; - - if (_protectValues) - mpValue = JStylerObj.MP_TRUE; - else - mpValue = mp; - - if (_protectKeys) - mpKey = JStylerObj.MP_TRUE; - else - mpKey = mp; - - if (_protect4Web) - esc = JStylerObj.ESCAPE4Web; - else - esc = JStylerObj.ESCAPE_LT; - } - - public JSONStyle() { - this(0); - } - - public boolean protectKeys() { - return _protectKeys; - } - - public boolean protectValues() { - return _protectValues; - } - - public boolean protect4Web() { - return _protect4Web; - } - - public boolean ignoreNull() { - return _ignore_null; - } - - public boolean indent() { - return false; - } - - public boolean mustProtectKey(String s) { - return mpKey.mustBeProtect(s); - } - - public boolean mustProtectValue(String s) { - return mpValue.mustBeProtect(s); - } - - public void writeString(Appendable out, String value) throws IOException { - if (!this.mustProtectValue(value)) - out.append(value); - else { - out.append('"'); - JSONValue.escape(value, out, this); - out.append('"'); - } - } - - public void escape(String s, Appendable out) { - esc.escape(s, out); - } - - /** - * begin Object - */ - public void objectStart(Appendable out) throws IOException { - out.append('{'); - } - - /** - * terminate Object - */ - public void objectStop(Appendable out) throws IOException { - out.append('}'); - } - - /** - * Start the first Obeject element - */ - public void objectFirstStart(Appendable out) throws IOException { - } - - /** - * Start a new Object element - */ - public void objectNext(Appendable out) throws IOException { - out.append(','); - } - - /** - * End Of Object element - */ - public void objectElmStop(Appendable out) throws IOException { - } - - /** - * end of Key in json Object - */ - public void objectEndOfKey(Appendable out) throws IOException { - out.append(':'); - } - - /** - * Array start - */ - public void arrayStart(Appendable out) throws IOException { - out.append('['); - } - - /** - * Array Done - */ - public void arrayStop(Appendable out) throws IOException { - out.append(']'); - } - - /** - * Start the first Array element - */ - public void arrayfirstObject(Appendable out) throws IOException { - } - - /** - * Start a new Array element - */ - public void arrayNextElm(Appendable out) throws IOException { - out.append(','); - } - - /** - * End of an Array element - */ - public void arrayObjectEnd(Appendable out) throws IOException { - } -} diff --git a/maxkey-jose-jwt/src/main/java/net/minidev/json/JSONUtil.java b/maxkey-jose-jwt/src/main/java/net/minidev/json/JSONUtil.java deleted file mode 100644 index 6f4f817c9..000000000 --- a/maxkey-jose-jwt/src/main/java/net/minidev/json/JSONUtil.java +++ /dev/null @@ -1,261 +0,0 @@ -package net.minidev.json; - -import java.lang.reflect.Field; -import java.lang.reflect.Method; - -import net.minidev.asm.FieldFilter; -import net.minidev.json.annotate.JsonIgnore; - -/* - * Copyright 2011 JSON-SMART authors - * - * 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. - */ -public class JSONUtil { - @SuppressWarnings({ "unchecked", "rawtypes" }) - public static Object convertToStrict(Object obj, Class dest) { - if (obj == null) - return null; - if (dest.isAssignableFrom(obj.getClass())) - return obj; - if (dest.isPrimitive()) { - if (dest == int.class) - if (obj instanceof Number) - return ((Number) obj).intValue(); - else - return Integer.valueOf(obj.toString()); - else if (dest == short.class) - if (obj instanceof Number) - return ((Number) obj).shortValue(); - else - return Short.valueOf(obj.toString()); - else if (dest == long.class) - if (obj instanceof Number) - return ((Number) obj).longValue(); - else - return Long.valueOf(obj.toString()); - else if (dest == byte.class) - if (obj instanceof Number) - return ((Number) obj).byteValue(); - else - return Byte.valueOf(obj.toString()); - else if (dest == float.class) - if (obj instanceof Number) - return ((Number) obj).floatValue(); - else - return Float.valueOf(obj.toString()); - else if (dest == double.class) - if (obj instanceof Number) - return ((Number) obj).doubleValue(); - else - return Double.valueOf(obj.toString()); - else if (dest == char.class) { - String asString = dest.toString(); - if (asString.length() > 0) - return Character.valueOf(asString.charAt(0)); - } else if (dest == boolean.class) { - return (Boolean) obj; - } - throw new RuntimeException("Primitive: Can not convert " + obj.getClass().getName() + " to " - + dest.getName()); - } else { - if (dest.isEnum()) - return Enum.valueOf((Class) dest, obj.toString()); - if (dest == Integer.class) - if (obj instanceof Number) - return Integer.valueOf(((Number) obj).intValue()); - else - return Integer.valueOf(obj.toString()); - if (dest == Long.class) - if (obj instanceof Number) - return Long.valueOf(((Number) obj).longValue()); - else - return Long.valueOf(obj.toString()); - if (dest == Short.class) - if (obj instanceof Number) - return Short.valueOf(((Number) obj).shortValue()); - else - return Short.valueOf(obj.toString()); - if (dest == Byte.class) - if (obj instanceof Number) - return Byte.valueOf(((Number) obj).byteValue()); - else - return Byte.valueOf(obj.toString()); - if (dest == Float.class) - if (obj instanceof Number) - return Float.valueOf(((Number) obj).floatValue()); - else - return Float.valueOf(obj.toString()); - if (dest == Double.class) - if (obj instanceof Number) - return Double.valueOf(((Number) obj).doubleValue()); - else - return Double.valueOf(obj.toString()); - if (dest == Character.class) { - String asString = dest.toString(); - if (asString.length() > 0) - return Character.valueOf(asString.charAt(0)); - } - throw new RuntimeException("Object: Can not Convert " + obj.getClass().getName() + " to " + dest.getName()); - } - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - public static Object convertToX(Object obj, Class dest) { - if (obj == null) - return null; - if (dest.isAssignableFrom(obj.getClass())) - return obj; - if (dest.isPrimitive()) { - if (obj instanceof Number) - return obj; - if (dest == int.class) - return Integer.valueOf(obj.toString()); - else if (dest == short.class) - return Short.valueOf(obj.toString()); - else if (dest == long.class) - return Long.valueOf(obj.toString()); - else if (dest == byte.class) - return Byte.valueOf(obj.toString()); - else if (dest == float.class) - return Float.valueOf(obj.toString()); - else if (dest == double.class) - return Double.valueOf(obj.toString()); - else if (dest == char.class) { - String asString = dest.toString(); - if (asString.length() > 0) - return Character.valueOf(asString.charAt(0)); - } else if (dest == boolean.class) { - return (Boolean) obj; - } - throw new RuntimeException("Primitive: Can not convert " + obj.getClass().getName() + " to " - + dest.getName()); - } else { - if (dest.isEnum()) - return Enum.valueOf((Class) dest, obj.toString()); - if (dest == Integer.class) - if (obj instanceof Number) - return Integer.valueOf(((Number) obj).intValue()); - else - return Integer.valueOf(obj.toString()); - if (dest == Long.class) - if (obj instanceof Number) - return Long.valueOf(((Number) obj).longValue()); - else - return Long.valueOf(obj.toString()); - if (dest == Short.class) - if (obj instanceof Number) - return Short.valueOf(((Number) obj).shortValue()); - else - return Short.valueOf(obj.toString()); - if (dest == Byte.class) - if (obj instanceof Number) - return Byte.valueOf(((Number) obj).byteValue()); - else - return Byte.valueOf(obj.toString()); - if (dest == Float.class) - if (obj instanceof Number) - return Float.valueOf(((Number) obj).floatValue()); - else - return Float.valueOf(obj.toString()); - if (dest == Double.class) - if (obj instanceof Number) - return Double.valueOf(((Number) obj).doubleValue()); - else - return Double.valueOf(obj.toString()); - if (dest == Character.class) { - String asString = dest.toString(); - if (asString.length() > 0) - return Character.valueOf(asString.charAt(0)); - } - throw new RuntimeException("Object: Can not Convert " + obj.getClass().getName() + " to " + dest.getName()); - } - } - - public final static JsonSmartFieldFilter JSON_SMART_FIELD_FILTER = new JsonSmartFieldFilter(); - - public static class JsonSmartFieldFilter implements FieldFilter { - - @Override - public boolean canUse(Field field) { - JsonIgnore ignore = field.getAnnotation(JsonIgnore.class); - if (ignore != null && ignore.value()) - return false; - return true; - } - - @Override - public boolean canUse(Field field, Method method) { - JsonIgnore ignore = method.getAnnotation(JsonIgnore.class); - if (ignore != null && ignore.value()) - return false; - return true; - } - - @Override - public boolean canRead(Field field) { - return true; - } - - @Override - public boolean canWrite(Field field) { - return true; - } - } - public static String getSetterName(String key) { - int len = key.length(); - char[] b = new char[len + 3]; - b[0] = 's'; - b[1] = 'e'; - b[2] = 't'; - char c = key.charAt(0); - if (c >= 'a' && c <= 'z') - c += 'A' - 'a'; - b[3] = c; - for (int i = 1; i < len; i++) { - b[i + 3] = key.charAt(i); - } - return new String(b); - } - - public static String getGetterName(String key) { - int len = key.length(); - char[] b = new char[len + 3]; - b[0] = 'g'; - b[1] = 'e'; - b[2] = 't'; - char c = key.charAt(0); - if (c >= 'a' && c <= 'z') - c += 'A' - 'a'; - b[3] = c; - for (int i = 1; i < len; i++) { - b[i + 3] = key.charAt(i); - } - return new String(b); - } - - public static String getIsName(String key) { - int len = key.length(); - char[] b = new char[len + 2]; - b[0] = 'i'; - b[1] = 's'; - char c = key.charAt(0); - if (c >= 'a' && c <= 'z') - c += 'A' - 'a'; - b[2] = c; - for (int i = 1; i < len; i++) { - b[i + 2] = key.charAt(i); - } - return new String(b); - } -} diff --git a/maxkey-jose-jwt/src/main/java/net/minidev/json/JSONValue.java b/maxkey-jose-jwt/src/main/java/net/minidev/json/JSONValue.java deleted file mode 100644 index 97b8aea32..000000000 --- a/maxkey-jose-jwt/src/main/java/net/minidev/json/JSONValue.java +++ /dev/null @@ -1,654 +0,0 @@ -package net.minidev.json; - -/* - * Copyright 2011 JSON-SMART authors - * - * 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. - */ -import static net.minidev.json.parser.JSONParser.DEFAULT_PERMISSIVE_MODE; -import static net.minidev.json.parser.JSONParser.MODE_RFC4627; - -import java.io.IOException; -import java.io.InputStream; -import java.io.Reader; -import java.util.List; -import java.util.Map; - -import net.minidev.json.parser.JSONParser; -import net.minidev.json.parser.ParseException; -import net.minidev.json.reader.JsonWriter; -import net.minidev.json.reader.JsonWriterI; -import net.minidev.json.writer.CompessorMapper; -import net.minidev.json.writer.FakeMapper; -import net.minidev.json.writer.JsonReader; -import net.minidev.json.writer.JsonReaderI; -import net.minidev.json.writer.UpdaterMapper; - -/** - * JSONValue is the helper class In most of case you should use those static - * methode to user JSON-smart - * - * - * The most commonly use methode are {@link #parse(String)} - * {@link #toJSONString(Object)} - * - * @author Uriel Chemouni <uchemouni@gmail.com> - */ -public class JSONValue { - /** - * Global default compression type - */ - public static JSONStyle COMPRESSION = JSONStyle.NO_COMPRESS; - - /** - * Parse JSON text into java object from the input source. Please use - * parseWithException() if you don't want to ignore the exception. if you - * want strict input check use parseStrict() - * - * @see JSONParser#parse(Reader) - * @see #parseWithException(Reader) - * - * @return Instance of the following: JSONObject, JSONArray, String, - * java.lang.Number, java.lang.Boolean, null - * - */ - public static Object parse(InputStream in) { - try { - return new JSONParser(DEFAULT_PERMISSIVE_MODE).parse(in); - } catch (Exception e) { - return null; - } - } - - /** - * Parse JSON text into java object from the input source. Please use - * parseWithException() if you don't want to ignore the exception. if you - * want strict input check use parseStrict() - * - * @see JSONParser#parse(Reader) - * @see #parseWithException(Reader) - * - * @return Instance of the following: JSONObject, JSONArray, String, - * java.lang.Number, java.lang.Boolean, null - * - */ - public static Object parse(byte[] in) { - try { - return new JSONParser(DEFAULT_PERMISSIVE_MODE).parse(in); - } catch (Exception e) { - return null; - } - } - - /** - * Parse input json as a mapTo class - * - * mapTo can be a bean - * - * @since 2.0 - */ - public static T parse(InputStream in, Class mapTo) { - try { - JSONParser p = new JSONParser(DEFAULT_PERMISSIVE_MODE); - return p.parse(in, defaultReader.getMapper(mapTo)); - } catch (Exception e) { - return null; - } - } - - /** - * Parse JSON text into java object from the input source. Please use - * parseWithException() if you don't want to ignore the exception. if you - * want strict input check use parseStrict() - * - * @see JSONParser#parse(Reader) - * @see #parseWithException(Reader) - * - * @return Instance of the following: JSONObject, JSONArray, String, - * java.lang.Number, java.lang.Boolean, null - * - */ - public static Object parse(Reader in) { - try { - return new JSONParser(DEFAULT_PERMISSIVE_MODE).parse(in); - } catch (Exception e) { - return null; - } - } - - /** - * Parse input json as a mapTo class - * - * mapTo can be a bean - * - * @since 2.0 - */ - public static T parse(byte[] in, Class mapTo) { - try { - JSONParser p = new JSONParser(DEFAULT_PERMISSIVE_MODE); - return p.parse(in, defaultReader.getMapper(mapTo)); - } catch (Exception e) { - return null; - } - } - - /** - * Parse input json as a mapTo class - * - * mapTo can be a bean - * - * @since 2.0 - */ - public static T parse(Reader in, Class mapTo) { - try { - JSONParser p = new JSONParser(DEFAULT_PERMISSIVE_MODE); - return p.parse(in, defaultReader.getMapper(mapTo)); - } catch (Exception e) { - return null; - } - } - - /** - * Parse input json as a mapTo class - * - * mapTo can be a bean - * - * @since 2.0 - */ - public static T parse(Reader in, T toUpdate) { - try { - JSONParser p = new JSONParser(DEFAULT_PERMISSIVE_MODE); - return p.parse(in, new UpdaterMapper(defaultReader, toUpdate)); - } catch (Exception e) { - return null; - } - } - - /** - * Parse input json as a mapTo class - * - * @since 2.0 - */ - protected static T parse(Reader in, JsonReaderI mapper) { - try { - JSONParser p = new JSONParser(DEFAULT_PERMISSIVE_MODE); - return p.parse(in, mapper); - } catch (Exception e) { - return null; - } - } - - /** - * Parse input json as a mapTo class - * - * mapTo can be a bean - * - * @since 2.0 - */ - public static T parse(String in, Class mapTo) { - try { - JSONParser p = new JSONParser(DEFAULT_PERMISSIVE_MODE); - return p.parse(in, defaultReader.getMapper(mapTo)); - } catch (Exception e) { - return null; - } - } - - /** - * Parse input json as a mapTo class - * - * mapTo can be a bean - * - * @since 2.0 - */ - public static T parse(InputStream in, T toUpdate) { - try { - JSONParser p = new JSONParser(DEFAULT_PERMISSIVE_MODE); - return p.parse(in, new UpdaterMapper(defaultReader, toUpdate)); - } catch (Exception e) { - return null; - } - } - - /** - * Parse input json as a mapTo class - * - * mapTo can be a bean - * - * @since 2.0 - */ - public static T parse(String in, T toUpdate) { - try { - JSONParser p = new JSONParser(DEFAULT_PERMISSIVE_MODE); - return p.parse(in, new UpdaterMapper(defaultReader, toUpdate)); - } catch (Exception e) { - return null; - } - } - - /** - * Parse input json as a mapTo class - * - * @since 2.0 - */ - protected static T parse(byte[] in, JsonReaderI mapper) { - try { - JSONParser p = new JSONParser(DEFAULT_PERMISSIVE_MODE); - return p.parse(in, mapper); - } catch (Exception e) { - return null; - } - } - - /** - * Parse input json as a mapTo class - * - * @since 2.0 - */ - protected static T parse(String in, JsonReaderI mapper) { - try { - JSONParser p = new JSONParser(DEFAULT_PERMISSIVE_MODE); - return p.parse(in, mapper); - } catch (Exception e) { - return null; - } - } - - /** - * Parse JSON text into java object from the input source. Please use - * parseWithException() if you don't want to ignore the exception. if you - * want strict input check use parseStrict() - * - * @see JSONParser#parse(String) - * @see #parseWithException(String) - * - * @return Instance of the following: JSONObject, JSONArray, String, - * java.lang.Number, java.lang.Boolean, null - * - */ - public static Object parse(String s) { - try { - return new JSONParser(DEFAULT_PERMISSIVE_MODE).parse(s); - } catch (Exception e) { - return null; - } - } - - /** - * Parse Json input to a java Object keeping element order - * - * @since 1.0.6.1 - */ - public static Object parseKeepingOrder(Reader in) { - try { - return new JSONParser(DEFAULT_PERMISSIVE_MODE).parse(in, defaultReader.DEFAULT_ORDERED); - } catch (Exception e) { - return null; - } - } - - /** - * Parse Json input to a java Object keeping element order - * - * @since 1.0.6.1 - */ - public static Object parseKeepingOrder(String in) { - try { - return new JSONParser(DEFAULT_PERMISSIVE_MODE).parse(in, defaultReader.DEFAULT_ORDERED); - } catch (Exception e) { - return null; - } - } - - /** - * Parse Json Using SAX event handler - * - * @since 1.0.6.2 - * @removed in 2.0 - */ - // public static void SAXParse(String input, ContentHandler handler) throws - // ParseException { - // } - - /** - * Parse Json Using SAX event handler - * - * @since 1.0.6.2 - * @removed in 2.0 - */ - // public static void SAXParse(Reader input, ContentHandler handler) throws - // ParseException, IOException { - // } - - /** - * Reformat Json input keeping element order - * - * @since 1.0.6.2 - * - * need to be rewrite in 2.0 - */ - public static String compress(String input, JSONStyle style) { - try { - StringBuilder sb = new StringBuilder(); - new JSONParser(DEFAULT_PERMISSIVE_MODE).parse(input, new CompessorMapper(defaultReader, sb, style)); - return sb.toString(); - } catch (Exception e) { - return input; - } - } - - /** - * Compress Json input keeping element order - * - * @since 1.0.6.1 - * - * need to be rewrite in 2.0 - */ - public static String compress(String input) { - return compress(input, JSONStyle.MAX_COMPRESS); - } - - /** - * Compress Json input keeping element order - * - * @since 1.0.6.1 - */ - public static String uncompress(String input) { - return compress(input, JSONStyle.NO_COMPRESS); - } - - /** - * Parse JSON text into java object from the input source. - * - * @see JSONParser - * - * @return Instance of the following: JSONObject, JSONArray, String, - * java.lang.Number, java.lang.Boolean, null - */ - public static Object parseWithException(byte[] in) throws IOException, ParseException { - return new JSONParser(DEFAULT_PERMISSIVE_MODE).parse(in, defaultReader.DEFAULT); - } - - /** - * Parse JSON text into java object from the input source. - * - * @see JSONParser - * - * @return Instance of the following: JSONObject, JSONArray, String, - * java.lang.Number, java.lang.Boolean, null - */ - public static Object parseWithException(InputStream in) throws IOException, ParseException { - return new JSONParser(DEFAULT_PERMISSIVE_MODE).parse(in, defaultReader.DEFAULT); - } - - /** - * Parse JSON text into java object from the input source. - * - * @see JSONParser - * - * @return Instance of the following: JSONObject, JSONArray, String, - * java.lang.Number, java.lang.Boolean, null - */ - public static Object parseWithException(Reader in) throws IOException, ParseException { - return new JSONParser(DEFAULT_PERMISSIVE_MODE).parse(in, defaultReader.DEFAULT); - } - - /** - * Parse JSON text into java object from the input source. - * - * @see JSONParser - * - * @return Instance of the following: JSONObject, JSONArray, String, - * java.lang.Number, java.lang.Boolean, null - */ - public static Object parseWithException(String s) throws ParseException { - return new JSONParser(DEFAULT_PERMISSIVE_MODE).parse(s, defaultReader.DEFAULT); - } - - /** - * Parse input json as a mapTo class - * - * mapTo can be a bean - * - * @since 2.0 - */ - public static T parseWithException(String in, Class mapTo) throws ParseException { - JSONParser p = new JSONParser(DEFAULT_PERMISSIVE_MODE); - return p.parse(in, defaultReader.getMapper(mapTo)); - } - - /** - * Parse valid RFC4627 JSON text into java object from the input source. - * - * @see JSONParser - * - * @return Instance of the following: JSONObject, JSONArray, String, - * java.lang.Number, java.lang.Boolean, null - */ - public static Object parseStrict(Reader in) throws IOException, ParseException { - return new JSONParser(MODE_RFC4627).parse(in, defaultReader.DEFAULT); - } - - /** - * Parse valid RFC4627 JSON text into java object from the input source. - * - * @see JSONParser - * - * @return Instance of the following: JSONObject, JSONArray, String, - * java.lang.Number, java.lang.Boolean, null - */ - public static Object parseStrict(String s) throws ParseException { - return new JSONParser(MODE_RFC4627).parse(s, defaultReader.DEFAULT); - } - - /** - * Check RFC4627 Json Syntax from input Reader - * - * @return if the input is valid - */ - public static boolean isValidJsonStrict(Reader in) throws IOException { - try { - new JSONParser(MODE_RFC4627).parse(in, FakeMapper.DEFAULT); - return true; - } catch (ParseException e) { - return false; - } - } - - /** - * check RFC4627 Json Syntax from input String - * - * @return if the input is valid - */ - public static boolean isValidJsonStrict(String s) { - try { - new JSONParser(MODE_RFC4627).parse(s, FakeMapper.DEFAULT); - return true; - } catch (ParseException e) { - return false; - } - } - - /** - * Check Json Syntax from input Reader - * - * @return if the input is valid - */ - public static boolean isValidJson(Reader in) throws IOException { - try { - new JSONParser(DEFAULT_PERMISSIVE_MODE).parse(in, FakeMapper.DEFAULT); - return true; - } catch (ParseException e) { - return false; - } - } - - /** - * Check Json Syntax from input String - * - * @return if the input is valid - */ - public static boolean isValidJson(String s) { - try { - new JSONParser(DEFAULT_PERMISSIVE_MODE).parse(s, FakeMapper.DEFAULT); - return true; - } catch (ParseException e) { - return false; - } - } - - /** - * Encode an object into JSON text and write it to out. - *

- * If this object is a Map or a List, and it's also a JSONStreamAware or a - * JSONAware, JSONStreamAware or JSONAware will be considered firstly. - *

- * - * @see JSONObject#writeJSON(Map, Appendable) - * @see JSONArray#writeJSONString(List, Appendable) - */ - public static void writeJSONString(Object value, Appendable out) throws IOException { - writeJSONString(value, out, COMPRESSION); - } - - /** - * Serialisation class Data - */ - public final static JsonWriter defaultWriter = new JsonWriter(); - /** - * deserialisation class Data - */ - public final static JsonReader defaultReader = new JsonReader(); - - /** - * remap field from java to json. - * @since 2.1.1 - */ - public static void remapField(Class type, String jsonFieldName, String javaFieldName) { - defaultReader.remapField(type, jsonFieldName, javaFieldName); - defaultWriter.remapField(type, javaFieldName, jsonFieldName); - } - - /** - * Register a serializer for a class. - */ - public static void registerWriter(Class cls, JsonWriterI writer) { - defaultWriter.registerWriter(writer, cls); - } - - /** - * register a deserializer for a class. - */ - public static void registerReader(Class type, JsonReaderI mapper) { - defaultReader.registerReader(type, mapper); - } - - /** - * Encode an object into JSON text and write it to out. - *

- * If this object is a Map or a List, and it's also a JSONStreamAware or a - * JSONAware, JSONStreamAware or JSONAware will be considered firstly. - *

- * - * @see JSONObject#writeJSON(Map, Appendable) - * @see JSONArray#writeJSONString(List, Appendable) - */ - @SuppressWarnings("unchecked") - public static void writeJSONString(Object value, Appendable out, JSONStyle compression) throws IOException { - if (value == null) { - out.append("null"); - return; - } - Class clz = value.getClass(); - @SuppressWarnings("rawtypes") - JsonWriterI w = defaultWriter.getWrite(clz); - if (w == null) { - if (clz.isArray()) - w = JsonWriter.arrayWriter; - else { - w = defaultWriter.getWriterByInterface(value.getClass()); - if (w == null) - w = JsonWriter.beansWriterASM; - // w = JsonWriter.beansWriter; - } - defaultWriter.registerWriter(w, clz); - } - w.writeJSONString(value, out, compression); - } - - /** - * Encode an object into JSON text and write it to out. - *

- * If this object is a Map or a List, and it's also a JSONStreamAware or a - * JSONAware, JSONStreamAware or JSONAware will be considered firstly. - *

- * - * @see JSONObject#writeJSON(Map, Appendable) - * @see JSONArray#writeJSONString(List, Appendable) - */ - public static String toJSONString(Object value) { - return toJSONString(value, COMPRESSION); - } - - /** - * Convert an object to JSON text. - *

- * If this object is a Map or a List, and it's also a JSONAware, JSONAware - * will be considered firstly. - *

- * DO NOT call this method from toJSONString() of a class that implements - * both JSONAware and Map or List with "this" as the parameter, use - * JSONObject.toJSONString(Map) or JSONArray.toJSONString(List) instead. - * - * @see JSONObject#toJSONString(Map) - * @see JSONArray#toJSONString(List) - * - * @return JSON text, or "null" if value is null or it's an NaN or an INF - * number. - */ - public static String toJSONString(Object value, JSONStyle compression) { - StringBuilder sb = new StringBuilder(); - try { - writeJSONString(value, sb, compression); - } catch (IOException e) { - // can not append on a StringBuilder - } - return sb.toString(); - } - - public static String escape(String s) { - return escape(s, COMPRESSION); - } - - /** - * Escape quotes, \, /, \r, \n, \b, \f, \t and other control characters - * (U+0000 through U+001F). - */ - public static String escape(String s, JSONStyle compression) { - if (s == null) - return null; - StringBuilder sb = new StringBuilder(); - compression.escape(s, sb); - return sb.toString(); - } - - public static void escape(String s, Appendable ap) { - escape(s, ap, COMPRESSION); - } - - public static void escape(String s, Appendable ap, JSONStyle compression) { - if (s == null) - return; - compression.escape(s, ap); - } -} diff --git a/maxkey-jose-jwt/src/main/java/net/minidev/json/JStylerObj.java b/maxkey-jose-jwt/src/main/java/net/minidev/json/JStylerObj.java deleted file mode 100644 index 0d69b8e63..000000000 --- a/maxkey-jose-jwt/src/main/java/net/minidev/json/JStylerObj.java +++ /dev/null @@ -1,329 +0,0 @@ -package net.minidev.json; - -/* - * Copyright 2011 JSON-SMART authors - * - * 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. - */ -import java.io.IOException; - -/** - * protected class used to stored Internal methods - * - * @author Uriel Chemouni <uchemouni@gmail.com> - */ -class JStylerObj { - - public final static MPSimple MP_SIMPLE = new MPSimple(); - public final static MPTrue MP_TRUE = new MPTrue(); - public final static MPAgressive MP_AGGRESIVE = new MPAgressive(); - - public final static EscapeLT ESCAPE_LT = new EscapeLT(); - public final static Escape4Web ESCAPE4Web = new Escape4Web(); - - public static interface MustProtect { - public boolean mustBeProtect(String s); - } - - private static class MPTrue implements MustProtect { - public boolean mustBeProtect(String s) { - return true; - } - } - - private static class MPSimple implements MustProtect { - /** - * can a String can be store without enclosing quotes. ie: should not - * contain any special json char - * - * @param s - * @return - */ - public boolean mustBeProtect(final String s) { - if (s == null) - return false; - int len = s.length(); - if (len == 0) - return true; - if (s.trim() != s) - return true; - - char ch = s.charAt(0); - if (ch >= '0' && ch <= '9' || ch == '-') - return true; - - for (int i = 0; i < len; i++) { - ch = s.charAt(i); - if (isSpace(ch)) - return true; - if (isSpecial(ch)) - return true; - if (isSpecialChar(ch)) - return true; - if (isUnicode(ch)) - return true; - } - // keyword check - if (isKeyword(s)) - return true; - return false; - } - } - - private static class MPAgressive implements MustProtect { - public boolean mustBeProtect(final String s) { - if (s == null) - return false; - int len = s.length(); - // protect empty String - if (len == 0) - return true; - - // protect trimable String - if (s.trim() != s) - return true; - - // json special char - char ch = s.charAt(0); - if (isSpecial(ch) || isUnicode(ch)) - return true; - - for (int i = 1; i < len; i++) { - ch = s.charAt(i); - if (isSpecialClose(ch) || isUnicode(ch)) - return true; - } - // keyWord must be protect - if (isKeyword(s)) - return true; - // Digit like text must be protect - ch = s.charAt(0); - // only test String if First Ch is a digit - if (ch >= '0' && ch <= '9' || ch == '-') { - int p = 1; - // skip first digits - for (; p < len; p++) { - ch = s.charAt(p); - if (ch < '0' || ch > '9') - break; - } - // int/long - if (p == len) - return true; - // Floating point - if (ch == '.') { - p++; - } - // Skip digits - for (; p < len; p++) { - ch = s.charAt(p); - if (ch < '0' || ch > '9') - break; - } - if (p == len) - return true; // can be read as an floating number - // Double - if (ch == 'E' || ch == 'e') { - p++; - if (p == len) // no power data not a digits - return false; - ch = s.charAt(p); - if (ch == '+' || ch == '-') { - p++; - ch = s.charAt(p); - } - } - if (p == len) // no power data => not a digit - return false; - - for (; p < len; p++) { - ch = s.charAt(p); - if (ch < '0' || ch > '9') - break; - } - // floating point With power of data. - if (p == len) - return true; - return false; - } - return false; - } - } - - public static boolean isSpace(char c) { - return (c == '\r' || c == '\n' || c == '\t' || c == ' '); - } - - public static boolean isSpecialChar(char c) { - return (c == '\b' || c == '\f' || c == '\n'); - } - - public static boolean isSpecialOpen(char c) { - return (c == '{' || c == '[' || c == ',' || c == ':'); - } - - public static boolean isSpecialClose(char c) { - return (c == '}' || c == ']' || c == ',' || c == ':'); - } - - public static boolean isSpecial(char c) { - return (c == '{' || c == '[' || c == ',' || c == '}' || c == ']' || c == ':' || c == '\'' || c == '"'); - } - - public static boolean isUnicode(char c) { - // ANSI controle char - return ((c >= '\u0000' && c <= '\u001F') || - // DEL or unicode ctrl - (c >= '\u007F' && c <= '\u009F') || - // '\u00A0' No-breakable space ? - // En Quad .. more - (c >= '\u2000' && c <= '\u20FF')); - } - - public static boolean isKeyword(String s) { - if (s.length() < 3) - return false; - char c = s.charAt(0); - if (c == 'n') - return s.equals("null"); - if (c == 't') - return s.equals("true"); - if (c == 'f') - return s.equals("false"); - if (c == 'N') - return s.equals("NaN"); - return false; - } - - public static interface StringProtector { - public void escape(String s, Appendable out); - } - - private static class EscapeLT implements StringProtector { - /** - * Escape special chars form String except / - * - * @param s - * - Must not be null. - * @param out - */ - public void escape(String s, Appendable out) { - try { - int len = s.length(); - for (int i = 0; i < len; i++) { - char ch = s.charAt(i); - switch (ch) { - case '"': - out.append("\\\""); - break; - case '\\': - out.append("\\\\"); - break; - case '\b': - out.append("\\b"); - break; - case '\f': - out.append("\\f"); - break; - case '\n': - out.append("\\n"); - break; - case '\r': - out.append("\\r"); - break; - case '\t': - out.append("\\t"); - break; - default: - // Reference: - // http://www.unicode.org/versions/Unicode5.1.0/ - if ((ch >= '\u0000' && ch <= '\u001F') || (ch >= '\u007F' && ch <= '\u009F') - || (ch >= '\u2000' && ch <= '\u20FF')) { - out.append("\\u"); - String hex = "0123456789ABCDEF"; - out.append(hex.charAt(ch >> 12 & 0x000F)); - out.append(hex.charAt(ch >> 8 & 0x000F)); - out.append(hex.charAt(ch >> 4 & 0x000F)); - out.append(hex.charAt(ch >> 0 & 0x000F)); - } else { - out.append(ch); - } - } - } - } catch (IOException e) { - throw new RuntimeException("Impossible Exeption"); - } - } - } - - private static class Escape4Web implements StringProtector { - - /** - * Escape special chars form String including / - * - * @param s - * - Must not be null. - * @param sb - */ - public void escape(String s, Appendable sb) { - try { - int len = s.length(); - for (int i = 0; i < len; i++) { - char ch = s.charAt(i); - switch (ch) { - case '"': - sb.append("\\\""); - break; - case '\\': - sb.append("\\\\"); - break; - case '\b': - sb.append("\\b"); - break; - case '\f': - sb.append("\\f"); - break; - case '\n': - sb.append("\\n"); - break; - case '\r': - sb.append("\\r"); - break; - case '\t': - sb.append("\\t"); - break; - case '/': - sb.append("\\/"); - break; - default: - // Reference: - // http://www.unicode.org/versions/Unicode5.1.0/ - if ((ch >= '\u0000' && ch <= '\u001F') || (ch >= '\u007F' && ch <= '\u009F') - || (ch >= '\u2000' && ch <= '\u20FF')) { - sb.append("\\u"); - String hex = "0123456789ABCDEF"; - sb.append(hex.charAt(ch >> 12 & 0x0F)); - sb.append(hex.charAt(ch >> 8 & 0x0F)); - sb.append(hex.charAt(ch >> 4 & 0x0F)); - sb.append(hex.charAt(ch >> 0 & 0x0F)); - } else { - sb.append(ch); - } - } - } - } catch (IOException e) { - throw new RuntimeException("Impossible Error"); - } - } - } -} diff --git a/maxkey-jose-jwt/src/main/java/net/minidev/json/annotate/JsonIgnore.java b/maxkey-jose-jwt/src/main/java/net/minidev/json/annotate/JsonIgnore.java deleted file mode 100644 index 77ad017fe..000000000 --- a/maxkey-jose-jwt/src/main/java/net/minidev/json/annotate/JsonIgnore.java +++ /dev/null @@ -1,31 +0,0 @@ -package net.minidev.json.annotate; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * block access to a field or to a getter or to a setter. - * - * If field and getter are annotate with @JsonIgnore the field will be Writable - * only - * - * - * If field and setter are annotate with @JsonIgnore the field will be Readable - * only - * - * - * If getter and setter are annotate with @JsonIgnore the field will be - * Read/Write using field if the field is public (default ) - * - * - * @author uriel - * - */ -@Target({ ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.FIELD }) -@Retention(RetentionPolicy.RUNTIME) -@JsonSmartAnnotation -public @interface JsonIgnore { - boolean value() default true; -} diff --git a/maxkey-jose-jwt/src/main/java/net/minidev/json/annotate/JsonSmartAnnotation.java b/maxkey-jose-jwt/src/main/java/net/minidev/json/annotate/JsonSmartAnnotation.java deleted file mode 100644 index ba21ea919..000000000 --- a/maxkey-jose-jwt/src/main/java/net/minidev/json/annotate/JsonSmartAnnotation.java +++ /dev/null @@ -1,19 +0,0 @@ -package net.minidev.json.annotate; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Jackson Annotation like - * - * @author uriel - * - */ - -@Target({ ElementType.ANNOTATION_TYPE }) -@Retention(RetentionPolicy.RUNTIME) -public @interface JsonSmartAnnotation { - -} diff --git a/maxkey-jose-jwt/src/main/java/net/minidev/json/parser/JSONParser.java b/maxkey-jose-jwt/src/main/java/net/minidev/json/parser/JSONParser.java deleted file mode 100644 index 4ec853114..000000000 --- a/maxkey-jose-jwt/src/main/java/net/minidev/json/parser/JSONParser.java +++ /dev/null @@ -1,281 +0,0 @@ -package net.minidev.json.parser; - -/* - * Copyright 2011 JSON-SMART authors - * - * 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. - */ -import java.io.InputStream; -import java.io.Reader; -import java.io.UnsupportedEncodingException; - -import net.minidev.json.JSONValue; -import net.minidev.json.writer.JsonReaderI; - -public class JSONParser { - /** - * allow simple quote as String quoting char - */ - public final static int ACCEPT_SIMPLE_QUOTE = 1; - /** - * allow non quoted test - */ - public final static int ACCEPT_NON_QUOTE = 2; - /** - * Parse NaN as Float.NaN - */ - public final static int ACCEPT_NAN = 4; - /** - * Ignore control char in input text. - */ - public final static int IGNORE_CONTROL_CHAR = 8; - /** - * Use int datatype to store number when it's possible. - * - * @since 1.0.7 - */ - public final static int USE_INTEGER_STORAGE = 16; - /** - * Throws exception on excessive 0 leading in digits - * - * @since 1.0.7 - */ - public final static int ACCEPT_LEADING_ZERO = 32; - /** - * Throws exception on useless comma in object and array - * - * @since 1.0.8 - */ - public final static int ACCEPT_USELESS_COMMA = 64; - /** - * Allow Json-smart to use Double or BigDecimal to store floating point - * value - * - * You may need to disable HI_PRECISION_FLOAT feature on 32bit to improve - * parsing performances. - * - * @since 1.0.9 - */ - public final static int USE_HI_PRECISION_FLOAT = 128; - /** - * If enabled json-smart will throws exception if datas are present after - * the end of the Json data. - * - * @since 1.0.9-2 - */ - public final static int ACCEPT_TAILLING_DATA = 256; - /** - * smart mode, fastest parsing mode. accept lots of non standard json syntax - * - * @since 2.0.1 - */ - public final static int ACCEPT_TAILLING_SPACE = 512; - /** - * smart mode, fastest parsing mode. accept lots of non standard json syntax - * - * @since 2.2.2 - */ - public final static int REJECT_127_CHAR = 1024; - - - /** - * smart mode, fastest parsing mode. accept lots of non standard json syntax - * - * @since 1.0.6 - */ - public final static int MODE_PERMISSIVE = -1; - /** - * strict RFC4627 mode. - * - * slower than PERMISIF MODE. - * - * @since 1.0.6 - */ - public final static int MODE_RFC4627 = USE_INTEGER_STORAGE | USE_HI_PRECISION_FLOAT | ACCEPT_TAILLING_SPACE; - /** - * Parse Object like json-simple - * - * Best for an iso-bug json-simple API port. - * - * @since 1.0.7 - */ - public final static int MODE_JSON_SIMPLE = ACCEPT_USELESS_COMMA | USE_HI_PRECISION_FLOAT | ACCEPT_TAILLING_DATA | ACCEPT_TAILLING_SPACE | REJECT_127_CHAR; - /** - * Strictest parsing mode - * - * @since 2.0.1 - */ - public final static int MODE_STRICTEST = USE_INTEGER_STORAGE | USE_HI_PRECISION_FLOAT | REJECT_127_CHAR; - /** - * Default json-smart processing mode - */ - public static int DEFAULT_PERMISSIVE_MODE = (System.getProperty("JSON_SMART_SIMPLE") != null) ? MODE_JSON_SIMPLE - : MODE_PERMISSIVE; - - /* - * internal fields - */ - private int mode; - - private JSONParserInputStream pBinStream; - private JSONParserByteArray pBytes; - private JSONParserReader pStream; - private JSONParserString pString; - - private JSONParserReader getPStream() { - if (pStream == null) - pStream = new JSONParserReader(mode); - return pStream; - } - - /** - * cached construcor - * - * @return instance of JSONParserInputStream - */ - private JSONParserInputStream getPBinStream() { - if (pBinStream == null) - pBinStream = new JSONParserInputStream(mode); - return pBinStream; - } - - /** - * cached construcor - * - * @return instance of JSONParserString - */ - private JSONParserString getPString() { - if (pString == null) - pString = new JSONParserString(mode); - return pString; - } - - /** - * cached construcor - * - * @return instance of JSONParserByteArray - */ - private JSONParserByteArray getPBytes() { - if (pBytes == null) - pBytes = new JSONParserByteArray(mode); - return pBytes; - } - - /** - * @deprecated prefer usage of new JSONParser(JSONParser.MODE_*) - */ - public JSONParser() { - this.mode = DEFAULT_PERMISSIVE_MODE; - } - - public JSONParser(int permissifMode) { - this.mode = permissifMode; - } - - /** - * use to return Primitive Type, or String, Or JsonObject or JsonArray - * generated by a ContainerFactory - */ - public Object parse(byte[] in) throws ParseException { - return getPBytes().parse(in); - } - - /** - * use to return Primitive Type, or String, Or JsonObject or JsonArray - * generated by a ContainerFactory - */ - public T parse(byte[] in, JsonReaderI mapper) throws ParseException { - return getPBytes().parse(in, mapper); - } - - /** - * use to return Primitive Type, or String, Or JsonObject or JsonArray - * generated by a ContainerFactory - */ - public T parse(byte[] in, Class mapTo) throws ParseException { - return getPBytes().parse(in, JSONValue.defaultReader.getMapper(mapTo)); - } - - /** - * use to return Primitive Type, or String, Or JsonObject or JsonArray - * generated by a ContainerFactory - * @throws UnsupportedEncodingException - */ - public Object parse(InputStream in) throws ParseException, UnsupportedEncodingException { - return getPBinStream().parse(in); - } - - /** - * use to return Primitive Type, or String, Or JsonObject or JsonArray - * generated by a ContainerFactory - */ - public T parse(InputStream in, JsonReaderI mapper) throws ParseException, UnsupportedEncodingException { - return getPBinStream().parse(in, mapper); - } - - /** - * use to return Primitive Type, or String, Or JsonObject or JsonArray - * generated by a ContainerFactory - */ - public T parse(InputStream in, Class mapTo) throws ParseException, UnsupportedEncodingException { - return getPBinStream().parse(in, JSONValue.defaultReader.getMapper(mapTo)); - } - - /** - * use to return Primitive Type, or String, Or JsonObject or JsonArray - * generated by a ContainerFactory - */ - public Object parse(Reader in) throws ParseException { - return getPStream().parse(in); - } - - /** - * use to return Primitive Type, or String, Or JsonObject or JsonArray - * generated by a ContainerFactory - */ - public T parse(Reader in, JsonReaderI mapper) throws ParseException { - return getPStream().parse(in, mapper); - } - - /** - * use to return Primitive Type, or String, Or JsonObject or JsonArray - * generated by a ContainerFactory - */ - public T parse(Reader in, Class mapTo) throws ParseException { - return getPStream().parse(in, JSONValue.defaultReader.getMapper(mapTo)); - } - - /** - * use to return Primitive Type, or String, Or JsonObject or JsonArray - * generated by a ContainerFactory - */ - public Object parse(String in) throws ParseException { - return getPString().parse(in); - } - - /** - * use to return Primitive Type, or String, Or JsonObject or JsonArray - * generated by a ContainerFactory - */ - public T parse(String in, JsonReaderI mapper) throws ParseException { - return getPString().parse(in, mapper); - } - - /** - * use to return Primitive Type, or String, Or JsonObject or JsonArray - * generated by a ContainerFactory - */ - public T parse(String in, Class mapTo) throws ParseException { - return getPString().parse(in, JSONValue.defaultReader.getMapper(mapTo)); - } -} diff --git a/maxkey-jose-jwt/src/main/java/net/minidev/json/parser/JSONParserBase.java b/maxkey-jose-jwt/src/main/java/net/minidev/json/parser/JSONParserBase.java deleted file mode 100644 index a5dd024c2..000000000 --- a/maxkey-jose-jwt/src/main/java/net/minidev/json/parser/JSONParserBase.java +++ /dev/null @@ -1,763 +0,0 @@ -package net.minidev.json.parser; - -/* - * Copyright 2011 JSON-SMART authors - * - * 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. - */ -import static net.minidev.json.parser.ParseException.ERROR_UNEXPECTED_CHAR; -import static net.minidev.json.parser.ParseException.ERROR_UNEXPECTED_EOF; -import static net.minidev.json.parser.ParseException.ERROR_UNEXPECTED_LEADING_0; -import static net.minidev.json.parser.ParseException.ERROR_UNEXPECTED_TOKEN; -import static net.minidev.json.parser.ParseException.ERROR_UNEXPECTED_UNICODE; - -import java.io.IOException; -import java.math.BigDecimal; -import java.math.BigInteger; - -import net.minidev.json.writer.JsonReader; -import net.minidev.json.writer.JsonReaderI; - -/** - * JSONParserBase is the common code between {@link JSONParserString} and - * {@link JSONParserReader} - * - * @see JSONParserMemory - * @see JSONParserStream - * - * @author Uriel Chemouni <uchemouni@gmail.com> - */ -abstract class JSONParserBase { - protected char c; - JsonReader base; - public final static byte EOI = 0x1A; - protected static final char MAX_STOP = 126; // '}' -> 125 - private String lastKey; - - protected static boolean[] stopAll = new boolean[MAX_STOP]; - protected static boolean[] stopArray = new boolean[MAX_STOP]; - protected static boolean[] stopKey = new boolean[MAX_STOP]; - protected static boolean[] stopValue = new boolean[MAX_STOP]; - protected static boolean[] stopX = new boolean[MAX_STOP]; - - static { - stopKey[':'] = stopKey[EOI] = true; - stopValue[','] = stopValue['}'] = stopValue[EOI] = true; - stopArray[','] = stopArray[']'] = stopArray[EOI] = true; - stopX[EOI] = true; - stopAll[','] = stopAll[':'] = true; - stopAll[']'] = stopAll['}'] = stopAll[EOI] = true; - } - - /* - * End of static declaration - */ - // - // - protected final MSB sb = new MSB(15); - protected Object xo; - protected String xs; - protected int pos; - - /* - * Parsing flags - */ - protected final boolean acceptLeadinZero; - protected final boolean acceptNaN; - protected final boolean acceptNonQuote; - protected final boolean acceptSimpleQuote; - protected final boolean acceptUselessComma; - protected final boolean checkTaillingData; - protected final boolean checkTaillingSpace; - protected final boolean ignoreControlChar; - protected final boolean useHiPrecisionFloat; - protected final boolean useIntegerStorage; - protected final boolean reject127; - - public JSONParserBase(int permissiveMode) { - this.acceptNaN = (permissiveMode & JSONParser.ACCEPT_NAN) > 0; - this.acceptNonQuote = (permissiveMode & JSONParser.ACCEPT_NON_QUOTE) > 0; - this.acceptSimpleQuote = (permissiveMode & JSONParser.ACCEPT_SIMPLE_QUOTE) > 0; - this.ignoreControlChar = (permissiveMode & JSONParser.IGNORE_CONTROL_CHAR) > 0; - this.useIntegerStorage = (permissiveMode & JSONParser.USE_INTEGER_STORAGE) > 0; - this.acceptLeadinZero = (permissiveMode & JSONParser.ACCEPT_LEADING_ZERO) > 0; - this.acceptUselessComma = (permissiveMode & JSONParser.ACCEPT_USELESS_COMMA) > 0; - this.useHiPrecisionFloat = (permissiveMode & JSONParser.USE_HI_PRECISION_FLOAT) > 0; - this.checkTaillingData = (permissiveMode & (JSONParser.ACCEPT_TAILLING_DATA | JSONParser.ACCEPT_TAILLING_SPACE)) != (JSONParser.ACCEPT_TAILLING_DATA | JSONParser.ACCEPT_TAILLING_SPACE); - this.checkTaillingSpace = (permissiveMode & JSONParser.ACCEPT_TAILLING_SPACE) == 0; - this.reject127 = (permissiveMode & JSONParser.REJECT_127_CHAR) > 0; - } - - public void checkControleChar() throws ParseException { - if (ignoreControlChar) - return; - int l = xs.length(); - for (int i = 0; i < l; i++) { - char c = xs.charAt(i); - if (c < 0) - continue; - if (c <= 31) - throw new ParseException(pos + i, ParseException.ERROR_UNEXPECTED_CHAR, c); - if (c == 127) { - if (reject127) - throw new ParseException(pos + i, ParseException.ERROR_UNEXPECTED_CHAR, c); - } - } - } - - public void checkLeadinZero() throws ParseException { - int len = xs.length(); - if (len == 1) - return; - if (len == 2) { - if (xs.equals("00")) - throw new ParseException(pos, ERROR_UNEXPECTED_LEADING_0, xs); - return; - } - char c1 = xs.charAt(0); - char c2 = xs.charAt(1); - if (c1 == '-') { - char c3 = xs.charAt(2); - if (c2 == '0' && c3 >= '0' && c3 <= '9') - throw new ParseException(pos, ERROR_UNEXPECTED_LEADING_0, xs); - return; - } - if (c1 == '0' && c2 >= '0' && c2 <= '9') - throw new ParseException(pos, ERROR_UNEXPECTED_LEADING_0, xs); - } - - protected Number extractFloat() throws ParseException { - if (!acceptLeadinZero) - checkLeadinZero(); - if (!useHiPrecisionFloat) - return Float.parseFloat(xs); - if (xs.length() > 18) // follow JSonIJ parsing method - return new BigDecimal(xs); - return Double.parseDouble(xs); - } - - /** - * use to return Primitive Type, or String, Or JsonObject or JsonArray - * generated by a ContainerFactory - */ - protected T parse(JsonReaderI mapper) throws ParseException { - this.pos = -1; - T result; - try { - read(); - result = readFirst(mapper); - if (checkTaillingData) { - if (!checkTaillingSpace) - skipSpace(); - if (c != EOI) - throw new ParseException(pos - 1, ERROR_UNEXPECTED_TOKEN, c); - } - } catch (IOException e) { - throw new ParseException(pos, e); - } - xs = null; - xo = null; - return result; - } - - protected Number parseNumber(String s) throws ParseException { - // pos - int p = 0; - // len - int l = s.length(); - // max pos long base 10 len - int max = 19; - boolean neg; - - if (s.charAt(0) == '-') { - p++; - max++; - neg = true; - if (!acceptLeadinZero && l >= 3 && s.charAt(1) == '0') - throw new ParseException(pos, ERROR_UNEXPECTED_LEADING_0, s); - } else { - neg = false; - if (!acceptLeadinZero && l >= 2 && s.charAt(0) == '0') - throw new ParseException(pos, ERROR_UNEXPECTED_LEADING_0, s); - } - - boolean mustCheck; - if (l < max) { - max = l; - mustCheck = false; - } else if (l > max) { - return new BigInteger(s, 10); - } else { - max = l - 1; - mustCheck = true; - } - - long r = 0; - while (p < max) { - r = (r * 10L) + ('0' - s.charAt(p++)); - } - if (mustCheck) { - boolean isBig; - if (r > -922337203685477580L) { - isBig = false; - } else if (r < -922337203685477580L) { - isBig = true; - } else { - if (neg) - isBig = (s.charAt(p) > '8'); - else - isBig = (s.charAt(p) > '7'); - } - if (isBig) - return new BigInteger(s, 10); - r = r * 10L + ('0' - s.charAt(p)); - } - if (neg) { - if (this.useIntegerStorage && r >= Integer.MIN_VALUE) - return (int) r; - return r; - } - r = -r; - if (this.useIntegerStorage && r <= Integer.MAX_VALUE) - return (int) r; - return r; - } - - abstract protected void read() throws IOException; - - protected T readArray(JsonReaderI mapper) throws ParseException, IOException { - Object current = mapper.createArray(); - if (c != '[') - throw new RuntimeException("Internal Error"); - read(); - boolean needData = false; - // special case needData is false and can close is true - if (c == ',' && !acceptUselessComma) - throw new ParseException(pos, ERROR_UNEXPECTED_CHAR, (char) c); - for (;;) { - switch (c) { - case ' ': - case '\r': - case '\n': - case '\t': - read(); - continue; - case ']': - if (needData && !acceptUselessComma) - throw new ParseException(pos, ERROR_UNEXPECTED_CHAR, (char) c); - read(); /* unstack */ - // - return mapper.convert(current); - case ':': - case '}': - throw new ParseException(pos, ERROR_UNEXPECTED_CHAR, (char) c); - case ',': - if (needData && !acceptUselessComma) - throw new ParseException(pos, ERROR_UNEXPECTED_CHAR, (char) c); - read(); - needData = true; - continue; - case EOI: - throw new ParseException(pos - 1, ERROR_UNEXPECTED_EOF, "EOF"); - default: - mapper.addValue(current, readMain(mapper, stopArray)); - needData = false; - continue; - } - } - } - - /** - * use to return Primitive Type, or String, Or JsonObject or JsonArray - * generated by a ContainerFactory - */ - protected T readFirst(JsonReaderI mapper) throws ParseException, IOException { - for (;;) { - switch (c) { - // skip spaces - case ' ': - case '\r': - case '\n': - case '\t': - read(); - continue; - // invalid stats - case ':': - case '}': - case ']': - throw new ParseException(pos, ERROR_UNEXPECTED_CHAR, c); - // start object - case '{': - return readObject(mapper); - // start Array - case '[': - return readArray(mapper); - // start string - case '"': - case '\'': - readString(); - // - return mapper.convert(xs); - // string or null - case 'n': - readNQString(stopX); - if ("null".equals(xs)) { - // - return null; - } - if (!acceptNonQuote) - throw new ParseException(pos, ERROR_UNEXPECTED_TOKEN, xs); - // - return mapper.convert(xs); - // string or false - case 'f': - readNQString(stopX); - if ("false".equals(xs)) { - // - return mapper.convert(Boolean.FALSE); - } - if (!acceptNonQuote) - throw new ParseException(pos, ERROR_UNEXPECTED_TOKEN, xs); - // - return mapper.convert(xs); - // string or true - case 't': - readNQString(stopX); - if ("true".equals(xs)) { - // - return mapper.convert(Boolean.TRUE); - } - if (!acceptNonQuote) - throw new ParseException(pos, ERROR_UNEXPECTED_TOKEN, xs); - // - return mapper.convert(xs); - // string or NaN - case 'N': - readNQString(stopX); - if (!acceptNaN) - throw new ParseException(pos, ERROR_UNEXPECTED_TOKEN, xs); - if ("NaN".equals(xs)) { - // - return mapper.convert(Float.valueOf(Float.NaN)); - } - if (!acceptNonQuote) - throw new ParseException(pos, ERROR_UNEXPECTED_TOKEN, xs); - // - return mapper.convert(xs); - // digits - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - case '-': - xo = readNumber(stopX); - // - return mapper.convert(xo); - default: - readNQString(stopX); - if (!acceptNonQuote) - throw new ParseException(pos, ERROR_UNEXPECTED_TOKEN, xs); - // - return mapper.convert(xs); - } - } - } - - /** - * use to return Primitive Type, or String, Or JsonObject or JsonArray - * generated by a ContainerFactory - */ - protected Object readMain(JsonReaderI mapper, boolean stop[]) throws ParseException, IOException { - for (;;) { - switch (c) { - // skip spaces - case ' ': - case '\r': - case '\n': - case '\t': - read(); - continue; - // invalid stats - case ':': - case '}': - case ']': - throw new ParseException(pos, ERROR_UNEXPECTED_CHAR, c); - // start object - case '{': - return readObject(mapper.startObject(lastKey)); - // start Array - case '[': - return readArray(mapper.startArray(lastKey)); - // start string - case '"': - case '\'': - readString(); - // - return xs; - // string or null - case 'n': - readNQString(stop); - if ("null".equals(xs)) { - // - return null; - } - if (!acceptNonQuote) - throw new ParseException(pos, ERROR_UNEXPECTED_TOKEN, xs); - // - return xs; - // string or false - case 'f': - readNQString(stop); - if ("false".equals(xs)) { - // - return Boolean.FALSE; - } - if (!acceptNonQuote) - throw new ParseException(pos, ERROR_UNEXPECTED_TOKEN, xs); - // - return xs; - // string or true - case 't': - readNQString(stop); - if ("true".equals(xs)) { - // - return Boolean.TRUE; - } - if (!acceptNonQuote) - throw new ParseException(pos, ERROR_UNEXPECTED_TOKEN, xs); - // - return xs; - // string or NaN - case 'N': - readNQString(stop); - if (!acceptNaN) - throw new ParseException(pos, ERROR_UNEXPECTED_TOKEN, xs); - if ("NaN".equals(xs)) { - // - return Float.valueOf(Float.NaN); - } - if (!acceptNonQuote) - throw new ParseException(pos, ERROR_UNEXPECTED_TOKEN, xs); - // - return xs; - // digits - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - case '-': - // - // - return readNumber(stop); - default: - readNQString(stop); - if (!acceptNonQuote) - throw new ParseException(pos, ERROR_UNEXPECTED_TOKEN, xs); - // - return xs; - } - } - } - - abstract protected void readNoEnd() throws ParseException, IOException; - - abstract protected void readNQString(boolean[] stop) throws IOException; - - abstract protected Object readNumber(boolean[] stop) throws ParseException, IOException; - - protected T readObject(JsonReaderI mapper) throws ParseException, IOException { - // - if (c != '{') - throw new RuntimeException("Internal Error"); - Object current = mapper.createObject(); - boolean needData = false; - boolean acceptData = true; - for (;;) { - read(); - switch (c) { - case ' ': - case '\r': - case '\t': - case '\n': - continue; - case ':': - case ']': - case '[': - case '{': - throw new ParseException(pos, ERROR_UNEXPECTED_CHAR, c); - case '}': - if (needData && !acceptUselessComma) - throw new ParseException(pos, ERROR_UNEXPECTED_CHAR, (char) c); - read(); /* unstack */ - // - return mapper.convert(current); - case ',': - if (needData && !acceptUselessComma) - throw new ParseException(pos, ERROR_UNEXPECTED_CHAR, (char) c); - acceptData = needData = true; - continue; - case '"': - case '\'': - default: - // int keyStart = pos; - if (c == '\"' || c == '\'') { - readString(); - } else { - readNQString(stopKey); - if (!acceptNonQuote) - throw new ParseException(pos, ERROR_UNEXPECTED_TOKEN, xs); - } - String key = xs; - if (!acceptData) - throw new ParseException(pos, ERROR_UNEXPECTED_TOKEN, key); - - // Skip spaces - skipSpace(); - - if (c != ':') { - if (c == EOI) - throw new ParseException(pos - 1, ERROR_UNEXPECTED_EOF, null); - throw new ParseException(pos - 1, ERROR_UNEXPECTED_CHAR, c); - } - readNoEnd(); /* skip : */ - lastKey = key; - Object value = readMain(mapper, stopValue); - mapper.setValue(current, key, value); - lastKey = null; - - // Object duplicate = obj.put(key, readMain(stopValue)); - // if (duplicate != null) - // throw new ParseException(keyStart, ERROR_UNEXPECTED_DUPLICATE_KEY, key); - // handler.endObjectEntry(); - // should loop skipping read step - skipSpace(); - if (c == '}') { - read(); /* unstack */ - // - return mapper.convert(current); - } - if (c == EOI) // Fixed on 18/10/2011 reported by vladimir - throw new ParseException(pos - 1, ERROR_UNEXPECTED_EOF, null); - // if c==, continue - if (c == ',') - acceptData = needData = true; - else - throw new ParseException(pos - 1, ERROR_UNEXPECTED_TOKEN, c); - // acceptData = needData = false; - } - } - } - - /** - * store and read - */ - abstract void readS() throws IOException; - - abstract protected void readString() throws ParseException, IOException; - - protected void readString2() throws ParseException, IOException { - /* assert (c == '\"' || c == '\'') */ - char sep = c; - for (;;) { - read(); - switch (c) { - case EOI: - throw new ParseException(pos - 1, ERROR_UNEXPECTED_EOF, null); - case '"': - case '\'': - if (sep == c) { - read(); - xs = sb.toString(); - return; - } - sb.append(c); - break; - case '\\': - read(); - switch (c) { - case 't': - sb.append('\t'); - break; - case 'n': - sb.append('\n'); - break; - case 'r': - sb.append('\r'); - break; - case 'f': - sb.append('\f'); - break; - case 'b': - sb.append('\b'); - break; - case '\\': - sb.append('\\'); - break; - case '/': - sb.append('/'); - break; - case '\'': - sb.append('\''); - break; - case '"': - sb.append('"'); - break; - case 'u': - sb.append(readUnicode(4)); - break; - case 'x': - sb.append(readUnicode(2)); - break; - default: - break; - } - break; - case '\0': // end of string - case (char) 1: // Start of heading - case (char) 2: // Start of text - case (char) 3: // End of text - case (char) 4: // End of transmission - case (char) 5: // Enquiry - case (char) 6: // Acknowledge - case (char) 7: // Bell - case '\b': // 8: backSpase - case '\t': // 9: horizontal tab - case '\n': // 10: new line - case (char) 11: // Vertical tab - case '\f': // 12: form feed - case '\r': // 13: return carriage - case (char) 14: // Shift Out, alternate character set - case (char) 15: // Shift In, resume defaultn character set - case (char) 16: // Data link escape - case (char) 17: // XON, with XOFF to pause listings; - case (char) 18: // Device control 2, block-mode flow control - case (char) 19: // XOFF, with XON is TERM=18 flow control - case (char) 20: // Device control 4 - case (char) 21: // Negative acknowledge - case (char) 22: // Synchronous idle - case (char) 23: // End transmission block, not the same as EOT - case (char) 24: // Cancel line, MPE echoes !!! - case (char) 25: // End of medium, Control-Y interrupt - // case (char) 26: // Substitute == EOI - case (char) 27: // escape - case (char) 28: // File Separator - case (char) 29: // Group Separator - case (char) 30: // Record Separator - case (char) 31: // Unit Separator - if (ignoreControlChar) - continue; - throw new ParseException(pos, ERROR_UNEXPECTED_CHAR, c); - case (char) 127: // del - if (ignoreControlChar) - continue; - if (reject127) - throw new ParseException(pos, ERROR_UNEXPECTED_CHAR, c); - default: - sb.append(c); - } - } - } - - protected char readUnicode(int totalChars) throws ParseException, IOException { - int value = 0; - for (int i = 0; i < totalChars; i++) { - value = value * 16; - read(); - if (c <= '9' && c >= '0') - value += c - '0'; - else if (c <= 'F' && c >= 'A') - value += (c - 'A') + 10; - else if (c >= 'a' && c <= 'f') - value += (c - 'a') + 10; - else if (c == EOI) - throw new ParseException(pos, ERROR_UNEXPECTED_EOF, "EOF"); - else - throw new ParseException(pos, ERROR_UNEXPECTED_UNICODE, c); - } - return (char) value; - } - - protected void skipDigits() throws IOException { - for (;;) { - if (c < '0' || c > '9') - return; - readS(); - } - } - - protected void skipNQString(boolean[] stop) throws IOException { - for (;;) { - if ((c == EOI) || (c >= 0 && c < MAX_STOP && stop[c])) - return; - readS(); - } - } - - protected void skipSpace() throws IOException { - for (;;) { - if (c > ' ' || c == EOI) - return; - readS(); - } - } - - public static class MSB { - char b[]; - int p; - - public MSB(int size) { - b = new char[size]; - p = -1; - } - - public void append(char c) { - p++; - if (b.length <= p) { - char[] t = new char[b.length * 2 + 1]; - System.arraycopy(b, 0, t, 0, b.length); - b = t; - } - b[p] = c; - } - - public void append(int c) { - p++; - if (b.length <= p) { - char[] t = new char[b.length * 2 + 1]; - System.arraycopy(b, 0, t, 0, b.length); - b = t; - } - b[p] = (char) c; - } - - public String toString() { - return new String(b, 0, p + 1); - } - - public void clear() { - p = -1; - } - } -} diff --git a/maxkey-jose-jwt/src/main/java/net/minidev/json/parser/JSONParserByteArray.java b/maxkey-jose-jwt/src/main/java/net/minidev/json/parser/JSONParserByteArray.java deleted file mode 100644 index 80f587e26..000000000 --- a/maxkey-jose-jwt/src/main/java/net/minidev/json/parser/JSONParserByteArray.java +++ /dev/null @@ -1,111 +0,0 @@ -package net.minidev.json.parser; - -/* - * Copyright 2011 JSON-SMART authors - * - * 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. - */ -import static net.minidev.json.parser.ParseException.ERROR_UNEXPECTED_EOF; -import net.minidev.json.JSONValue; -import net.minidev.json.writer.JsonReaderI; - -/** - * Parser for JSON text. Please note that JSONParser is NOT thread-safe. - * - * @author Uriel Chemouni <uchemouni@gmail.com> - */ -class JSONParserByteArray extends JSONParserMemory { - private byte[] in; - - public JSONParserByteArray(int permissiveMode) { - super(permissiveMode); - } - - /** - * use to return Primitive Type, or String, Or JsonObject or JsonArray - * generated by a ContainerFactory - */ - public Object parse(byte[] in) throws ParseException { - return parse(in, JSONValue.defaultReader.DEFAULT); - } - - // - // - // - // - // - // - // - - /** - * use to return Primitive Type, or String, Or JsonObject or JsonArray - * generated by a ContainerFactory - */ - public T parse(byte[] in, JsonReaderI mapper) throws ParseException { - this.base = mapper.base; - this.in = in; - this.len = in.length; - return parse(mapper); - } - - protected void extractString(int beginIndex, int endIndex) { - xs = new String(in, beginIndex, endIndex - beginIndex); - } - - protected void extractStringTrim(int start, int stop) { - byte[] val = this.in; /* avoid getfield opcode */ - - while ((start < stop) && (val[start] <= ' ')) { - start++; - } - while ((start < stop) && (val[stop - 1] <= ' ')) { - stop--; - } - xs = new String(in, start, stop - start); - } - - protected int indexOf(char c, int pos) { - for (int i = pos; pos < len; i++) - if (in[i] == (byte) c) - return i; - return -1; - } - - protected void read() { - if (++pos >= len) - this.c = EOI; - else - this.c = (char) in[pos]; - } - - /** - * Same as read() in memory parsing - */ - protected void readS() { - if (++pos >= len) - this.c = EOI; - else - this.c = (char) in[pos]; - } - - /** - * read data can not be EOI - */ - protected void readNoEnd() throws ParseException { - if (++pos >= len) { - this.c = EOI; - throw new ParseException(pos - 1, ERROR_UNEXPECTED_EOF, "EOF"); - } else - this.c = (char) in[pos]; - } -} diff --git a/maxkey-jose-jwt/src/main/java/net/minidev/json/parser/JSONParserInputStream.java b/maxkey-jose-jwt/src/main/java/net/minidev/json/parser/JSONParserInputStream.java deleted file mode 100644 index 1c88f4ddf..000000000 --- a/maxkey-jose-jwt/src/main/java/net/minidev/json/parser/JSONParserInputStream.java +++ /dev/null @@ -1,64 +0,0 @@ -package net.minidev.json.parser; - -/* - * Copyright 2011 JSON-SMART authors - * - * 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. - */ -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.UnsupportedEncodingException; - -import net.minidev.json.writer.JsonReaderI; - -/** - * Parser for JSON text. Please note that JSONParser is NOT thread-safe. - * - * @author Uriel Chemouni <uchemouni@gmail.com> - */ -class JSONParserInputStream extends JSONParserReader { - - // len - public JSONParserInputStream(int permissiveMode) { - super(permissiveMode); - } - - /** - * use to return Primitive Type, or String, Or JsonObject or JsonArray - * generated by a ContainerFactory - * @throws UnsupportedEncodingException - */ - public Object parse(InputStream in) throws ParseException, UnsupportedEncodingException { - InputStreamReader i2 = new InputStreamReader(in, "utf8"); - return super.parse(i2); - } - - /** - * use to return Primitive Type, or String, Or JsonObject or JsonArray - * generated by a ContainerFactory - */ - public T parse(InputStream in, JsonReaderI mapper) throws ParseException, UnsupportedEncodingException { - InputStreamReader i2 = new InputStreamReader(in, "utf8"); - // - return super.parse(i2, mapper); - } - - // - // - // - // - // - // - // - // -} diff --git a/maxkey-jose-jwt/src/main/java/net/minidev/json/parser/JSONParserMemory.java b/maxkey-jose-jwt/src/main/java/net/minidev/json/parser/JSONParserMemory.java deleted file mode 100644 index 356987c35..000000000 --- a/maxkey-jose-jwt/src/main/java/net/minidev/json/parser/JSONParserMemory.java +++ /dev/null @@ -1,140 +0,0 @@ -package net.minidev.json.parser; - -/* - * Copyright 2011 JSON-SMART authors - * - * 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. - */ -import static net.minidev.json.parser.ParseException.ERROR_UNEXPECTED_CHAR; -import static net.minidev.json.parser.ParseException.ERROR_UNEXPECTED_EOF; -import static net.minidev.json.parser.ParseException.ERROR_UNEXPECTED_TOKEN; - -import java.io.IOException; - -/** - * Parser for JSON text. Please note that JSONParser is NOT thread-safe. - * - * @author Uriel Chemouni <uchemouni@gmail.com> - * @see JSONParserString - * @see JSONParserByteArray - */ -abstract class JSONParserMemory extends JSONParserBase { - protected int len; - - public JSONParserMemory(int permissiveMode) { - super(permissiveMode); - } - - protected void readNQString(boolean[] stop) throws IOException { - int start = pos; - skipNQString(stop); - extractStringTrim(start, pos); - } - - protected Object readNumber(boolean[] stop) throws ParseException, IOException { - int start = pos; - // accept first char digit or - - read(); - skipDigits(); - - // Integer digit - if (c != '.' && c != 'E' && c != 'e') { - skipSpace(); - if (c >= 0 && c < MAX_STOP && !stop[c] && c != EOI) { - // convert string - skipNQString(stop); - extractStringTrim(start, pos); - if (!acceptNonQuote) - throw new ParseException(pos, ERROR_UNEXPECTED_TOKEN, xs); - return xs; - } - extractStringTrim(start, pos); - return parseNumber(xs); - } - // floating point - if (c == '.') { - // - read(); - skipDigits(); - } - if (c != 'E' && c != 'e') { - skipSpace(); - if (c >= 0 && c < MAX_STOP && !stop[c] && c != EOI) { - // convert string - skipNQString(stop); - extractStringTrim(start, pos); - if (!acceptNonQuote) - throw new ParseException(pos, ERROR_UNEXPECTED_TOKEN, xs); - return xs; - } - extractStringTrim(start, pos); - return extractFloat(); - } - sb.append('E'); - read(); - if (c == '+' || c == '-' || c >= '0' && c <= '9') { - sb.append(c); - read(); // skip first char - skipDigits(); - skipSpace(); - if (c >= 0 && c < MAX_STOP && !stop[c] && c != EOI) { - // convert string - skipNQString(stop); - extractStringTrim(start, pos); - if (!acceptNonQuote) - throw new ParseException(pos, ERROR_UNEXPECTED_TOKEN, xs); - return xs; - } - extractStringTrim(start, pos); - return extractFloat(); - } else { - skipNQString(stop); - extractStringTrim(start, pos); - if (!acceptNonQuote) - throw new ParseException(pos, ERROR_UNEXPECTED_TOKEN, xs); - if (!acceptLeadinZero) - checkLeadinZero(); - return xs; - } - // throw new ParseException(pos - 1, ERROR_UNEXPECTED_CHAR, null); - } - - protected void readString() throws ParseException, IOException { - if (!acceptSimpleQuote && c == '\'') { - if (acceptNonQuote) { - readNQString(stopAll); - return; - } - throw new ParseException(pos, ERROR_UNEXPECTED_CHAR, c); - } - int tmpP = indexOf(c, pos + 1); - if (tmpP == -1) - throw new ParseException(len, ERROR_UNEXPECTED_EOF, null); - extractString(pos + 1, tmpP); - if (xs.indexOf('\\') == -1) { - checkControleChar(); - pos = tmpP; - read(); - // handler.primitive(tmp); - return; - } - sb.clear(); - readString2(); - } - - abstract protected void extractString(int start, int stop); - - abstract protected int indexOf(char c, int pos); - - abstract protected void extractStringTrim(int start, int stop); -} diff --git a/maxkey-jose-jwt/src/main/java/net/minidev/json/parser/JSONParserReader.java b/maxkey-jose-jwt/src/main/java/net/minidev/json/parser/JSONParserReader.java deleted file mode 100644 index e8841c471..000000000 --- a/maxkey-jose-jwt/src/main/java/net/minidev/json/parser/JSONParserReader.java +++ /dev/null @@ -1,91 +0,0 @@ -package net.minidev.json.parser; - -/* - * Copyright 2011 JSON-SMART authors - * - * 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. - */ -import static net.minidev.json.parser.ParseException.ERROR_UNEXPECTED_EOF; - -import java.io.IOException; -import java.io.Reader; - -import net.minidev.json.JSONValue; -import net.minidev.json.writer.JsonReaderI; - -/** - * Parser for JSON text. Please note that JSONParser is NOT thread-safe. - * - * @author Uriel Chemouni <uchemouni@gmail.com> - */ -class JSONParserReader extends JSONParserStream { - private Reader in; - - // len - public JSONParserReader(int permissiveMode) { - super(permissiveMode); - } - - /** - * use to return Primitive Type, or String, Or JsonObject or JsonArray - * generated by a ContainerFactory - */ - public Object parse(Reader in) throws ParseException { - return parse(in, JSONValue.defaultReader.DEFAULT); - } - - /** - * use to return Primitive Type, or String, Or JsonObject or JsonArray - * generated by a ContainerFactory - */ - public T parse(Reader in, JsonReaderI mapper) throws ParseException { - this.base = mapper.base; - // - this.in = in; - return super.parse(mapper); - } - - // - // - // - // - // - // - // - - protected void read() throws IOException { - int i = in.read(); - c = (i == -1) ? (char) EOI : (char) i; - pos++; - // - } - - protected void readS() throws IOException { - sb.append(c); - int i = in.read(); - if (i == -1) { - c = EOI; - } else { - c = (char) i; - pos++; - } - } - - protected void readNoEnd() throws ParseException, IOException { - int i = in.read(); - if (i == -1) - throw new ParseException(pos - 1, ERROR_UNEXPECTED_EOF, "EOF"); - c = (char) i; - // - } -} diff --git a/maxkey-jose-jwt/src/main/java/net/minidev/json/parser/JSONParserStream.java b/maxkey-jose-jwt/src/main/java/net/minidev/json/parser/JSONParserStream.java deleted file mode 100644 index 05ec2870d..000000000 --- a/maxkey-jose-jwt/src/main/java/net/minidev/json/parser/JSONParserStream.java +++ /dev/null @@ -1,142 +0,0 @@ -package net.minidev.json.parser; - -/* - * Copyright 2011 JSON-SMART authors - * - * 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. - */ -import static net.minidev.json.parser.ParseException.ERROR_UNEXPECTED_CHAR; -import static net.minidev.json.parser.ParseException.ERROR_UNEXPECTED_TOKEN; - -import java.io.IOException; - -/** - * Parser for JSON text. Please note that JSONParser is NOT thread-safe. - * - * @author Uriel Chemouni <uchemouni@gmail.com> - * @see JSONParserInputStream - * @see JSONParserReader - */ -abstract class JSONParserStream extends JSONParserBase { - // len - // - public JSONParserStream(int permissiveMode) { - super(permissiveMode); - } - - protected void readNQString(boolean[] stop) throws IOException { - sb.clear(); - skipNQString(stop); - xs = sb.toString().trim(); - } - - protected Object readNumber(boolean[] stop) throws ParseException, IOException { - sb.clear(); - sb.append(c);// accept first char digit or - - read(); - skipDigits(); - - // Integer digit - if (c != '.' && c != 'E' && c != 'e') { - skipSpace(); - if (c >= 0 && c < MAX_STOP && !stop[c] && c != EOI) { - // convert string - skipNQString(stop); - xs = sb.toString().trim(); - if (!acceptNonQuote) - throw new ParseException(pos, ERROR_UNEXPECTED_TOKEN, xs); - return xs; - } - xs = sb.toString().trim(); - return parseNumber(xs); - } - // floating point - if (c == '.') { - sb.append(c); - read(); - skipDigits(); - } - if (c != 'E' && c != 'e') { - skipSpace(); - if (c >= 0 && c < MAX_STOP && !stop[c] && c != EOI) { - // convert string - skipNQString(stop); - xs = sb.toString().trim(); - if (!acceptNonQuote) - throw new ParseException(pos, ERROR_UNEXPECTED_TOKEN, xs); - return xs; - } - xs = sb.toString().trim(); - return extractFloat(); - } - sb.append('E'); - read(); - if (c == '+' || c == '-' || c >= '0' && c <= '9') { - sb.append(c); - read(); // skip first char - skipDigits(); - skipSpace(); - if (c >= 0 && c < MAX_STOP && !stop[c] && c != EOI) { - // convert string - skipNQString(stop); - xs = sb.toString().trim(); - if (!acceptNonQuote) - throw new ParseException(pos, ERROR_UNEXPECTED_TOKEN, xs); - return xs; - } - xs = sb.toString().trim(); - return extractFloat(); - } else { - skipNQString(stop); - xs = sb.toString().trim(); - if (!acceptNonQuote) - throw new ParseException(pos, ERROR_UNEXPECTED_TOKEN, xs); - if (!acceptLeadinZero) - checkLeadinZero(); - return xs; - } - // throw new ParseException(pos - 1, ERROR_UNEXPECTED_CHAR, null); - } - - protected void readString() throws ParseException, IOException { - if (!acceptSimpleQuote && c == '\'') { - if (acceptNonQuote) { - readNQString(stopAll); - return; - } - throw new ParseException(pos, ERROR_UNEXPECTED_CHAR, c); - } - sb.clear(); - // - // - // - // - // - // - // - // - // - // - /* assert (c == '\"' || c == '\'') */ - readString2(); - } - - // - // - // - // - // - // - // - // -} diff --git a/maxkey-jose-jwt/src/main/java/net/minidev/json/parser/JSONParserString.java b/maxkey-jose-jwt/src/main/java/net/minidev/json/parser/JSONParserString.java deleted file mode 100644 index 94f71a8d4..000000000 --- a/maxkey-jose-jwt/src/main/java/net/minidev/json/parser/JSONParserString.java +++ /dev/null @@ -1,109 +0,0 @@ -package net.minidev.json.parser; - -/* - * Copyright 2011 JSON-SMART authors - * - * 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. - */ -import static net.minidev.json.parser.ParseException.ERROR_UNEXPECTED_EOF; -import net.minidev.json.JSONValue; -import net.minidev.json.writer.JsonReaderI; - -/** - * Parser for JSON text. Please note that JSONParser is NOT thread-safe. - * - * @author Uriel Chemouni <uchemouni@gmail.com> - */ -class JSONParserString extends JSONParserMemory { - private String in; - - public JSONParserString(int permissiveMode) { - super(permissiveMode); - } - - /** - * use to return Primitive Type, or String, Or JsonObject or JsonArray - * generated by a ContainerFactory - */ - public Object parse(String in) throws ParseException { - return parse(in, JSONValue.defaultReader.DEFAULT); - } - - // - // - // - // - // - // - // - - /** - * use to return Primitive Type, or String, Or JsonObject or JsonArray - * generated by a ContainerFactory - */ - public T parse(String in, JsonReaderI mapper) throws ParseException { - this.base = mapper.base; - this.in = in; - this.len = in.length(); - return parse(mapper); - } - - protected void extractString(int beginIndex, int endIndex) { - xs = in.substring(beginIndex, endIndex); - } - - protected void extractStringTrim(int start, int stop) { - while (start < stop-1 && Character.isWhitespace(in.charAt(start))) { - start++; - } - while (stop-1 > start && Character.isWhitespace(in.charAt(stop-1))) { - stop--; - } - extractString(start, stop); - } - - protected int indexOf(char c, int pos) { - return in.indexOf(c, pos); - } - - /** - * Read next char or END OF INPUT - */ - protected void read() { - if (++pos >= len) - this.c = EOI; - else - this.c = in.charAt(pos); - } - - /** - * Same as read() in memory parsing - */ - protected void readS() { - if (++pos >= len) - this.c = EOI; - else - this.c = in.charAt(pos); - } - - /** - * read data can not be EOI - */ - protected void readNoEnd() throws ParseException { - if (++pos >= len) { - this.c = EOI; - throw new ParseException(pos - 1, ERROR_UNEXPECTED_EOF, "EOF"); - } else - this.c = in.charAt(pos); - } -} diff --git a/maxkey-jose-jwt/src/main/java/net/minidev/json/parser/ParseException.java b/maxkey-jose-jwt/src/main/java/net/minidev/json/parser/ParseException.java deleted file mode 100644 index e9332d9b1..000000000 --- a/maxkey-jose-jwt/src/main/java/net/minidev/json/parser/ParseException.java +++ /dev/null @@ -1,125 +0,0 @@ -package net.minidev.json.parser; - -/* - * Copyright 2011 JSON-SMART authors - * - * 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. - */ -/** - * ParseException explains why and where the error occurs in source JSON text. - * - * @author Uriel Chemouni <uchemouni@gmail.com> - */ -public class ParseException extends Exception { - private static final long serialVersionUID = 8879024178584091857L; - - public static final int ERROR_UNEXPECTED_CHAR = 0; - public static final int ERROR_UNEXPECTED_TOKEN = 1; - public static final int ERROR_UNEXPECTED_EXCEPTION = 2; - public static final int ERROR_UNEXPECTED_EOF = 3; - public static final int ERROR_UNEXPECTED_UNICODE = 4; - public static final int ERROR_UNEXPECTED_DUPLICATE_KEY = 5; - public static final int ERROR_UNEXPECTED_LEADING_0 = 6; - - private int errorType; - private Object unexpectedObject; - private int position; - - public ParseException(int position, int errorType, Object unexpectedObject) { - super(toMessage(position, errorType, unexpectedObject)); - this.position = position; - this.errorType = errorType; - this.unexpectedObject = unexpectedObject; - } - - public ParseException(int position, Throwable cause) { - super(toMessage(position, ERROR_UNEXPECTED_EXCEPTION, cause), cause); - this.position = position; - this.errorType = ERROR_UNEXPECTED_EXCEPTION; - this.unexpectedObject = cause; - } - - public int getErrorType() { - return errorType; - } - - /** - * @return The character position (starting with 0) of the input where the - * error occurs. - */ - public int getPosition() { - return position; - } - - /** - * @return One of the following base on the value of errorType: - * ERROR_UNEXPECTED_CHAR java.lang.Character ERROR_UNEXPECTED_TOKEN - * ERROR_UNEXPECTED_EXCEPTION java.lang.Exception - */ - public Object getUnexpectedObject() { - return unexpectedObject; - } - - private static String toMessage(int position, int errorType, Object unexpectedObject) { - StringBuilder sb = new StringBuilder(); - - if (errorType == ERROR_UNEXPECTED_CHAR) { - sb.append("Unexpected character ("); - sb.append(unexpectedObject); - sb.append(") at position "); - sb.append(position); - sb.append("."); - } else if (errorType == ERROR_UNEXPECTED_TOKEN) { - sb.append("Unexpected token "); - sb.append(unexpectedObject); - sb.append(" at position "); - sb.append(position); - sb.append("."); - } else if (errorType == ERROR_UNEXPECTED_EXCEPTION) { - sb.append("Unexpected exception "); - sb.append(unexpectedObject); - sb.append(" occur at position "); - sb.append(position); - sb.append("."); - } else if (errorType == ERROR_UNEXPECTED_EOF) { - sb.append("Unexpected End Of File position "); - sb.append(position); - sb.append(": "); - sb.append(unexpectedObject); - } else if (errorType == ERROR_UNEXPECTED_UNICODE) { - sb.append("Unexpected unicode escape sequence "); - sb.append(unexpectedObject); - sb.append(" at position "); - sb.append(position); - sb.append("."); - } else if (errorType == ERROR_UNEXPECTED_DUPLICATE_KEY) { - sb.append("Unexpected duplicate key:"); - sb.append(unexpectedObject); - sb.append(" at position "); - sb.append(position); - sb.append("."); - } else if (errorType == ERROR_UNEXPECTED_LEADING_0) { - sb.append("Unexpected leading 0 in digit for token:"); - sb.append(unexpectedObject); - sb.append(" at position "); - sb.append(position); - sb.append("."); - } else { - sb.append("Unkown error at position "); - sb.append(position); - sb.append("."); - } - return sb.toString(); - } - -} diff --git a/maxkey-jose-jwt/src/main/java/net/minidev/json/reader/ArrayWriter.java b/maxkey-jose-jwt/src/main/java/net/minidev/json/reader/ArrayWriter.java deleted file mode 100644 index 4341a2661..000000000 --- a/maxkey-jose-jwt/src/main/java/net/minidev/json/reader/ArrayWriter.java +++ /dev/null @@ -1,21 +0,0 @@ -package net.minidev.json.reader; - -import java.io.IOException; - -import net.minidev.json.JSONStyle; -import net.minidev.json.JSONValue; - -public class ArrayWriter implements JsonWriterI { - public void writeJSONString(E value, Appendable out, JSONStyle compression) throws IOException { - compression.arrayStart(out); - boolean needSep = false; - for (Object o : ((Object[]) value)) { - if (needSep) - compression.objectNext(out); - else - needSep = true; - JSONValue.writeJSONString(o, out, compression); - } - compression.arrayStop(out); - } -} diff --git a/maxkey-jose-jwt/src/main/java/net/minidev/json/reader/BeansWriter.java b/maxkey-jose-jwt/src/main/java/net/minidev/json/reader/BeansWriter.java deleted file mode 100644 index 5644db33d..000000000 --- a/maxkey-jose-jwt/src/main/java/net/minidev/json/reader/BeansWriter.java +++ /dev/null @@ -1,63 +0,0 @@ -package net.minidev.json.reader; - -import java.io.IOException; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; - -import net.minidev.json.JSONStyle; -import net.minidev.json.JSONUtil; - -public class BeansWriter implements JsonWriterI { - public void writeJSONString(E value, Appendable out, JSONStyle compression) throws IOException { - try { - Class nextClass = value.getClass(); - boolean needSep = false; - compression.objectStart(out); - while (nextClass != Object.class) { - Field[] fields = nextClass.getDeclaredFields(); - for (Field field : fields) { - int m = field.getModifiers(); - if ((m & (Modifier.STATIC | Modifier.TRANSIENT | Modifier.FINAL)) > 0) - continue; - Object v = null; - if ((m & Modifier.PUBLIC) > 0) { - v = field.get(value); - } else { - String g = JSONUtil.getGetterName(field.getName()); - Method mtd = null; - - try { - mtd = nextClass.getDeclaredMethod(g); - } catch (Exception e) { - } - if (mtd == null) { - Class c2 = field.getType(); - if (c2 == Boolean.TYPE || c2 == Boolean.class) { - g = JSONUtil.getIsName(field.getName()); - mtd = nextClass.getDeclaredMethod(g); - } - } - if (mtd == null) - continue; - v = mtd.invoke(value); - } - if (v == null && compression.ignoreNull()) - continue; - if (needSep) - compression.objectNext(out); - else - needSep = true; - String key = field.getName(); - - JsonWriter.writeJSONKV(key, v, out, compression); - // compression.objectElmStop(out); - } - nextClass = nextClass.getSuperclass(); - } - compression.objectStop(out); - } catch (Exception e) { - throw new RuntimeException(e); - } - } -} diff --git a/maxkey-jose-jwt/src/main/java/net/minidev/json/reader/BeansWriterASM.java b/maxkey-jose-jwt/src/main/java/net/minidev/json/reader/BeansWriterASM.java deleted file mode 100644 index 7b1feb047..000000000 --- a/maxkey-jose-jwt/src/main/java/net/minidev/json/reader/BeansWriterASM.java +++ /dev/null @@ -1,36 +0,0 @@ -package net.minidev.json.reader; - -import java.io.IOException; - -import net.minidev.asm.Accessor; -import net.minidev.asm.BeansAccess; -import net.minidev.json.JSONObject; -import net.minidev.json.JSONStyle; -import net.minidev.json.JSONUtil; - -public class BeansWriterASM implements JsonWriterI { - public void writeJSONString(E value, Appendable out, JSONStyle compression) throws IOException { - try { - Class cls = value.getClass(); - boolean needSep = false; - @SuppressWarnings("rawtypes") - BeansAccess fields = BeansAccess.get(cls, JSONUtil.JSON_SMART_FIELD_FILTER); - out.append('{'); - for (Accessor field : fields.getAccessors()) { - @SuppressWarnings("unchecked") - Object v = fields.get(value, field.getIndex()); - if (v == null && compression.ignoreNull()) - continue; - if (needSep) - out.append(','); - else - needSep = true; - String key = field.getName(); - JSONObject.writeJSONKV(key, v, out, compression); - } - out.append('}'); - } catch (IOException e) { - throw e; - } - } -} diff --git a/maxkey-jose-jwt/src/main/java/net/minidev/json/reader/BeansWriterASMRemap.java b/maxkey-jose-jwt/src/main/java/net/minidev/json/reader/BeansWriterASMRemap.java deleted file mode 100644 index c9b913730..000000000 --- a/maxkey-jose-jwt/src/main/java/net/minidev/json/reader/BeansWriterASMRemap.java +++ /dev/null @@ -1,53 +0,0 @@ -package net.minidev.json.reader; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -import net.minidev.asm.Accessor; -import net.minidev.asm.BeansAccess; -import net.minidev.json.JSONObject; -import net.minidev.json.JSONStyle; -import net.minidev.json.JSONUtil; - -public class BeansWriterASMRemap implements JsonWriterI { - private Map rename = new HashMap(); - - public void renameField(String source, String dest) { - rename.put(source, dest); - } - - private String rename(String key) { - String k2 = rename.get(key); - if (k2 != null) - return k2; - return key; - } - - public void writeJSONString(E value, Appendable out, JSONStyle compression) throws IOException { - try { - Class cls = value.getClass(); - boolean needSep = false; - @SuppressWarnings("rawtypes") - BeansAccess fields = BeansAccess.get(cls, JSONUtil.JSON_SMART_FIELD_FILTER); - out.append('{'); - for (Accessor field : fields.getAccessors()) { - @SuppressWarnings("unchecked") - Object v = fields.get(value, field.getIndex()); - if (v == null && compression.ignoreNull()) - continue; - if (needSep) - out.append(','); - else - needSep = true; - String key = field.getName(); - key = rename(key); - JSONObject.writeJSONKV(key, v, out, compression); - } - out.append('}'); - } catch (IOException e) { - throw e; - } - } - -} diff --git a/maxkey-jose-jwt/src/main/java/net/minidev/json/reader/JsonWriter.java b/maxkey-jose-jwt/src/main/java/net/minidev/json/reader/JsonWriter.java deleted file mode 100644 index 8a73d642b..000000000 --- a/maxkey-jose-jwt/src/main/java/net/minidev/json/reader/JsonWriter.java +++ /dev/null @@ -1,395 +0,0 @@ -package net.minidev.json.reader; - -import java.io.IOException; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.util.Date; -import java.util.LinkedList; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import net.minidev.json.JSONAware; -import net.minidev.json.JSONAwareEx; -import net.minidev.json.JSONStreamAware; -import net.minidev.json.JSONStreamAwareEx; -import net.minidev.json.JSONStyle; -import net.minidev.json.JSONValue; - -public class JsonWriter { - private ConcurrentHashMap, JsonWriterI> data; - private LinkedList writerInterfaces; - - public JsonWriter() { - data = new ConcurrentHashMap, JsonWriterI>(); - writerInterfaces = new LinkedList(); - init(); - } - - /** - * remap field name in custom classes - * - * @param fromJava - * field name in java - * @param toJson - * field name in json - * @since 2.1.1 - */ - @SuppressWarnings({ "rawtypes", "unchecked" }) - public void remapField(Class type, String fromJava, String toJson) { - JsonWriterI map = this.getWrite(type); - if (!(map instanceof BeansWriterASMRemap)) { - map = new BeansWriterASMRemap(); - registerWriter(map, type); - } - ((BeansWriterASMRemap) map).renameField(fromJava, toJson); - } - - static class WriterByInterface { - public Class _interface; - public JsonWriterI _writer; - - public WriterByInterface(Class _interface, JsonWriterI _writer) { - this._interface = _interface; - this._writer = _writer; - } - } - - /** - * try to find a Writer by Cheking implemented interface - * @param clazz class to serialize - * @return a Writer or null - */ - @SuppressWarnings("rawtypes") - public JsonWriterI getWriterByInterface(Class clazz) { - for (WriterByInterface w : writerInterfaces) { - if (w._interface.isAssignableFrom(clazz)) - return w._writer; - } - return null; - } - - @SuppressWarnings("rawtypes") - public JsonWriterI getWrite(Class cls) { - return data.get(cls); - } - - final static public JsonWriterI JSONStreamAwareWriter = new JsonWriterI() { - public void writeJSONString(E value, Appendable out, JSONStyle compression) throws IOException { - value.writeJSONString(out); - } - }; - - final static public JsonWriterI JSONStreamAwareExWriter = new JsonWriterI() { - public void writeJSONString(E value, Appendable out, JSONStyle compression) throws IOException { - value.writeJSONString(out, compression); - } - }; - - final static public JsonWriterI JSONJSONAwareExWriter = new JsonWriterI() { - public void writeJSONString(E value, Appendable out, JSONStyle compression) throws IOException { - out.append(value.toJSONString(compression)); - } - }; - - final static public JsonWriterI JSONJSONAwareWriter = new JsonWriterI() { - public void writeJSONString(E value, Appendable out, JSONStyle compression) throws IOException { - out.append(value.toJSONString()); - } - }; - - final static public JsonWriterI> JSONIterableWriter = new JsonWriterI>() { - public > void writeJSONString(E list, Appendable out, JSONStyle compression) throws IOException { - boolean first = true; - compression.arrayStart(out); - for (Object value : list) { - if (first) { - first = false; - compression.arrayfirstObject(out); - } else { - compression.arrayNextElm(out); - } - if (value == null) - out.append("null"); - else - JSONValue.writeJSONString(value, out, compression); - compression.arrayObjectEnd(out); - } - compression.arrayStop(out); - } - }; - - final static public JsonWriterI> EnumWriter = new JsonWriterI>() { - public > void writeJSONString(E value, Appendable out, JSONStyle compression) throws IOException { - @SuppressWarnings("rawtypes") - String s = ((Enum) value).name(); - compression.writeString(out, s); - } - }; - - final static public JsonWriterI> JSONMapWriter = new JsonWriterI>() { - public > void writeJSONString(E map, Appendable out, JSONStyle compression) throws IOException { - boolean first = true; - compression.objectStart(out); - /** - * do not use to handle non String key maps - */ - for (Map.Entry entry : map.entrySet()) { - Object v = entry.getValue(); - if (v == null && compression.ignoreNull()) - continue; - if (first) { - compression.objectFirstStart(out); - first = false; - } else { - compression.objectNext(out); - } - JsonWriter.writeJSONKV(entry.getKey().toString(), v, out, compression); - // compression.objectElmStop(out); - } - compression.objectStop(out); - } - }; - - /** - * Json-Smart V2 Beans serialiser - * - * Based on ASM - */ - final static public JsonWriterI beansWriterASM = new BeansWriterASM(); - - /** - * Json-Smart V1 Beans serialiser - */ - final static public JsonWriterI beansWriter = new BeansWriter(); - - /** - * Json-Smart ArrayWriterClass - */ - final static public JsonWriterI arrayWriter = new ArrayWriter(); - - /** - * ToString Writer - */ - final static public JsonWriterI toStringWriter = new JsonWriterI() { - public void writeJSONString(Object value, Appendable out, JSONStyle compression) throws IOException { - out.append(value.toString()); - } - }; - - public void init() { - registerWriter(new JsonWriterI() { - public void writeJSONString(String value, Appendable out, JSONStyle compression) throws IOException { - compression.writeString(out, (String) value); - } - }, String.class); - - registerWriter(new JsonWriterI() { - public void writeJSONString(Double value, Appendable out, JSONStyle compression) throws IOException { - if (value.isInfinite()) - out.append("null"); - else - out.append(value.toString()); - } - }, Double.class); - - registerWriter(new JsonWriterI() { - public void writeJSONString(Date value, Appendable out, JSONStyle compression) throws IOException { - out.append('"'); - JSONValue.escape(value.toString(), out, compression); - out.append('"'); - } - }, Date.class); - - registerWriter(new JsonWriterI() { - public void writeJSONString(Float value, Appendable out, JSONStyle compression) throws IOException { - if (value.isInfinite()) - out.append("null"); - else - out.append(value.toString()); - } - }, Float.class); - - registerWriter(toStringWriter, Integer.class, Long.class, Byte.class, Short.class, BigInteger.class, BigDecimal.class); - registerWriter(toStringWriter, Boolean.class); - - /** - * Array - */ - - registerWriter(new JsonWriterI() { - public void writeJSONString(int[] value, Appendable out, JSONStyle compression) throws IOException { - boolean needSep = false; - compression.arrayStart(out); - for (int b : value) { - if (needSep) - compression.objectNext(out); - else - needSep = true; - out.append(Integer.toString(b)); - } - compression.arrayStop(out); - } - }, int[].class); - - registerWriter(new JsonWriterI() { - public void writeJSONString(short[] value, Appendable out, JSONStyle compression) throws IOException { - boolean needSep = false; - compression.arrayStart(out); - for (short b : value) { - if (needSep) - compression.objectNext(out); - else - needSep = true; - out.append(Short.toString(b)); - } - compression.arrayStop(out); - } - }, short[].class); - - registerWriter(new JsonWriterI() { - public void writeJSONString(long[] value, Appendable out, JSONStyle compression) throws IOException { - boolean needSep = false; - compression.arrayStart(out); - for (long b : value) { - if (needSep) - compression.objectNext(out); - else - needSep = true; - out.append(Long.toString(b)); - } - compression.arrayStop(out); - } - }, long[].class); - - registerWriter(new JsonWriterI() { - public void writeJSONString(float[] value, Appendable out, JSONStyle compression) throws IOException { - boolean needSep = false; - compression.arrayStart(out); - for (float b : value) { - if (needSep) - compression.objectNext(out); - else - needSep = true; - out.append(Float.toString(b)); - } - compression.arrayStop(out); - } - }, float[].class); - - registerWriter(new JsonWriterI() { - public void writeJSONString(double[] value, Appendable out, JSONStyle compression) throws IOException { - boolean needSep = false; - compression.arrayStart(out); - for (double b : value) { - if (needSep) - compression.objectNext(out); - else - needSep = true; - out.append(Double.toString(b)); - } - compression.arrayStop(out); - } - }, double[].class); - - registerWriter(new JsonWriterI() { - public void writeJSONString(boolean[] value, Appendable out, JSONStyle compression) throws IOException { - boolean needSep = false; - compression.arrayStart(out); - for (boolean b : value) { - if (needSep) - compression.objectNext(out); - else - needSep = true; - out.append(Boolean.toString(b)); - } - compression.arrayStop(out); - } - }, boolean[].class); - - registerWriterInterface(JSONStreamAwareEx.class, JsonWriter.JSONStreamAwareExWriter); - registerWriterInterface(JSONStreamAware.class, JsonWriter.JSONStreamAwareWriter); - registerWriterInterface(JSONAwareEx.class, JsonWriter.JSONJSONAwareExWriter); - registerWriterInterface(JSONAware.class, JsonWriter.JSONJSONAwareWriter); - registerWriterInterface(Map.class, JsonWriter.JSONMapWriter); - registerWriterInterface(Iterable.class, JsonWriter.JSONIterableWriter); - registerWriterInterface(Enum.class, JsonWriter.EnumWriter); - registerWriterInterface(Number.class, JsonWriter.toStringWriter); - } - - /** - * associate an Writer to a interface With Hi priority - * @param interFace interface to map - * @param writer writer Object - * @deprecated use registerWriterInterfaceFirst - */ - public void addInterfaceWriterFirst(Class interFace, JsonWriterI writer) { - registerWriterInterfaceFirst(interFace, writer); - } - - /** - * associate an Writer to a interface With Low priority - * @param interFace interface to map - * @param writer writer Object - * @deprecated use registerWriterInterfaceLast - */ - public void addInterfaceWriterLast(Class interFace, JsonWriterI writer) { - registerWriterInterfaceLast(interFace, writer); - } - - /** - * associate an Writer to a interface With Low priority - * @param interFace interface to map - * @param writer writer Object - */ - public void registerWriterInterfaceLast(Class interFace, JsonWriterI writer) { - writerInterfaces.addLast(new WriterByInterface(interFace, writer)); - } - - /** - * associate an Writer to a interface With Hi priority - * @param interFace interface to map - * @param writer writer Object - */ - public void registerWriterInterfaceFirst(Class interFace, JsonWriterI writer) { - writerInterfaces.addFirst(new WriterByInterface(interFace, writer)); - } - - /** - * an alias for registerWriterInterfaceLast - * @param interFace interface to map - * @param writer writer Object - */ - public void registerWriterInterface(Class interFace, JsonWriterI writer) { - registerWriterInterfaceLast(interFace, writer); - } - - /** - * associate an Writer to a Class - * @param writer - * @param cls - */ - public void registerWriter(JsonWriterI writer, Class... cls) { - for (Class c : cls) - data.put(c, writer); - } - - /** - * Write a Key : value entry to a stream - */ - public static void writeJSONKV(String key, Object value, Appendable out, JSONStyle compression) throws IOException { - if (key == null) - out.append("null"); - else if (!compression.mustProtectKey(key)) - out.append(key); - else { - out.append('"'); - JSONValue.escape(key, out, compression); - out.append('"'); - } - compression.objectEndOfKey(out); - if (value instanceof String) { - compression.writeString(out, (String) value); - } else - JSONValue.writeJSONString(value, out, compression); - compression.objectElmStop(out); - } -} diff --git a/maxkey-jose-jwt/src/main/java/net/minidev/json/reader/JsonWriterI.java b/maxkey-jose-jwt/src/main/java/net/minidev/json/reader/JsonWriterI.java deleted file mode 100644 index ee818bf0f..000000000 --- a/maxkey-jose-jwt/src/main/java/net/minidev/json/reader/JsonWriterI.java +++ /dev/null @@ -1,9 +0,0 @@ -package net.minidev.json.reader; - -import java.io.IOException; - -import net.minidev.json.JSONStyle; - -public interface JsonWriterI { - public void writeJSONString(E value, Appendable out, JSONStyle compression) throws IOException; -} diff --git a/maxkey-jose-jwt/src/main/java/net/minidev/json/writer/ArraysMapper.java b/maxkey-jose-jwt/src/main/java/net/minidev/json/writer/ArraysMapper.java deleted file mode 100644 index 7f6b6becc..000000000 --- a/maxkey-jose-jwt/src/main/java/net/minidev/json/writer/ArraysMapper.java +++ /dev/null @@ -1,309 +0,0 @@ -package net.minidev.json.writer; - -/* - * Copyright 2011 JSON-SMART authors - * - * 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. - */ -import java.lang.reflect.Array; -import java.util.ArrayList; -import java.util.List; - -public class ArraysMapper extends JsonReaderI { - public ArraysMapper(JsonReader base) { - super(base); - } - - @Override - public Object createArray() { - return new ArrayList(); - } - - @SuppressWarnings("unchecked") - @Override - public void addValue(Object current, Object value) { - ((List) current).add(value); - } - - @SuppressWarnings("unchecked") - @Override - public T convert(Object current) { - return (T) current; - } - - public static class GenericMapper extends ArraysMapper { - final Class componentType; - JsonReaderI subMapper; - - public GenericMapper(JsonReader base, Class type) { - super(base); - this.componentType = type.getComponentType(); - } - - @SuppressWarnings("unchecked") - @Override - public T convert(Object current) { - int p = 0; - - Object[] r = (Object[]) Array.newInstance(componentType, ((List) current).size()); - for (Object e : ((List) current)) - r[p++] = e; - return (T) r; - } - - @Override - public JsonReaderI startArray(String key) { - if (subMapper == null) - subMapper = base.getMapper(componentType); - return subMapper; - } - - @Override - public JsonReaderI startObject(String key) { - if (subMapper == null) - subMapper = base.getMapper(componentType); - return subMapper; - } - }; - - public static JsonReaderI MAPPER_PRIM_INT = new ArraysMapper(null) { - @Override - public int[] convert(Object current) { - int p = 0; - int[] r = new int[((List) current).size()]; - for (Object e : ((List) current)) - r[p++] = ((Number) e).intValue(); - return r; - } - }; - - public static JsonReaderI MAPPER_INT = new ArraysMapper(null) { - @Override - public Integer[] convert(Object current) { - int p = 0; - Integer[] r = new Integer[((List) current).size()]; - for (Object e : ((List) current)) { - if (e == null) - continue; - if (e instanceof Integer) - r[p] = (Integer) e; - else - r[p] = ((Number) e).intValue(); - p++; - } - return r; - } - }; - - public static JsonReaderI MAPPER_PRIM_SHORT = new ArraysMapper(null) { - @Override - public short[] convert(Object current) { - int p = 0; - short[] r = new short[((List) current).size()]; - for (Object e : ((List) current)) - r[p++] = ((Number) e).shortValue(); - return r; - } - }; - - public static JsonReaderI MAPPER_SHORT = new ArraysMapper(null) { - @Override - public Short[] convert(Object current) { - int p = 0; - Short[] r = new Short[((List) current).size()]; - for (Object e : ((List) current)) { - if (e == null) - continue; - if (e instanceof Short) - r[p] = (Short) e; - else - r[p] = ((Number) e).shortValue(); - p++; - } - return r; - } - }; - - public static JsonReaderI MAPPER_PRIM_BYTE = new ArraysMapper(null) { - @Override - public byte[] convert(Object current) { - int p = 0; - byte[] r = new byte[((List) current).size()]; - for (Object e : ((List) current)) - r[p++] = ((Number) e).byteValue(); - return r; - } - }; - - public static JsonReaderI MAPPER_BYTE = new ArraysMapper(null) { - @Override - public Byte[] convert(Object current) { - int p = 0; - Byte[] r = new Byte[((List) current).size()]; - for (Object e : ((List) current)) { - if (e == null) - continue; - if (e instanceof Byte) - r[p] = (Byte) e; - else - r[p] = ((Number) e).byteValue(); - p++; - } - return r; - } - }; - - public static JsonReaderI MAPPER_PRIM_CHAR = new ArraysMapper(null) { - @Override - public char[] convert(Object current) { - int p = 0; - char[] r = new char[((List) current).size()]; - for (Object e : ((List) current)) - r[p++] = e.toString().charAt(0); - return r; - } - }; - - public static JsonReaderI MAPPER_CHAR = new ArraysMapper(null) { - @Override - public Character[] convert(Object current) { - int p = 0; - Character[] r = new Character[((List) current).size()]; - for (Object e : ((List) current)) { - if (e == null) - continue; - r[p] = e.toString().charAt(0); - p++; - } - return r; - } - }; - - public static JsonReaderI MAPPER_PRIM_LONG = new ArraysMapper(null) { - @Override - public long[] convert(Object current) { - int p = 0; - long[] r = new long[((List) current).size()]; - for (Object e : ((List) current)) - r[p++] = ((Number) e).intValue(); - return r; - } - }; - - public static JsonReaderI MAPPER_LONG = new ArraysMapper(null) { - @Override - public Long[] convert(Object current) { - int p = 0; - Long[] r = new Long[((List) current).size()]; - for (Object e : ((List) current)) { - if (e == null) - continue; - if (e instanceof Float) - r[p] = ((Long) e); - else - r[p] = ((Number) e).longValue(); - p++; - } - return r; - } - }; - - public static JsonReaderI MAPPER_PRIM_FLOAT = new ArraysMapper(null) { - @Override - public float[] convert(Object current) { - int p = 0; - float[] r = new float[((List) current).size()]; - for (Object e : ((List) current)) - r[p++] = ((Number) e).floatValue(); - return r; - } - }; - - public static JsonReaderI MAPPER_FLOAT = new ArraysMapper(null) { - @Override - public Float[] convert(Object current) { - int p = 0; - Float[] r = new Float[((List) current).size()]; - for (Object e : ((List) current)) { - if (e == null) - continue; - if (e instanceof Float) - r[p] = ((Float) e); - else - r[p] = ((Number) e).floatValue(); - p++; - } - return r; - } - }; - - public static JsonReaderI MAPPER_PRIM_DOUBLE = new ArraysMapper(null) { - @Override - public double[] convert(Object current) { - int p = 0; - double[] r = new double[((List) current).size()]; - for (Object e : ((List) current)) - r[p++] = ((Number) e).doubleValue(); - return r; - } - }; - - public static JsonReaderI MAPPER_DOUBLE = new ArraysMapper(null) { - @Override - public Double[] convert(Object current) { - int p = 0; - Double[] r = new Double[((List) current).size()]; - for (Object e : ((List) current)) { - if (e == null) - continue; - if (e instanceof Double) - r[p] = ((Double) e); - else - r[p] = ((Number) e).doubleValue(); - p++; - } - return r; - } - }; - - public static JsonReaderI MAPPER_PRIM_BOOL = new ArraysMapper(null) { - @Override - public boolean[] convert(Object current) { - int p = 0; - boolean[] r = new boolean[((List) current).size()]; - for (Object e : ((List) current)) - r[p++] = ((Boolean) e).booleanValue(); - return r; - } - }; - - public static JsonReaderI MAPPER_BOOL = new ArraysMapper(null) { - @Override - public Boolean[] convert(Object current) { - int p = 0; - Boolean[] r = new Boolean[((List) current).size()]; - for (Object e : ((List) current)) { - if (e == null) - continue; - if (e instanceof Boolean) - r[p] = ((Boolean) e).booleanValue(); - else if (e instanceof Number) - r[p] = ((Number) e).intValue() != 0; - else - throw new RuntimeException("can not convert " + e + " toBoolean"); - p++; - } - return r; - } - }; -} diff --git a/maxkey-jose-jwt/src/main/java/net/minidev/json/writer/BeansMapper.java b/maxkey-jose-jwt/src/main/java/net/minidev/json/writer/BeansMapper.java deleted file mode 100644 index 9f73fb7e2..000000000 --- a/maxkey-jose-jwt/src/main/java/net/minidev/json/writer/BeansMapper.java +++ /dev/null @@ -1,153 +0,0 @@ -package net.minidev.json.writer; - -/* - * Copyright 2011 JSON-SMART authors - * - * 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. - */ - -import java.lang.reflect.Type; -import java.util.Date; -import java.util.HashMap; - -import net.minidev.asm.Accessor; -import net.minidev.asm.BeansAccess; -import net.minidev.asm.ConvertDate; -import net.minidev.json.JSONUtil; - -@SuppressWarnings("unchecked") -public abstract class BeansMapper extends JsonReaderI { - - public BeansMapper(JsonReader base) { - super(base); - } - - public abstract Object getValue(Object current, String key); - - public static class Bean extends JsonReaderI { - final Class clz; - final BeansAccess ba; - final HashMap index; - - public Bean(JsonReader base, Class clz) { - super(base); - this.clz = clz; - this.ba = BeansAccess.get(clz, JSONUtil.JSON_SMART_FIELD_FILTER); - this.index = ba.getMap(); - } - - @Override - public void setValue(Object current, String key, Object value) { - ba.set((T) current, key, value); - // Accessor nfo = index.get(key); - // if (nfo == null) - // throw new RuntimeException("Can not set " + key + " field in " + - // clz); - // value = JSONUtil.convertTo(value, nfo.getType()); - // ba.set((T) current, nfo.getIndex(), value); - } - - public Object getValue(Object current, String key) { - return ba.get((T) current, key); - // Accessor nfo = index.get(key); - // if (nfo == null) - // throw new RuntimeException("Can not set " + key + " field in " + - // clz); - // return ba.get((T) current, nfo.getIndex()); - } - - @Override - public Type getType(String key) { - Accessor nfo = index.get(key); - return nfo.getGenericType(); - } - - @Override - public JsonReaderI startArray(String key) { - Accessor nfo = index.get(key); - if (nfo == null) - throw new RuntimeException("Can not find Array '" + key + "' field in " + clz); - return base.getMapper(nfo.getGenericType()); - } - - @Override - public JsonReaderI startObject(String key) { - Accessor f = index.get(key); - if (f == null) - throw new RuntimeException("Can not find Object '" + key + "' field in " + clz); - return base.getMapper(f.getGenericType()); - } - - @Override - public Object createObject() { - return ba.newInstance(); - } - } - - public static class BeanNoConv extends JsonReaderI { - final Class clz; - final BeansAccess ba; - final HashMap index; - - public BeanNoConv(JsonReader base, Class clz) { - super(base); - this.clz = clz; - this.ba = BeansAccess.get(clz, JSONUtil.JSON_SMART_FIELD_FILTER); - this.index = ba.getMap(); - } - - @Override - public void setValue(Object current, String key, Object value) { - ba.set((T) current, key, value); - } - - public Object getValue(Object current, String key) { - return ba.get((T) current, key); - } - - @Override - public Type getType(String key) { - Accessor nfo = index.get(key); - return nfo.getGenericType(); - } - - @Override - public JsonReaderI startArray(String key) { - Accessor nfo = index.get(key); - if (nfo == null) - throw new RuntimeException("Can not set " + key + " field in " + clz); - return base.getMapper(nfo.getGenericType()); - } - - @Override - public JsonReaderI startObject(String key) { - Accessor f = index.get(key); - if (f == null) - throw new RuntimeException("Can not set " + key + " field in " + clz); - return base.getMapper(f.getGenericType()); - } - - @Override - public Object createObject() { - return ba.newInstance(); - } - } - - public static JsonReaderI MAPPER_DATE = new ArraysMapper(null) { - @Override - public Date convert(Object current) { - return ConvertDate.convertToDate(current); - } - }; - -} diff --git a/maxkey-jose-jwt/src/main/java/net/minidev/json/writer/CollectionMapper.java b/maxkey-jose-jwt/src/main/java/net/minidev/json/writer/CollectionMapper.java deleted file mode 100644 index 346c4512e..000000000 --- a/maxkey-jose-jwt/src/main/java/net/minidev/json/writer/CollectionMapper.java +++ /dev/null @@ -1,252 +0,0 @@ -package net.minidev.json.writer; - -/* - * Copyright 2011 JSON-SMART authors - * - * 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. - */ -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.util.List; -import java.util.Map; - -import net.minidev.asm.BeansAccess; -import net.minidev.json.JSONArray; -import net.minidev.json.JSONObject; -import net.minidev.json.JSONUtil; - -public class CollectionMapper { - - public static class MapType extends JsonReaderI { - final ParameterizedType type; - final Class rawClass; - final Class instance; - final BeansAccess ba; - - final Type keyType; - final Type valueType; - - final Class keyClass; - final Class valueClass; - - JsonReaderI subMapper; - - public MapType(JsonReader base, ParameterizedType type) { - super(base); - this.type = type; - this.rawClass = (Class) type.getRawType(); - if (rawClass.isInterface()) - instance = JSONObject.class; - else - instance = rawClass; - ba = BeansAccess.get(instance, JSONUtil.JSON_SMART_FIELD_FILTER); - - keyType = type.getActualTypeArguments()[0]; - valueType = type.getActualTypeArguments()[1]; - if (keyType instanceof Class) - keyClass = (Class) keyType; - else - keyClass = (Class) ((ParameterizedType) keyType).getRawType(); - if (valueType instanceof Class) - valueClass = (Class) valueType; - else - valueClass = (Class) ((ParameterizedType) valueType).getRawType(); - } - - @Override - public Object createObject() { - try { - return instance.newInstance(); - } catch (InstantiationException e) { - e.printStackTrace(); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } - return null; - } - - @Override - public JsonReaderI startArray(String key) { - if (subMapper == null) - subMapper = base.getMapper(valueType); - return subMapper; - } - - @Override - public JsonReaderI startObject(String key) { - if (subMapper == null) - subMapper = base.getMapper(valueType); - return subMapper; - } - - @SuppressWarnings("unchecked") - @Override - public void setValue(Object current, String key, Object value) { - ((Map) current).put(JSONUtil.convertToX(key, keyClass), - JSONUtil.convertToX(value, valueClass)); - } - - @SuppressWarnings("unchecked") - @Override - public Object getValue(Object current, String key) { - return ((Map) current).get(JSONUtil.convertToX(key, keyClass)); - } - - @Override - public Type getType(String key) { - return type; - } - }; - - public static class MapClass extends JsonReaderI { - final Class type; - final Class instance; - final BeansAccess ba; - - JsonReaderI subMapper; - - public MapClass(JsonReader base, Class type) { - super(base); - this.type = type; - if (type.isInterface()) - this.instance = JSONObject.class; - else - this.instance = type; - this.ba = BeansAccess.get(instance, JSONUtil.JSON_SMART_FIELD_FILTER); - } - - @Override - public Object createObject() { - return ba.newInstance(); - } - - @Override - public JsonReaderI startArray(String key) { - return base.DEFAULT ; // _ARRAY - } - - @Override - public JsonReaderI startObject(String key) { - return base.DEFAULT; // _MAP - } - - @SuppressWarnings("unchecked") - @Override - public void setValue(Object current, String key, Object value) { - ((Map) current).put(key, value); - } - - @SuppressWarnings("unchecked") - @Override - public Object getValue(Object current, String key) { - return ((Map) current).get(key); - } - - @Override - public Type getType(String key) { - return type; - } - }; - - public static class ListType extends JsonReaderI { - final ParameterizedType type; - final Class rawClass; - final Class instance; - final BeansAccess ba; - - final Type valueType; - final Class valueClass; - - JsonReaderI subMapper; - - public ListType(JsonReader base, ParameterizedType type) { - super(base); - this.type = type; - this.rawClass = (Class) type.getRawType(); - if (rawClass.isInterface()) - instance = JSONArray.class; - else - instance = rawClass; - ba = BeansAccess.get(instance, JSONUtil.JSON_SMART_FIELD_FILTER); // NEW - valueType = type.getActualTypeArguments()[0]; - if (valueType instanceof Class) - valueClass = (Class) valueType; - else - valueClass = (Class) ((ParameterizedType) valueType).getRawType(); - } - - @Override - public Object createArray() { - return ba.newInstance(); - } - - @Override - public JsonReaderI startArray(String key) { - if (subMapper == null) - subMapper = base.getMapper(type.getActualTypeArguments()[0]); - return subMapper; - } - - @Override - public JsonReaderI startObject(String key) { - if (subMapper == null) - subMapper = base.getMapper(type.getActualTypeArguments()[0]); - return subMapper; - } - - @SuppressWarnings("unchecked") - @Override - public void addValue(Object current, Object value) { - ((List) current).add(JSONUtil.convertToX(value, valueClass)); - } - }; - - public static class ListClass extends JsonReaderI { - final Class type; - final Class instance; - final BeansAccess ba; - - JsonReaderI subMapper; - - public ListClass(JsonReader base, Class clazz) { - super(base); - this.type = clazz; - if (clazz.isInterface()) - instance = JSONArray.class; - else - instance = clazz; - ba = BeansAccess.get(instance, JSONUtil.JSON_SMART_FIELD_FILTER); - } - - @Override - public Object createArray() { - return ba.newInstance(); - } - - @Override - public JsonReaderI startArray(String key) { - return base.DEFAULT;// _ARRAY; - } - - @Override - public JsonReaderI startObject(String key) { - return base.DEFAULT;// _MAP; - } - - @SuppressWarnings("unchecked") - @Override - public void addValue(Object current, Object value) { - ((List) current).add(value); - } - }; -} diff --git a/maxkey-jose-jwt/src/main/java/net/minidev/json/writer/CompessorMapper.java b/maxkey-jose-jwt/src/main/java/net/minidev/json/writer/CompessorMapper.java deleted file mode 100644 index aab1319cf..000000000 --- a/maxkey-jose-jwt/src/main/java/net/minidev/json/writer/CompessorMapper.java +++ /dev/null @@ -1,218 +0,0 @@ -package net.minidev.json.writer; - -/* - * Copyright 2011 JSON-SMART authors - * - * 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. - */ -import java.io.IOException; - -import net.minidev.json.JSONStyle; -import net.minidev.json.JSONValue; - -public class CompessorMapper extends JsonReaderI { - private Appendable out; - private JSONStyle compression; - private Boolean _isObj; - private boolean needSep = false; - private boolean isOpen = false; - private boolean isClosed = false; - - // private boolean isRoot = false; - - private boolean isArray() { - return _isObj == Boolean.FALSE; - } - - private boolean isObject() { - return _isObj == Boolean.TRUE; - } - - private boolean isCompressor(Object obj) { - return obj instanceof CompessorMapper; - } - - public CompessorMapper(JsonReader base, Appendable out, JSONStyle compression) { - this(base, out, compression, null); - // isRoot = true; - } - - public CompessorMapper(JsonReader base, Appendable out, JSONStyle compression, Boolean isObj) { - super(base); - this.out = out; - this.compression = compression; - this._isObj = isObj; - // System.out.println("new CompressorMapper isObj:" + isObj); - } - - @Override - public JsonReaderI startObject(String key) throws IOException { - open(this); - startKey(key); - // System.out.println("startObject " + key); - CompessorMapper r = new CompessorMapper(base, out, compression, true); - open(r); - return r; - } - - @Override - public JsonReaderI startArray(String key) throws IOException { - open(this); - startKey(key); - // System.out.println("startArray " + key); - CompessorMapper r = new CompessorMapper(base, out, compression, false); - open(r); - return r; - } - - private void startKey(String key) throws IOException { - addComma(); - // if (key == null) - // return; - if (isArray()) - return; - if (!compression.mustProtectKey(key)) - out.append(key); - else { - out.append('"'); - JSONValue.escape(key, out, compression); - out.append('"'); - } - out.append(':'); - } - - @Override - public void setValue(Object current, String key, Object value) throws IOException { - // System.out.println("setValue(" + key + "," + value + ")"); - // if comprossor => data allready writed - if (isCompressor(value)) { - addComma(); - return; - } - startKey(key); - writeValue(value); - } - - @Override - public void addValue(Object current, Object value) throws IOException { - // System.out.println("add value" + value); - // if (!isCompressor(value)) - addComma(); - writeValue(value); - } - - private void addComma() throws IOException { - if (needSep) { - out.append(','); - // needSep = false; - } else { - needSep = true; - } - } - - private void writeValue(Object value) throws IOException { - if (value instanceof String) { - compression.writeString(out, (String) value); -// -// if (!compression.mustProtectValue((String) value)) -// out.append((String) value); -// else { -// out.append('"'); -// JSONValue.escape((String) value, out, compression); -// out.append('"'); -// } - // needSep = true; - } else { - if (isCompressor(value)) { - close(value); - // needSep = true; - } else { - JSONValue.writeJSONString(value, out, compression); - // needSep = true; - } - } - } - - @Override - public Object createObject() { - // System.out.println("createObject"); - this._isObj = true; - try { - open(this); - } catch (Exception e) { - } - // if (this.isUnknow() && isRoot) { // && isRoot - // this._isObj = true; - // try { - // out.append('{'); // 1 - // } catch (Exception e) { - // } - // } - return this; - } - - @Override - public Object createArray() { - // System.out.println("createArray"); - this._isObj = false; - try { - open(this); - } catch (Exception e) { - } - return this; - } - - public CompessorMapper convert(Object current) { - try { - close(current); - return this; - } catch (Exception e) { - return this; - } - } - - private void close(Object obj) throws IOException { - if (!isCompressor(obj)) - return; - if (((CompessorMapper) obj).isClosed) - return; - ((CompessorMapper) obj).isClosed = true; - if (((CompessorMapper) obj).isObject()) { - // System.out.println("convert }"); - out.append('}'); - needSep = true; - } else if (((CompessorMapper) obj).isArray()) { - // System.out.println("convert ]"); - out.append(']'); - needSep = true; - } - } - - private void open(Object obj) throws IOException { - if (!isCompressor(obj)) - return; - if (((CompessorMapper) obj).isOpen) - return; - ((CompessorMapper) obj).isOpen = true; - if (((CompessorMapper) obj).isObject()) { - // System.out.println("open {"); - out.append('{'); - needSep = false; - } else if (((CompessorMapper) obj).isArray()) { - // System.out.println("open ["); - out.append('['); - needSep = false; - } - } - -} diff --git a/maxkey-jose-jwt/src/main/java/net/minidev/json/writer/DefaultMapper.java b/maxkey-jose-jwt/src/main/java/net/minidev/json/writer/DefaultMapper.java deleted file mode 100644 index a3cf49d7e..000000000 --- a/maxkey-jose-jwt/src/main/java/net/minidev/json/writer/DefaultMapper.java +++ /dev/null @@ -1,63 +0,0 @@ -package net.minidev.json.writer; - -/* - * Copyright 2011-2014 JSON-SMART authors - * - * 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. - */ -import net.minidev.json.JSONArray; -import net.minidev.json.JSONAwareEx; -import net.minidev.json.JSONObject; -/** - * Simple Reader Class for generic Map - * - * @author uriel - * - * @param - */ -public class DefaultMapper extends JsonReaderI { - protected DefaultMapper(JsonReader base) { - super(base); - } - - @Override - public JsonReaderI startObject(String key) { - return base.DEFAULT; - } - - @Override - public JsonReaderI startArray(String key) { - return base.DEFAULT; - } - - @Override - public Object createObject() { - return new JSONObject(); - } - - @Override - public Object createArray() { - return new JSONArray(); - } - - @Override - public void setValue(Object current, String key, Object value) { - ((JSONObject) current).put(key, value); - } - - @Override - public void addValue(Object current, Object value) { - ((JSONArray) current).add(value); - } - -} diff --git a/maxkey-jose-jwt/src/main/java/net/minidev/json/writer/DefaultMapperCollection.java b/maxkey-jose-jwt/src/main/java/net/minidev/json/writer/DefaultMapperCollection.java deleted file mode 100644 index 315217f63..000000000 --- a/maxkey-jose-jwt/src/main/java/net/minidev/json/writer/DefaultMapperCollection.java +++ /dev/null @@ -1,74 +0,0 @@ -package net.minidev.json.writer; - -/* - * Copyright 2011 JSON-SMART authors - * - * 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. - */ -import java.lang.reflect.Constructor; -import java.util.List; -import java.util.Map; - -public class DefaultMapperCollection extends JsonReaderI { - Class clz; - //? extends Collection - public DefaultMapperCollection(JsonReader base, Class clz) { - super(base); - this.clz = clz; - } - - // public static AMapper DEFAULT = new - // DefaultMapperCollection(); - @Override - public JsonReaderI startObject(String key) { - return this; - } - - @Override - public JsonReaderI startArray(String key) { - return this; - } - - @Override - public Object createObject() { - try { - Constructor c = clz.getConstructor(); - return c.newInstance(); - } catch (Exception e) { - return null; - } - } - - @Override - public Object createArray() { - try { - Constructor c = clz.getConstructor(); - return c.newInstance(); - } catch (Exception e) { - return null; - } - } - - @SuppressWarnings({ "unchecked"}) - @Override - public void setValue(Object current, String key, Object value) { - ((Map) current).put(key, value); - } - - @SuppressWarnings("unchecked") - @Override - public void addValue(Object current, Object value) { - ((List) current).add(value); - } - -} diff --git a/maxkey-jose-jwt/src/main/java/net/minidev/json/writer/DefaultMapperOrdered.java b/maxkey-jose-jwt/src/main/java/net/minidev/json/writer/DefaultMapperOrdered.java deleted file mode 100644 index 044b78853..000000000 --- a/maxkey-jose-jwt/src/main/java/net/minidev/json/writer/DefaultMapperOrdered.java +++ /dev/null @@ -1,58 +0,0 @@ -package net.minidev.json.writer; - -/* - * Copyright 2011 JSON-SMART authors - * - * 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. - */ -import java.util.LinkedHashMap; -import java.util.Map; - -import net.minidev.json.JSONArray; -import net.minidev.json.JSONAwareEx; - -public class DefaultMapperOrdered extends JsonReaderI { - protected DefaultMapperOrdered(JsonReader base) { - super(base); - }; - - @Override - public JsonReaderI startObject(String key) { - return base.DEFAULT_ORDERED; - } - - @Override - public JsonReaderI startArray(String key) { - return base.DEFAULT_ORDERED; - } - - @SuppressWarnings("unchecked") - public void setValue(Object current, String key, Object value) { - ((Map) current).put(key, value); - } - - @Override - public Object createObject() { - return new LinkedHashMap(); - } - - @Override - public void addValue(Object current, Object value) { - ((JSONArray) current).add(value); - } - - @Override - public Object createArray() { - return new JSONArray(); - } -} diff --git a/maxkey-jose-jwt/src/main/java/net/minidev/json/writer/FakeMapper.java b/maxkey-jose-jwt/src/main/java/net/minidev/json/writer/FakeMapper.java deleted file mode 100644 index fc75af0f9..000000000 --- a/maxkey-jose-jwt/src/main/java/net/minidev/json/writer/FakeMapper.java +++ /dev/null @@ -1,54 +0,0 @@ -package net.minidev.json.writer; - - -/* - * Copyright 2011 JSON-SMART authors - * - * 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. - */ - -public class FakeMapper extends JsonReaderI { - private FakeMapper() { - super(null); - } - - public static JsonReaderI DEFAULT = new FakeMapper(); - - @Override - public JsonReaderI startObject(String key) { - return this; - } - - @Override - public JsonReaderI startArray(String key) { - return this; - } - - @Override - public void setValue(Object current, String key, Object value) { - } - - @Override - public void addValue(Object current, Object value) { - } - - @Override - public Object createObject() { - return null; - } - - @Override - public Object createArray() { - return null; - } -} diff --git a/maxkey-jose-jwt/src/main/java/net/minidev/json/writer/JsonReader.java b/maxkey-jose-jwt/src/main/java/net/minidev/json/writer/JsonReader.java deleted file mode 100644 index 61bc88988..000000000 --- a/maxkey-jose-jwt/src/main/java/net/minidev/json/writer/JsonReader.java +++ /dev/null @@ -1,155 +0,0 @@ -package net.minidev.json.writer; - -/* - * Copyright 2011 JSON-SMART authors - * - * 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. - */ -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.util.Date; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import net.minidev.json.JSONArray; -import net.minidev.json.JSONAware; -import net.minidev.json.JSONAwareEx; -import net.minidev.json.JSONObject; - -public class JsonReader { - private final ConcurrentHashMap> cache; - - public JsonReaderI DEFAULT; - public JsonReaderI DEFAULT_ORDERED; - - public JsonReader() { - cache = new ConcurrentHashMap>(100); - - cache.put(Date.class, BeansMapper.MAPPER_DATE); - - cache.put(int[].class, ArraysMapper.MAPPER_PRIM_INT); - cache.put(Integer[].class, ArraysMapper.MAPPER_INT); - - cache.put(short[].class, ArraysMapper.MAPPER_PRIM_INT); - cache.put(Short[].class, ArraysMapper.MAPPER_INT); - - cache.put(long[].class, ArraysMapper.MAPPER_PRIM_LONG); - cache.put(Long[].class, ArraysMapper.MAPPER_LONG); - - cache.put(byte[].class, ArraysMapper.MAPPER_PRIM_BYTE); - cache.put(Byte[].class, ArraysMapper.MAPPER_BYTE); - - cache.put(char[].class, ArraysMapper.MAPPER_PRIM_CHAR); - cache.put(Character[].class, ArraysMapper.MAPPER_CHAR); - - cache.put(float[].class, ArraysMapper.MAPPER_PRIM_FLOAT); - cache.put(Float[].class, ArraysMapper.MAPPER_FLOAT); - - cache.put(double[].class, ArraysMapper.MAPPER_PRIM_DOUBLE); - cache.put(Double[].class, ArraysMapper.MAPPER_DOUBLE); - - cache.put(boolean[].class, ArraysMapper.MAPPER_PRIM_BOOL); - cache.put(Boolean[].class, ArraysMapper.MAPPER_BOOL); - - this.DEFAULT = new DefaultMapper(this); - this.DEFAULT_ORDERED = new DefaultMapperOrdered(this); - - cache.put(JSONAwareEx.class, this.DEFAULT); - cache.put(JSONAware.class, this.DEFAULT); - cache.put(JSONArray.class, this.DEFAULT); - cache.put(JSONObject.class, this.DEFAULT); - } - - /** - * remap field name in custom classes - * - * @param fromJson - * field name in json - * @param toJava - * field name in Java - * @since 2.1.1 - */ - public void remapField(Class type, String fromJson, String toJava) { - JsonReaderI map = this.getMapper(type); - if (!(map instanceof MapperRemapped)) { - map = new MapperRemapped(map); - registerReader(type, map); - } - ((MapperRemapped) map).renameField(fromJson, toJava); - } - - public void registerReader(Class type, JsonReaderI mapper) { - cache.put(type, mapper); - } - - @SuppressWarnings("unchecked") - public JsonReaderI getMapper(Type type) { - if (type instanceof ParameterizedType) - return getMapper((ParameterizedType) type); - return getMapper((Class) type); - } - - /** - * Get the corresponding mapper Class, or create it on first call - * - * @param type - * to be map - */ - public JsonReaderI getMapper(Class type) { - // look for cached Mapper - @SuppressWarnings("unchecked") - JsonReaderI map = (JsonReaderI) cache.get(type); - if (map != null) - return map; - /* - * Special handle - */ - if (type instanceof Class) { - if (Map.class.isAssignableFrom(type)) - map = new DefaultMapperCollection(this, type); - else if (List.class.isAssignableFrom(type)) - map = new DefaultMapperCollection(this, type); - if (map != null) { - cache.put(type, map); - return map; - } - } - - if (type.isArray()) - map = new ArraysMapper.GenericMapper(this, type); - else if (List.class.isAssignableFrom(type)) - map = new CollectionMapper.ListClass(this, type); - else if (Map.class.isAssignableFrom(type)) - map = new CollectionMapper.MapClass(this, type); - else - // use bean class - map = new BeansMapper.Bean(this, type); - cache.putIfAbsent(type, map); - return map; - } - - @SuppressWarnings("unchecked") - public JsonReaderI getMapper(ParameterizedType type) { - JsonReaderI map = (JsonReaderI) cache.get(type); - if (map != null) - return map; - Class clz = (Class) type.getRawType(); - if (List.class.isAssignableFrom(clz)) - map = new CollectionMapper.ListType(this, type); - else if (Map.class.isAssignableFrom(clz)) - map = new CollectionMapper.MapType(this, type); - cache.putIfAbsent(type, map); - return map; - } -} diff --git a/maxkey-jose-jwt/src/main/java/net/minidev/json/writer/JsonReaderI.java b/maxkey-jose-jwt/src/main/java/net/minidev/json/writer/JsonReaderI.java deleted file mode 100644 index db54df75a..000000000 --- a/maxkey-jose-jwt/src/main/java/net/minidev/json/writer/JsonReaderI.java +++ /dev/null @@ -1,110 +0,0 @@ -package net.minidev.json.writer; - -/* - * Copyright 2011 JSON-SMART authors - * - * 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. - */ -import java.io.IOException; -import java.lang.reflect.Type; - -import net.minidev.json.parser.ParseException; - -/** - * Default datatype mapper use by Json-smart ton store data. - * - * @author uriel Chemouni - * - * @param - */ -public abstract class JsonReaderI { - public final JsonReader base; - - /** - * Reader can be link to the JsonReader Base - * - * @param base - */ - public JsonReaderI(JsonReader base) { - this.base = base; - } - - private static String ERR_MSG = "Invalid or non Implemented status"; - - /** - * called when json-smart parser meet an object key - */ - public JsonReaderI startObject(String key) throws ParseException, IOException { - throw new RuntimeException(ERR_MSG + " startObject(String key) in " + this.getClass() + " key=" + key); - } - - /** - * called when json-smart parser start an array. - * - * @param key - * the destination key name, or null. - */ - public JsonReaderI startArray(String key) throws ParseException, IOException { - throw new RuntimeException(ERR_MSG + " startArray in " + this.getClass() + " key=" + key); - } - - /** - * called when json-smart done parsing a value - */ - public void setValue(Object current, String key, Object value) throws ParseException, IOException { - throw new RuntimeException(ERR_MSG + " setValue in " + this.getClass() + " key=" + key); - } - - /** - * ------------- - */ - public Object getValue(Object current, String key) { - throw new RuntimeException(ERR_MSG + " getValue(Object current, String key) in " + this.getClass() + " key=" + key); - } - - // Object current, - public Type getType(String key) { - throw new RuntimeException(ERR_MSG + " getType(String key) in " + this.getClass() + " key=" + key); - } - - /** - * add a value in an array json object. - */ - public void addValue(Object current, Object value) throws ParseException, IOException { - throw new RuntimeException(ERR_MSG + " addValue(Object current, Object value) in " + this.getClass()); - } - - /** - * use to instantiate a new object that will be used as an object - */ - public Object createObject() { - throw new RuntimeException(ERR_MSG + " createObject() in " + this.getClass()); - } - - /** - * use to instantiate a new object that will be used as an array - */ - public Object createArray() { - throw new RuntimeException(ERR_MSG + " createArray() in " + this.getClass()); - } - - /** - * Allow a mapper to converte a temprary structure to the final data format. - * - * example: convert an List<Integer> to an int[] - */ - @SuppressWarnings("unchecked") - public T convert(Object current) { - return (T) current; - } -} diff --git a/maxkey-jose-jwt/src/main/java/net/minidev/json/writer/MapperRemapped.java b/maxkey-jose-jwt/src/main/java/net/minidev/json/writer/MapperRemapped.java deleted file mode 100644 index 970527978..000000000 --- a/maxkey-jose-jwt/src/main/java/net/minidev/json/writer/MapperRemapped.java +++ /dev/null @@ -1,71 +0,0 @@ -package net.minidev.json.writer; - -import java.io.IOException; -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.Map; - -import net.minidev.json.parser.ParseException; - -/** - * Simple solution to supporr on read filed renaming - * - * @author uriel - * - * @param - */ -public class MapperRemapped extends JsonReaderI { - private Map rename; - private JsonReaderI parent; - - public MapperRemapped(JsonReaderI parent) { - super(parent.base); - this.parent = parent; - this.rename = new HashMap(); - } - - public void renameField(String source, String dest) { - rename.put(source, dest); - } - - private String rename(String key) { - String k2 = rename.get(key); - if (k2 != null) - return k2; - return key; - } - - @Override - public void setValue(Object current, String key, Object value) throws ParseException, IOException { - key = rename(key); - parent.setValue(current, key, value); - } - - public Object getValue(Object current, String key) { - key = rename(key); - return parent.getValue(current, key); - } - - @Override - public Type getType(String key) { - key = rename(key); - return parent.getType(key); - } - - @Override - public JsonReaderI startArray(String key) throws ParseException, IOException { - key = rename(key); - return parent.startArray(key); - } - - @Override - public JsonReaderI startObject(String key) throws ParseException, IOException { - key = rename(key); - return parent.startObject(key); - } - - @Override - public Object createObject() { - return parent.createObject(); - } -} diff --git a/maxkey-jose-jwt/src/main/java/net/minidev/json/writer/UpdaterMapper.java b/maxkey-jose-jwt/src/main/java/net/minidev/json/writer/UpdaterMapper.java deleted file mode 100644 index 8c8cd2f19..000000000 --- a/maxkey-jose-jwt/src/main/java/net/minidev/json/writer/UpdaterMapper.java +++ /dev/null @@ -1,94 +0,0 @@ -package net.minidev.json.writer; - -import java.io.IOException; -import java.lang.reflect.Type; - -import net.minidev.json.parser.ParseException; - -public class UpdaterMapper extends JsonReaderI { - final T obj; - final JsonReaderI mapper; - - public UpdaterMapper(JsonReader base, T obj) { - super(base); - if (obj == null) - throw new NullPointerException("can not update null Object"); - this.obj = obj; - this.mapper = (JsonReaderI) base.getMapper(obj.getClass()); - } - - public UpdaterMapper(JsonReader base, T obj, Type type) { - super(base); - if (obj == null) - throw new NullPointerException("can not update null Object"); - this.obj = obj; - this.mapper = (JsonReaderI) base.getMapper(type); - } - - /** - * called when json-smart parser meet an object key - */ - public JsonReaderI startObject(String key) throws ParseException, IOException { - Object bean = mapper.getValue(obj, key); - if (bean == null) - return mapper.startObject(key); - return new UpdaterMapper(base, bean, mapper.getType(key)); - } - - /** - * called when json-smart parser start an array. - * - * @param key - * the destination key name, or null. - */ - public JsonReaderI startArray(String key) throws ParseException, IOException { - // if (obj != null) - return mapper.startArray(key); - } - - /** - * called when json-smart done parsing a value - */ - public void setValue(Object current, String key, Object value) throws ParseException, IOException { - // if (obj != null) - mapper.setValue(current, key, value); - } - - /** - * add a value in an array json object. - */ - public void addValue(Object current, Object value) throws ParseException, IOException { - // if (obj != null) - mapper.addValue(current, value); - } - - /** - * use to instantiate a new object that will be used as an object - */ - public Object createObject() { - if (obj != null) - return obj; - return mapper.createObject(); - } - - /** - * use to instantiate a new object that will be used as an array - */ - public Object createArray() { - if (obj != null) - return obj; - return mapper.createArray(); - } - - /** - * Allow a mapper to converte a temprary structure to the final data format. - * - * example: convert an List<Integer> to an int[] - */ - @SuppressWarnings("unchecked") - public T convert(Object current) { - if (obj != null) - return obj; - return (T) mapper.convert(current); - } -} diff --git a/maxkey-protocols/maxkey-protocol-authorize/build.gradle b/maxkey-protocols/maxkey-protocol-authorize/build.gradle index bf5e08612..7b4a84e64 100644 --- a/maxkey-protocols/maxkey-protocol-authorize/build.gradle +++ b/maxkey-protocols/maxkey-protocol-authorize/build.gradle @@ -8,7 +8,6 @@ dependencies { compile project(":maxkey-core") compile project(":maxkey-dao") - compile project(":maxkey-jose-jwt") compile project(":maxkey-client-sdk") //compileOnly project(":maxkey-protocols:maxkey-protocol-oauth-2.0") //compileOnly project(":maxkey-protocols:maxkey-protocol-saml-2.0") diff --git a/maxkey-protocols/maxkey-protocol-cas/build.gradle b/maxkey-protocols/maxkey-protocol-cas/build.gradle index 65a23b5db..9fa26f842 100644 --- a/maxkey-protocols/maxkey-protocol-cas/build.gradle +++ b/maxkey-protocols/maxkey-protocol-cas/build.gradle @@ -8,7 +8,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-authorize") diff --git a/maxkey-protocols/maxkey-protocol-desktop/build.gradle b/maxkey-protocols/maxkey-protocol-desktop/build.gradle index a2b3e5c94..b7d588c71 100644 --- a/maxkey-protocols/maxkey-protocol-desktop/build.gradle +++ b/maxkey-protocols/maxkey-protocol-desktop/build.gradle @@ -8,7 +8,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-authorize") diff --git a/maxkey-protocols/maxkey-protocol-extendapi/build.gradle b/maxkey-protocols/maxkey-protocol-extendapi/build.gradle index 78cc14148..3fe274ce0 100644 --- a/maxkey-protocols/maxkey-protocol-extendapi/build.gradle +++ b/maxkey-protocols/maxkey-protocol-extendapi/build.gradle @@ -8,7 +8,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-authorize") } \ No newline at end of file diff --git a/maxkey-protocols/maxkey-protocol-formbased/build.gradle b/maxkey-protocols/maxkey-protocol-formbased/build.gradle index 33911c380..3e2d4f8c6 100644 --- a/maxkey-protocols/maxkey-protocol-formbased/build.gradle +++ b/maxkey-protocols/maxkey-protocol-formbased/build.gradle @@ -8,7 +8,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-authorize") diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/build.gradle b/maxkey-protocols/maxkey-protocol-oauth-2.0/build.gradle index 7e9ae1f79..a3e605964 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/build.gradle +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/build.gradle @@ -6,7 +6,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-authorize") diff --git a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/maxkey/authz/oauth2/provider/userinfo/endpoint/UserInfoEndpoint.java b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/maxkey/authz/oauth2/provider/userinfo/endpoint/UserInfoEndpoint.java index 45c63c68b..310a8d1b5 100644 --- a/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/maxkey/authz/oauth2/provider/userinfo/endpoint/UserInfoEndpoint.java +++ b/maxkey-protocols/maxkey-protocol-oauth-2.0/src/main/java/org/maxkey/authz/oauth2/provider/userinfo/endpoint/UserInfoEndpoint.java @@ -44,6 +44,7 @@ import com.nimbusds.jose.JWSHeader; import com.nimbusds.jwt.EncryptedJWT; import com.nimbusds.jwt.JWT; import com.nimbusds.jwt.JWTClaimsSet; +import com.nimbusds.jwt.JWTClaimsSet.Builder; import com.nimbusds.jwt.SignedJWT; @Controller @@ -144,20 +145,20 @@ public class UserInfoEndpoint { UserInfo userInfo=queryUserInfo(principal); String userJson=""; - HashMap claimsFields = new HashMap(); + Builder jwtClaimsSetBuilder= new JWTClaimsSet.Builder(); - claimsFields.put("sub", userInfo.getId()); + jwtClaimsSetBuilder.claim("sub", userInfo.getId()); if(scopes.contains("profile")){ - claimsFields.put("name", userInfo.getUsername()); - claimsFields.put("preferred_username", userInfo.getDisplayName()); - claimsFields.put("given_name", userInfo.getGivenName()); - claimsFields.put("family_name", userInfo.getFamilyName()); - claimsFields.put("middle_name", userInfo.getMiddleName()); - claimsFields.put("nickname", userInfo.getNickName()); - claimsFields.put("profile", "profile"); - claimsFields.put("picture", "picture"); - claimsFields.put("website", userInfo.getWebSite()); + jwtClaimsSetBuilder.claim("name", userInfo.getUsername()); + jwtClaimsSetBuilder.claim("preferred_username", userInfo.getDisplayName()); + jwtClaimsSetBuilder.claim("given_name", userInfo.getGivenName()); + jwtClaimsSetBuilder.claim("family_name", userInfo.getFamilyName()); + jwtClaimsSetBuilder.claim("middle_name", userInfo.getMiddleName()); + jwtClaimsSetBuilder.claim("nickname", userInfo.getNickName()); + jwtClaimsSetBuilder.claim("profile", "profile"); + jwtClaimsSetBuilder.claim("picture", "picture"); + jwtClaimsSetBuilder.claim("website", userInfo.getWebSite()); String gender; switch(userInfo.getGender()){ @@ -168,21 +169,21 @@ public class UserInfoEndpoint { default: gender="unknown"; } - claimsFields.put("gender", gender); - claimsFields.put("zoneinfo", userInfo.getTimeZone()); - claimsFields.put("locale", userInfo.getLocale()); - claimsFields.put("updated_time", userInfo.getModifiedDate()); - claimsFields.put("birthdate", userInfo.getBirthDate()); + jwtClaimsSetBuilder.claim("gender", gender); + jwtClaimsSetBuilder.claim("zoneinfo", userInfo.getTimeZone()); + jwtClaimsSetBuilder.claim("locale", userInfo.getLocale()); + jwtClaimsSetBuilder.claim("updated_time", userInfo.getModifiedDate()); + jwtClaimsSetBuilder.claim("birthdate", userInfo.getBirthDate()); } if(scopes.contains("email")){ - claimsFields.put("email", userInfo.getWorkEmail()); - claimsFields.put("email_verified", false); + jwtClaimsSetBuilder.claim("email", userInfo.getWorkEmail()); + jwtClaimsSetBuilder.claim("email_verified", false); } if(scopes.contains("phone")){ - claimsFields.put("phone_number", userInfo.getWorkPhoneNumber()); - claimsFields.put("phone_number_verified", false); + jwtClaimsSetBuilder.claim("phone_number", userInfo.getWorkPhoneNumber()); + jwtClaimsSetBuilder.claim("phone_number_verified", false); } if(scopes.contains("address")){ @@ -194,18 +195,16 @@ public class UserInfoEndpoint { addressFields.put("formatted", userInfo.getWorkAddressFormatted()); addressFields.put("postal_code", userInfo.getWorkPostalCode()); - claimsFields.put("address", addressFields); + jwtClaimsSetBuilder.claim("address", addressFields); } - JWTClaimsSet userInfoJWTClaims = new JWTClaimsSet.Builder() + jwtClaimsSetBuilder .jwtID(UUID.randomUUID().toString())// set a random NONCE in the middle of it .audience(Arrays.asList(clientDetails.getClientId())) .issueTime(new Date()) - .expirationTime(new Date(new Date().getTime()+clientDetails.getAccessTokenValiditySeconds()*1000)) - .claim(claimsFields) - .build(); - + .expirationTime(new Date(new Date().getTime()+clientDetails.getAccessTokenValiditySeconds()*1000)); + JWTClaimsSet userInfoJWTClaims = jwtClaimsSetBuilder.build(); JWT userInfoJWT=null; JWSAlgorithm signingAlg = jwtSignerValidationService.getDefaultSigningAlgorithm(); if (clientDetails.getUserInfoEncryptedAlgorithm() != null && !clientDetails.getUserInfoEncryptedAlgorithm().equals("none") @@ -232,7 +231,7 @@ public class UserInfoEndpoint { if (clientDetails.getUserInfoSigningAlgorithm()==null||clientDetails.getUserInfoSigningAlgorithm().equals("none")) { // unsigned ID token //userInfoJWT = new PlainJWT(userInfoJWTClaims); - userJson=JsonUtils.gson2Json(claimsFields); + userJson=JsonUtils.gson2Json(jwtClaimsSetBuilder.getClaims()); } else { // signed ID token if (signingAlg.equals(JWSAlgorithm.HS256) diff --git a/maxkey-protocols/maxkey-protocol-tokenbased/build.gradle b/maxkey-protocols/maxkey-protocol-tokenbased/build.gradle index 9a40e0991..9f6876e95 100644 --- a/maxkey-protocols/maxkey-protocol-tokenbased/build.gradle +++ b/maxkey-protocols/maxkey-protocol-tokenbased/build.gradle @@ -8,7 +8,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-authorize") diff --git a/maxkey-web-manage/build.gradle b/maxkey-web-manage/build.gradle index 3bf73a606..2fb895ac6 100644 --- a/maxkey-web-manage/build.gradle +++ b/maxkey-web-manage/build.gradle @@ -18,7 +18,6 @@ buildscript { dependencies { compile project(":maxkey-core") - compile project(":maxkey-jose-jwt") compile project(":maxkey-dao") compile project(":maxkey-client-sdk") compile project(":maxkey-protocols:maxkey-protocol-oauth-2.0") diff --git a/maxkey-web-manage/src/main/resources/application.properties b/maxkey-web-manage/src/main/resources/application.properties index 8615ec1c9..6806d9744 100644 --- a/maxkey-web-manage/src/main/resources/application.properties +++ b/maxkey-web-manage/src/main/resources/application.properties @@ -7,7 +7,7 @@ server.servlet.context-path=/maxkey-mgt application.name=MaxKey-Mgt #message.properties global.application.version is need to update -application.formatted-version=v1.2 GA +application.formatted-version=v1.2.1 GA #for freemarker spring.freemarker.template-loader-path=classpath:/templates/views diff --git a/maxkey-web-manage/src/main/resources/messages/message.properties b/maxkey-web-manage/src/main/resources/messages/message.properties index 53aaf66e6..f8d4c90fd 100644 --- a/maxkey-web-manage/src/main/resources/messages/message.properties +++ b/maxkey-web-manage/src/main/resources/messages/message.properties @@ -1,5 +1,5 @@ global.application=MaxKey\u5E94\u7528\u5B89\u5168\u7BA1\u7406\u7CFB\u7EDF -global.application.version=v1.2 GA +global.application.version=v1.2.1 GA global.change.language=\u8BED\u97F3\u9009\u62E9 global.change.language.en=English global.change.language.zh=\u4E2D\u6587 diff --git a/maxkey-web-manage/src/main/resources/messages/message_en.properties b/maxkey-web-manage/src/main/resources/messages/message_en.properties index e91da731a..c6ff9a245 100644 --- a/maxkey-web-manage/src/main/resources/messages/message_en.properties +++ b/maxkey-web-manage/src/main/resources/messages/message_en.properties @@ -1,5 +1,5 @@ global.application=MaxKey Secure Management -global.application.version=v1.2 GA +global.application.version=v1.2.1 GA global.change.language=Language global.change.language.en=English global.change.language.zh=\u4E2D\u6587 diff --git a/maxkey-web-maxkey/build.gradle b/maxkey-web-maxkey/build.gradle index 6558aeaca..91e426d36 100644 --- a/maxkey-web-maxkey/build.gradle +++ b/maxkey-web-maxkey/build.gradle @@ -19,7 +19,6 @@ buildscript { dependencies { compile project(":maxkey-core") compile project(":maxkey-dao") - compile project(":maxkey-jose-jwt") compile project(":maxkey-client-sdk") compile project(":maxkey-authentications") diff --git a/maxkey-web-maxkey/src/main/java/org/maxkey/MaxKeyConfig.java b/maxkey-web-maxkey/src/main/java/org/maxkey/MaxKeyConfig.java index b34fc703e..4dddc602f 100644 --- a/maxkey-web-maxkey/src/main/java/org/maxkey/MaxKeyConfig.java +++ b/maxkey-web-maxkey/src/main/java/org/maxkey/MaxKeyConfig.java @@ -62,30 +62,31 @@ public class MaxKeyConfig { }; } - @Bean - public Connector connector(){ - Connector connector=new Connector("org.apache.coyote.http11.Http11NioProtocol"); - connector.setScheme("http"); - connector.setPort(80); - connector.setSecure(false); - connector.setRedirectPort(443); - return connector; - } + @Bean + public Connector connector() { + Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol"); + connector.setScheme("http"); + connector.setPort(80); + connector.setSecure(false); + connector.setRedirectPort(443); + return connector; + } + + @Bean + public TomcatServletWebServerFactory tomcatServletWebServerFactory(Connector connector) { + TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() { + @Override + protected void postProcessContext(Context context) { + SecurityConstraint securityConstraint = new SecurityConstraint(); + securityConstraint.setUserConstraint("CONFIDENTIAL"); + SecurityCollection collection = new SecurityCollection(); + collection.addPattern("/*"); + securityConstraint.addCollection(collection); + context.addConstraint(securityConstraint); + } + }; + tomcat.addAdditionalTomcatConnectors(connector); + return tomcat; + } - @Bean - public TomcatServletWebServerFactory tomcatServletWebServerFactory(Connector connector){ - TomcatServletWebServerFactory tomcat=new TomcatServletWebServerFactory(){ - @Override - protected void postProcessContext(Context context) { - SecurityConstraint securityConstraint=new SecurityConstraint(); - securityConstraint.setUserConstraint("CONFIDENTIAL"); - SecurityCollection collection=new SecurityCollection(); - collection.addPattern("/*"); - securityConstraint.addCollection(collection); - context.addConstraint(securityConstraint); - } - }; - tomcat.addAdditionalTomcatConnectors(connector); - return tomcat; - } } diff --git a/maxkey-web-maxkey/src/main/resources/application.properties b/maxkey-web-maxkey/src/main/resources/application.properties index 15d4979f5..c3365b868 100644 --- a/maxkey-web-maxkey/src/main/resources/application.properties +++ b/maxkey-web-maxkey/src/main/resources/application.properties @@ -15,7 +15,7 @@ server.servlet.context-path=/maxkey application.name=MaxKey #message.properties global.application.version is need to update -application.formatted-version=v1.2 GA +application.formatted-version=v1.2.1 GA #for freemarker spring.freemarker.template-loader-path=classpath:/templates/views diff --git a/maxkey-web-maxkey/src/main/resources/messages/message.properties b/maxkey-web-maxkey/src/main/resources/messages/message.properties index 990b3d64b..815cb7fa2 100644 --- a/maxkey-web-maxkey/src/main/resources/messages/message.properties +++ b/maxkey-web-maxkey/src/main/resources/messages/message.properties @@ -1,5 +1,5 @@ global.application=MaxKey\u5E94\u7528\u5B89\u5168\u7CFB\u7EDF -global.application.version=v1.2 GA +global.application.version=v1.2.1 GA global.change.language=\u8BED\u97F3\u9009\u62E9 global.change.language.en=English global.change.language.zh=\u4E2D\u6587 diff --git a/maxkey-web-maxkey/src/main/resources/messages/message_en.properties b/maxkey-web-maxkey/src/main/resources/messages/message_en.properties index 8278195f0..90096e1da 100644 --- a/maxkey-web-maxkey/src/main/resources/messages/message_en.properties +++ b/maxkey-web-maxkey/src/main/resources/messages/message_en.properties @@ -1,5 +1,5 @@ global.application=MaxKey Secure Sign-on System -global.application.version=v1.2 GA +global.application.version=v1.2.1 GA global.change.language=Language global.change.language.en=English global.change.language.zh=\u4E2D\u6587 diff --git a/settings.gradle b/settings.gradle index 390031523..55aae80be 100644 --- a/settings.gradle +++ b/settings.gradle @@ -7,7 +7,7 @@ rootProject.name = 'MaxKey' include 'maxkey-client-sdk' include 'maxkey-core' include 'maxkey-dao' -include 'maxkey-jose-jwt' +//include 'maxkey-jose-jwt' include 'maxkey-authentications' -- GitLab