use of org.xdi.oxauth.model.exception.InvalidJweException in project oxAuth by GluuFederation.
the class IdTokenFactory method generateEncryptedIdToken.
public Jwe generateEncryptedIdToken(IAuthorizationGrant authorizationGrant, String nonce, AuthorizationCode authorizationCode, AccessToken accessToken, Set<String> scopes, boolean includeIdTokenClaims) throws Exception {
Jwe jwe = new Jwe();
// Header
KeyEncryptionAlgorithm keyEncryptionAlgorithm = KeyEncryptionAlgorithm.fromName(authorizationGrant.getClient().getIdTokenEncryptedResponseAlg());
BlockEncryptionAlgorithm blockEncryptionAlgorithm = BlockEncryptionAlgorithm.fromName(authorizationGrant.getClient().getIdTokenEncryptedResponseEnc());
jwe.getHeader().setType(JwtType.JWT);
jwe.getHeader().setAlgorithm(keyEncryptionAlgorithm);
jwe.getHeader().setEncryptionMethod(blockEncryptionAlgorithm);
// Claims
jwe.getClaims().setIssuer(appConfiguration.getIssuer());
jwe.getClaims().setAudience(authorizationGrant.getClient().getClientId());
int lifeTime = appConfiguration.getIdTokenLifetime();
Calendar calendar = Calendar.getInstance();
Date issuedAt = calendar.getTime();
calendar.add(Calendar.SECOND, lifeTime);
Date expiration = calendar.getTime();
jwe.getClaims().setExpirationTime(expiration);
jwe.getClaims().setIssuedAt(issuedAt);
if (authorizationGrant.getAcrValues() != null) {
jwe.getClaims().setClaim(JwtClaimName.AUTHENTICATION_CONTEXT_CLASS_REFERENCE, authorizationGrant.getAcrValues());
setAmrClaim(jwe, authorizationGrant.getAcrValues());
}
if (StringUtils.isNotBlank(nonce)) {
jwe.getClaims().setClaim(JwtClaimName.NONCE, nonce);
}
if (authorizationGrant.getAuthenticationTime() != null) {
jwe.getClaims().setClaim(JwtClaimName.AUTHENTICATION_TIME, authorizationGrant.getAuthenticationTime());
}
if (authorizationCode != null) {
String codeHash = authorizationCode.getHash(null);
jwe.getClaims().setClaim(JwtClaimName.CODE_HASH, codeHash);
}
if (accessToken != null) {
String accessTokenHash = accessToken.getHash(null);
jwe.getClaims().setClaim(JwtClaimName.ACCESS_TOKEN_HASH, accessTokenHash);
}
jwe.getClaims().setClaim(JwtClaimName.OX_OPENID_CONNECT_VERSION, appConfiguration.getOxOpenIdConnectVersion());
List<org.xdi.oxauth.model.common.Scope> dynamicScopes = Lists.newArrayList();
if (includeIdTokenClaims) {
for (String scopeName : scopes) {
org.xdi.oxauth.model.common.Scope scope = scopeService.getScopeByDisplayName(scopeName);
if (org.xdi.oxauth.model.common.ScopeType.DYNAMIC == scope.getScopeType()) {
dynamicScopes.add(scope);
continue;
}
if (scope != null && scope.getOxAuthClaims() != null) {
for (String claimDn : scope.getOxAuthClaims()) {
GluuAttribute gluuAttribute = attributeService.getAttributeByDn(claimDn);
String claimName = gluuAttribute.getOxAuthClaimName();
String ldapName = gluuAttribute.getName();
String attributeValue;
if (StringUtils.isNotBlank(claimName) && StringUtils.isNotBlank(ldapName)) {
if (ldapName.equals("uid")) {
attributeValue = authorizationGrant.getUser().getUserId();
} else {
attributeValue = authorizationGrant.getUser().getAttribute(gluuAttribute.getName());
}
jwe.getClaims().setClaim(claimName, attributeValue);
}
}
}
}
}
if (authorizationGrant.getJwtAuthorizationRequest() != null && authorizationGrant.getJwtAuthorizationRequest().getIdTokenMember() != null) {
for (Claim claim : authorizationGrant.getJwtAuthorizationRequest().getIdTokenMember().getClaims()) {
// ClaimValueType.OPTIONAL.equals(claim.getClaimValue().getClaimValueType());
boolean optional = true;
GluuAttribute gluuAttribute = attributeService.getByClaimName(claim.getName());
if (gluuAttribute != null) {
String ldapClaimName = gluuAttribute.getName();
Object attribute = authorizationGrant.getUser().getAttribute(ldapClaimName, optional);
if (attribute != null) {
if (attribute instanceof JSONArray) {
JSONArray jsonArray = (JSONArray) attribute;
List<String> values = new ArrayList<String>();
for (int i = 0; i < jsonArray.length(); i++) {
String value = jsonArray.optString(i);
if (value != null) {
values.add(value);
}
}
jwe.getClaims().setClaim(claim.getName(), values);
} else {
String value = (String) attribute;
jwe.getClaims().setClaim(claim.getName(), value);
}
}
}
}
}
// Check for Subject Identifier Type
if (authorizationGrant.getClient().getSubjectType() != null && SubjectType.fromString(authorizationGrant.getClient().getSubjectType()).equals(SubjectType.PAIRWISE)) {
String sectorIdentifierUri;
if (StringUtils.isNotBlank(authorizationGrant.getClient().getSectorIdentifierUri())) {
sectorIdentifierUri = authorizationGrant.getClient().getSectorIdentifierUri();
} else {
sectorIdentifierUri = authorizationGrant.getClient().getRedirectUris()[0];
}
String userInum = authorizationGrant.getUser().getAttribute("inum");
PairwiseIdentifier pairwiseIdentifier = pairwiseIdentifierService.findPairWiseIdentifier(userInum, sectorIdentifierUri);
if (pairwiseIdentifier == null) {
pairwiseIdentifier = new PairwiseIdentifier(sectorIdentifierUri);
pairwiseIdentifier.setId(UUID.randomUUID().toString());
pairwiseIdentifier.setDn(pairwiseIdentifierService.getDnForPairwiseIdentifier(pairwiseIdentifier.getId(), userInum));
pairwiseIdentifierService.addPairwiseIdentifier(userInum, pairwiseIdentifier);
}
jwe.getClaims().setSubjectIdentifier(pairwiseIdentifier.getId());
} else {
String openidSubAttribute = appConfiguration.getOpenidSubAttribute();
if (openidSubAttribute.equals("uid")) {
jwe.getClaims().setSubjectIdentifier(authorizationGrant.getUser().getUserId());
} else {
jwe.getClaims().setSubjectIdentifier(authorizationGrant.getUser().getAttribute(openidSubAttribute));
}
}
if ((dynamicScopes.size() > 0) && externalDynamicScopeService.isEnabled()) {
final UnmodifiableAuthorizationGrant unmodifiableAuthorizationGrant = new UnmodifiableAuthorizationGrant(authorizationGrant);
DynamicScopeExternalContext dynamicScopeContext = new DynamicScopeExternalContext(dynamicScopes, jwe, unmodifiableAuthorizationGrant);
externalDynamicScopeService.executeExternalUpdateMethods(dynamicScopeContext);
}
// Encryption
if (keyEncryptionAlgorithm == KeyEncryptionAlgorithm.RSA_OAEP || keyEncryptionAlgorithm == KeyEncryptionAlgorithm.RSA1_5) {
JSONObject jsonWebKeys = JwtUtil.getJSONWebKeys(authorizationGrant.getClient().getJwksUri());
AbstractCryptoProvider cryptoProvider = CryptoProviderFactory.getCryptoProvider(appConfiguration);
String keyId = cryptoProvider.getKeyId(JSONWebKeySet.fromJSONObject(jsonWebKeys), SignatureAlgorithm.RS256);
PublicKey publicKey = cryptoProvider.getPublicKey(keyId, jsonWebKeys);
if (publicKey != null) {
JweEncrypter jweEncrypter = new JweEncrypterImpl(keyEncryptionAlgorithm, blockEncryptionAlgorithm, publicKey);
jwe = jweEncrypter.encrypt(jwe);
} else {
throw new InvalidJweException("The public key is not valid");
}
} else if (keyEncryptionAlgorithm == KeyEncryptionAlgorithm.A128KW || keyEncryptionAlgorithm == KeyEncryptionAlgorithm.A256KW) {
try {
byte[] sharedSymmetricKey = clientService.decryptSecret(authorizationGrant.getClient().getClientSecret()).getBytes(Util.UTF8_STRING_ENCODING);
JweEncrypter jweEncrypter = new JweEncrypterImpl(keyEncryptionAlgorithm, blockEncryptionAlgorithm, sharedSymmetricKey);
jwe = jweEncrypter.encrypt(jwe);
} catch (UnsupportedEncodingException e) {
throw new InvalidJweException(e);
} catch (StringEncrypter.EncryptionException e) {
throw new InvalidJweException(e);
} catch (Exception e) {
throw new InvalidJweException(e);
}
}
return jwe;
}
use of org.xdi.oxauth.model.exception.InvalidJweException in project oxAuth by GluuFederation.
the class JweDecrypterImpl method decryptEncryptionKey.
@Override
public byte[] decryptEncryptionKey(String encodedEncryptedKey) throws InvalidJweException {
if (getKeyEncryptionAlgorithm() == null) {
throw new InvalidJweException("The key encryption algorithm is null");
}
if (encodedEncryptedKey == null) {
throw new InvalidJweException("The encoded encryption key is null");
}
try {
if (getKeyEncryptionAlgorithm() == KeyEncryptionAlgorithm.RSA_OAEP || getKeyEncryptionAlgorithm() == KeyEncryptionAlgorithm.RSA1_5) {
if (rsaPrivateKey == null && privateKey == null) {
throw new InvalidJweException("The RSA private key is null");
}
//Cipher cipher = Cipher.getInstance(getKeyEncryptionAlgorithm().getAlgorithm(), "BC");
Cipher cipher = Cipher.getInstance(getKeyEncryptionAlgorithm().getAlgorithm());
if (rsaPrivateKey != null) {
KeyFactory keyFactory = KeyFactory.getInstance(getKeyEncryptionAlgorithm().getFamily(), "BC");
RSAPrivateKeySpec privKeySpec = new RSAPrivateKeySpec(rsaPrivateKey.getModulus(), rsaPrivateKey.getPrivateExponent());
java.security.interfaces.RSAPrivateKey privKey = (java.security.interfaces.RSAPrivateKey) keyFactory.generatePrivate(privKeySpec);
cipher.init(Cipher.DECRYPT_MODE, privKey);
} else {
cipher.init(Cipher.DECRYPT_MODE, privateKey);
}
byte[] decryptedKey = cipher.doFinal(Base64Util.base64urldecode(encodedEncryptedKey));
return decryptedKey;
} else if (getKeyEncryptionAlgorithm() == KeyEncryptionAlgorithm.A128KW || getKeyEncryptionAlgorithm() == KeyEncryptionAlgorithm.A256KW) {
if (sharedSymmetricKey == null) {
throw new InvalidJweException("The shared symmetric key is null");
}
if (sharedSymmetricKey.length != 16) {
// 128 bit
MessageDigest sha = MessageDigest.getInstance("SHA-1");
sharedSymmetricKey = sha.digest(sharedSymmetricKey);
sharedSymmetricKey = Arrays.copyOf(sharedSymmetricKey, 16);
}
byte[] encryptedKey = Base64Util.base64urldecode(encodedEncryptedKey);
SecretKeySpec keyEncryptionKey = new SecretKeySpec(sharedSymmetricKey, "AES");
AESWrapEngine aesWrapEngine = new AESWrapEngine();
CipherParameters params = new KeyParameter(keyEncryptionKey.getEncoded());
aesWrapEngine.init(false, params);
byte[] decryptedKey = aesWrapEngine.unwrap(encryptedKey, 0, encryptedKey.length);
return decryptedKey;
} else {
throw new InvalidJweException("The key encryption algorithm is not supported");
}
} catch (NoSuchPaddingException e) {
throw new InvalidJweException(e);
} catch (NoSuchAlgorithmException e) {
throw new InvalidJweException(e);
} catch (IllegalBlockSizeException e) {
throw new InvalidJweException(e);
} catch (BadPaddingException e) {
throw new InvalidJweException(e);
} catch (NoSuchProviderException e) {
throw new InvalidJweException(e);
} catch (InvalidKeyException e) {
throw new InvalidJweException(e);
} catch (InvalidKeySpecException e) {
throw new InvalidJweException(e);
} catch (InvalidCipherTextException e) {
throw new InvalidJweException(e);
}
}
use of org.xdi.oxauth.model.exception.InvalidJweException in project oxAuth by GluuFederation.
the class JweDecrypterImpl method decryptCipherText.
@Override
public String decryptCipherText(String encodedCipherText, byte[] contentMasterKey, byte[] initializationVector, byte[] authenticationTag, byte[] additionalAuthenticatedData) throws InvalidJweException {
if (getBlockEncryptionAlgorithm() == null) {
throw new InvalidJweException("The block encryption algorithm is null");
}
if (contentMasterKey == null) {
throw new InvalidJweException("The content master key (CMK) is null");
}
if (initializationVector == null) {
throw new InvalidJweException("The initialization vector is null");
}
if (authenticationTag == null) {
throw new InvalidJweException("The authentication tag is null");
}
if (additionalAuthenticatedData == null) {
throw new InvalidJweException("The additional authentication data is null");
}
try {
if (getBlockEncryptionAlgorithm() == BlockEncryptionAlgorithm.A128GCM || getBlockEncryptionAlgorithm() == BlockEncryptionAlgorithm.A256GCM) {
final int MAC_SIZE_BITS = 128;
byte[] cipherText = Base64Util.base64urldecode(encodedCipherText);
KeyParameter key = new KeyParameter(contentMasterKey);
AEADParameters aeadParameters = new AEADParameters(key, MAC_SIZE_BITS, initializationVector, additionalAuthenticatedData);
SecretKeySpec sks = new SecretKeySpec(contentMasterKey, "AES");
BlockCipher blockCipher = new AESEngine();
CipherParameters params = new KeyParameter(sks.getEncoded());
blockCipher.init(false, params);
GCMBlockCipher aGCMBlockCipher = new GCMBlockCipher(blockCipher);
aGCMBlockCipher.init(false, aeadParameters);
byte[] input = new byte[cipherText.length + authenticationTag.length];
System.arraycopy(cipherText, 0, input, 0, cipherText.length);
System.arraycopy(authenticationTag, 0, input, cipherText.length, authenticationTag.length);
int len = aGCMBlockCipher.getOutputSize(input.length);
byte[] out = new byte[len];
int outOff = aGCMBlockCipher.processBytes(input, 0, input.length, out, 0);
aGCMBlockCipher.doFinal(out, outOff);
String plaintext = new String(out, Charset.forName(Util.UTF8_STRING_ENCODING));
return plaintext;
} else if (getBlockEncryptionAlgorithm() == BlockEncryptionAlgorithm.A128CBC_PLUS_HS256 || getBlockEncryptionAlgorithm() == BlockEncryptionAlgorithm.A256CBC_PLUS_HS512) {
byte[] cipherText = Base64Util.base64urldecode(encodedCipherText);
byte[] cek = KeyDerivationFunction.generateCek(contentMasterKey, getBlockEncryptionAlgorithm());
Cipher cipher = Cipher.getInstance(getBlockEncryptionAlgorithm().getAlgorithm());
IvParameterSpec ivParameter = new IvParameterSpec(initializationVector);
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(cek, "AES"), ivParameter);
byte[] decodedPlainTextBytes = cipher.doFinal(cipherText);
String decodedPlainText = new String(decodedPlainTextBytes, Charset.forName(Util.UTF8_STRING_ENCODING));
// Integrity check
String securedInputValue = new String(additionalAuthenticatedData, Charset.forName(Util.UTF8_STRING_ENCODING)) + "." + encodedCipherText;
byte[] cik = KeyDerivationFunction.generateCik(contentMasterKey, getBlockEncryptionAlgorithm());
SecretKey secretKey = new SecretKeySpec(cik, getBlockEncryptionAlgorithm().getIntegrityValueAlgorithm());
Mac mac = Mac.getInstance(getBlockEncryptionAlgorithm().getIntegrityValueAlgorithm());
mac.init(secretKey);
byte[] integrityValue = mac.doFinal(securedInputValue.getBytes(Util.UTF8_STRING_ENCODING));
if (!Arrays.equals(integrityValue, authenticationTag)) {
throw new InvalidJweException("The authentication tag is not valid");
}
return decodedPlainText;
} else {
throw new InvalidJweException("The block encryption algorithm is not supported");
}
} catch (InvalidCipherTextException e) {
throw new InvalidJweException(e);
} catch (NoSuchPaddingException e) {
throw new InvalidJweException(e);
} catch (BadPaddingException e) {
throw new InvalidJweException(e);
} catch (InvalidAlgorithmParameterException e) {
throw new InvalidJweException(e);
} catch (NoSuchAlgorithmException e) {
throw new InvalidJweException(e);
} catch (IllegalBlockSizeException e) {
throw new InvalidJweException(e);
} catch (UnsupportedEncodingException e) {
throw new InvalidJweException(e);
} catch (NoSuchProviderException e) {
throw new InvalidJweException(e);
} catch (InvalidKeyException e) {
throw new InvalidJweException(e);
} catch (InvalidParameterException e) {
throw new InvalidJweException(e);
}
}
use of org.xdi.oxauth.model.exception.InvalidJweException in project oxAuth by GluuFederation.
the class JweEncrypterImpl method generateEncryptedKey.
@Override
public String generateEncryptedKey(byte[] contentMasterKey) throws InvalidJweException {
if (getKeyEncryptionAlgorithm() == null) {
throw new InvalidJweException("The key encryption algorithm is null");
}
if (contentMasterKey == null) {
throw new InvalidJweException("The content master key (CMK) is null");
}
try {
if (getKeyEncryptionAlgorithm() == KeyEncryptionAlgorithm.RSA_OAEP || getKeyEncryptionAlgorithm() == KeyEncryptionAlgorithm.RSA1_5) {
if (publicKey != null) {
Cipher cipher = Cipher.getInstance(getKeyEncryptionAlgorithm().getAlgorithm(), "BC");
//Cipher cipher = Cipher.getInstance(getKeyEncryptionAlgorithm().getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encryptedKey = cipher.doFinal(contentMasterKey);
String encodedEncryptedKey = Base64Util.base64urlencode(encryptedKey);
return encodedEncryptedKey;
} else {
throw new InvalidJweException("The RSA public key is null");
}
} else if (getKeyEncryptionAlgorithm() == KeyEncryptionAlgorithm.A128KW || getKeyEncryptionAlgorithm() == KeyEncryptionAlgorithm.A256KW) {
if (sharedSymmetricKey == null) {
throw new InvalidJweException("The shared symmetric key is null");
}
if (sharedSymmetricKey.length != 16) {
// 128 bit
MessageDigest sha = MessageDigest.getInstance("SHA-1");
sharedSymmetricKey = sha.digest(sharedSymmetricKey);
sharedSymmetricKey = Arrays.copyOf(sharedSymmetricKey, 16);
}
SecretKeySpec keyEncryptionKey = new SecretKeySpec(sharedSymmetricKey, "AES");
AESWrapEngine aesWrapEngine = new AESWrapEngine();
CipherParameters params = new KeyParameter(keyEncryptionKey.getEncoded());
aesWrapEngine.init(true, params);
byte[] wrappedKey = aesWrapEngine.wrap(contentMasterKey, 0, contentMasterKey.length);
String encodedEncryptedKey = Base64Util.base64urlencode(wrappedKey);
return encodedEncryptedKey;
} else {
throw new InvalidJweException("The key encryption algorithm is not supported");
}
} catch (NoSuchPaddingException e) {
throw new InvalidJweException(e);
} catch (NoSuchAlgorithmException e) {
throw new InvalidJweException(e);
} catch (IllegalBlockSizeException e) {
throw new InvalidJweException(e);
} catch (BadPaddingException e) {
throw new InvalidJweException(e);
} catch (InvalidKeyException e) {
throw new InvalidJweException(e);
} catch (NoSuchProviderException e) {
throw new InvalidJweException(e);
}
}
use of org.xdi.oxauth.model.exception.InvalidJweException in project oxAuth by GluuFederation.
the class AbstractJweEncrypter method encrypt.
@Override
public Jwe encrypt(Jwe jwe) throws InvalidJweException {
try {
jwe.setEncodedHeader(jwe.getHeader().toBase64JsonObject());
byte[] contentMasterKey = new byte[blockEncryptionAlgorithm.getCmkLength() / 8];
SecureRandom random = new SecureRandom();
random.nextBytes(contentMasterKey);
String encodedEncryptedKey = generateEncryptedKey(contentMasterKey);
jwe.setEncodedEncryptedKey(encodedEncryptedKey);
byte[] initializationVector = new byte[blockEncryptionAlgorithm.getInitVectorLength() / 8];
random.nextBytes(initializationVector);
String encodedInitializationVector = Base64Util.base64urlencode(initializationVector);
jwe.setEncodedInitializationVector(encodedInitializationVector);
Pair<String, String> result = generateCipherTextAndIntegrityValue(contentMasterKey, initializationVector, jwe.getAdditionalAuthenticatedData().getBytes(Util.UTF8_STRING_ENCODING), jwe.getClaims().toBase64JsonObject().getBytes(Util.UTF8_STRING_ENCODING));
jwe.setEncodedCiphertext(result.getFirst());
jwe.setEncodedIntegrityValue(result.getSecond());
return jwe;
} catch (InvalidJwtException e) {
throw new InvalidJweException(e);
} catch (UnsupportedEncodingException e) {
throw new InvalidJweException(e);
}
}
Aggregations