use of java.security.SignatureException in project bigbluebutton by bigbluebutton.
the class TurnServer method calculateRFC2104HMAC.
/**
* Computes RFC 2104-compliant HMAC signature.
* * @param data
* The data to be signed.
* @param key
* The signing key.
* @return
* The Base64-encoded RFC 2104-compliant HMAC signature.
* @throws
* java.security.SignatureException when signature generation fails
*/
private String calculateRFC2104HMAC(String data, String key) throws java.security.SignatureException {
String result;
try {
// get an hmac_sha1 key from the raw key bytes
SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM);
// get an hmac_sha1 Mac instance and initialize with the signing key
Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
mac.init(signingKey);
// compute the hmac on input data bytes
byte[] rawHmac = mac.doFinal(data.getBytes());
// base64-encode the hmac
result = new String(Base64.encodeBase64(rawHmac));
} catch (Exception e) {
throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
}
return result;
}
use of java.security.SignatureException in project MonjaDB by Kanatoko.
the class MStringUtil method getHMacSHAHash.
//-------------------------------------------------------------------------------
public static final String getHMacSHAHash(String key, String data) {
String result;
try {
// Get an hmac_sha1 key from the raw key bytes
byte[] keyBytes = key.getBytes();
SecretKeySpec signingKey = new SecretKeySpec(keyBytes, HMAC_SHA1_ALGORITHM);
// Get an hmac_sha1 Mac instance and initialize with the signing key
Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
mac.init(signingKey);
// Compute the hmac on input data bytes
byte[] rawHmac = mac.doFinal(data.getBytes());
// Convert raw bytes to Hex
//byte[] hexBytes = new Hex().encode(rawHmac);
// Covert array of Hex bytes to a String
result = byteToHexString(rawHmac);
//System.out.println("MAC : " + result);
} catch (Exception e) {
//throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
return "";
}
return result;
}
use of java.security.SignatureException in project cloudstack by apache.
the class SAML2AuthManagerImpl method initSP.
protected boolean initSP() {
KeystoreVO keyStoreVO = _ksDao.findByName(SAMLPluginConstants.SAMLSP_KEYPAIR);
if (keyStoreVO == null) {
try {
KeyPair keyPair = SAMLUtils.generateRandomKeyPair();
_ksDao.save(SAMLPluginConstants.SAMLSP_KEYPAIR, SAMLUtils.savePrivateKey(keyPair.getPrivate()), SAMLUtils.savePublicKey(keyPair.getPublic()), "samlsp-keypair");
keyStoreVO = _ksDao.findByName(SAMLPluginConstants.SAMLSP_KEYPAIR);
s_logger.info("No SAML keystore found, created and saved a new Service Provider keypair");
} catch (NoSuchProviderException | NoSuchAlgorithmException e) {
s_logger.error("Unable to create and save SAML keypair: " + e.toString());
}
}
String spId = SAMLServiceProviderID.value();
String spSsoUrl = SAMLServiceProviderSingleSignOnURL.value();
String spSloUrl = SAMLServiceProviderSingleLogOutURL.value();
String spOrgName = SAMLServiceProviderOrgName.value();
String spOrgUrl = SAMLServiceProviderOrgUrl.value();
String spContactPersonName = SAMLServiceProviderContactPersonName.value();
String spContactPersonEmail = SAMLServiceProviderContactEmail.value();
KeyPair spKeyPair = null;
X509Certificate spX509Key = null;
if (keyStoreVO != null) {
PrivateKey privateKey = SAMLUtils.loadPrivateKey(keyStoreVO.getCertificate());
PublicKey publicKey = SAMLUtils.loadPublicKey(keyStoreVO.getKey());
if (privateKey != null && publicKey != null) {
spKeyPair = new KeyPair(publicKey, privateKey);
KeystoreVO x509VO = _ksDao.findByName(SAMLPluginConstants.SAMLSP_X509CERT);
if (x509VO == null) {
try {
spX509Key = SAMLUtils.generateRandomX509Certificate(spKeyPair);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(bos);
out.writeObject(spX509Key);
out.flush();
_ksDao.save(SAMLPluginConstants.SAMLSP_X509CERT, Base64.encodeBase64String(bos.toByteArray()), "", "samlsp-x509cert");
bos.close();
} catch (NoSuchAlgorithmException | NoSuchProviderException | CertificateEncodingException | SignatureException | InvalidKeyException | IOException e) {
s_logger.error("SAML Plugin won't be able to use X509 signed authentication");
}
} else {
try {
ByteArrayInputStream bi = new ByteArrayInputStream(Base64.decodeBase64(x509VO.getCertificate()));
ObjectInputStream si = new ObjectInputStream(bi);
spX509Key = (X509Certificate) si.readObject();
bi.close();
} catch (IOException | ClassNotFoundException ignored) {
s_logger.error("SAML Plugin won't be able to use X509 signed authentication. Failed to load X509 Certificate from Database.");
}
}
}
}
if (spKeyPair != null && spX509Key != null && spId != null && spSsoUrl != null && spSloUrl != null && spOrgName != null && spOrgUrl != null && spContactPersonName != null && spContactPersonEmail != null) {
_spMetadata.setEntityId(spId);
_spMetadata.setOrganizationName(spOrgName);
_spMetadata.setOrganizationUrl(spOrgUrl);
_spMetadata.setContactPersonName(spContactPersonName);
_spMetadata.setContactPersonEmail(spContactPersonEmail);
_spMetadata.setSsoUrl(spSsoUrl);
_spMetadata.setSloUrl(spSloUrl);
_spMetadata.setKeyPair(spKeyPair);
_spMetadata.setSigningCertificate(spX509Key);
_spMetadata.setEncryptionCertificate(spX509Key);
return true;
}
return false;
}
use of java.security.SignatureException in project oxAuth by GluuFederation.
the class UserInfoRestWebServiceImpl method requestUserInfo.
public Response requestUserInfo(String accessToken, String authorization, HttpServletRequest request, SecurityContext securityContext) {
if (authorization != null && !authorization.isEmpty() && authorization.startsWith("Bearer ")) {
accessToken = authorization.substring(7);
}
log.debug("Attempting to request User Info, Access token = {}, Is Secure = {}", accessToken, securityContext.isSecure());
Response.ResponseBuilder builder = Response.ok();
OAuth2AuditLog oAuth2AuditLog = new OAuth2AuditLog(ServerUtil.getIpAddress(request), Action.USER_INFO);
try {
if (!UserInfoParamsValidator.validateParams(accessToken)) {
builder = Response.status(400);
builder.entity(errorResponseFactory.getErrorAsJson(UserInfoErrorResponseType.INVALID_REQUEST));
} else {
AuthorizationGrant authorizationGrant = authorizationGrantList.getAuthorizationGrantByAccessToken(accessToken);
if (authorizationGrant == null) {
builder = Response.status(400);
builder.entity(errorResponseFactory.getErrorAsJson(UserInfoErrorResponseType.INVALID_TOKEN));
} else if (authorizationGrant.getAuthorizationGrantType() == AuthorizationGrantType.CLIENT_CREDENTIALS) {
builder = Response.status(403);
builder.entity(errorResponseFactory.getErrorAsJson(UserInfoErrorResponseType.INSUFFICIENT_SCOPE));
} else if (!authorizationGrant.getScopes().contains(DefaultScope.OPEN_ID.toString()) && !authorizationGrant.getScopes().contains(DefaultScope.PROFILE.toString())) {
builder = Response.status(403);
builder.entity(errorResponseFactory.getErrorAsJson(UserInfoErrorResponseType.INSUFFICIENT_SCOPE));
oAuth2AuditLog.updateOAuth2AuditLog(authorizationGrant, false);
} else {
oAuth2AuditLog.updateOAuth2AuditLog(authorizationGrant, true);
CacheControl cacheControl = new CacheControl();
cacheControl.setPrivate(true);
cacheControl.setNoTransform(false);
cacheControl.setNoStore(true);
builder.cacheControl(cacheControl);
builder.header("Pragma", "no-cache");
User currentUser = authorizationGrant.getUser();
try {
currentUser = userService.getUserByDn(authorizationGrant.getUserDn());
} catch (EntryPersistenceException ex) {
log.warn("Failed to reload user entry: '{}'", authorizationGrant.getUserDn());
}
if (authorizationGrant.getClient() != null && authorizationGrant.getClient().getUserInfoEncryptedResponseAlg() != null && authorizationGrant.getClient().getUserInfoEncryptedResponseEnc() != null) {
KeyEncryptionAlgorithm keyEncryptionAlgorithm = KeyEncryptionAlgorithm.fromName(authorizationGrant.getClient().getUserInfoEncryptedResponseAlg());
BlockEncryptionAlgorithm blockEncryptionAlgorithm = BlockEncryptionAlgorithm.fromName(authorizationGrant.getClient().getUserInfoEncryptedResponseEnc());
builder.type("application/jwt");
builder.entity(getJweResponse(keyEncryptionAlgorithm, blockEncryptionAlgorithm, currentUser, authorizationGrant, authorizationGrant.getScopes()));
} else if (authorizationGrant.getClient() != null && authorizationGrant.getClient().getUserInfoSignedResponseAlg() != null) {
SignatureAlgorithm algorithm = SignatureAlgorithm.fromString(authorizationGrant.getClient().getUserInfoSignedResponseAlg());
builder.type("application/jwt");
builder.entity(getJwtResponse(algorithm, currentUser, authorizationGrant, authorizationGrant.getScopes()));
} else {
builder.type((MediaType.APPLICATION_JSON + ";charset=UTF-8"));
builder.entity(getJSonResponse(currentUser, authorizationGrant, authorizationGrant.getScopes()));
}
}
}
} catch (StringEncrypter.EncryptionException e) {
// 500
builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
log.error(e.getMessage(), e);
} catch (InvalidJwtException e) {
// 500
builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
log.error(e.getMessage(), e);
} catch (SignatureException e) {
// 500
builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
log.error(e.getMessage(), e);
} catch (InvalidClaimException e) {
// 500
builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
log.error(e.getMessage(), e);
} catch (Exception e) {
// 500
builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
log.error(e.getMessage(), e);
}
applicationAuditLogger.sendMessage(oAuth2AuditLog);
return builder.build();
}
use of java.security.SignatureException in project oxAuth by GluuFederation.
the class TokenRestWebServiceImpl method requestAccessToken.
@Override
public Response requestAccessToken(String grantType, String code, String redirectUri, String username, String password, String scope, String assertion, String refreshToken, String oxAuthExchangeToken, String clientId, String clientSecret, String codeVerifier, HttpServletRequest request, SecurityContext sec) {
log.debug("Attempting to request access token: grantType = {}, code = {}, redirectUri = {}, username = {}, refreshToken = {}, " + "clientId = {}, ExtraParams = {}, isSecure = {}, codeVerifier = {}", grantType, code, redirectUri, username, refreshToken, clientId, request.getParameterMap(), sec.isSecure(), codeVerifier);
OAuth2AuditLog oAuth2AuditLog = new OAuth2AuditLog(ServerUtil.getIpAddress(request), Action.TOKEN_REQUEST);
oAuth2AuditLog.setClientId(clientId);
oAuth2AuditLog.setUsername(username);
oAuth2AuditLog.setScope(scope);
// it may be encoded in uma case
scope = ServerUtil.urlDecode(scope);
ResponseBuilder builder = Response.ok();
try {
log.debug("Starting to validate request parameters");
if (!TokenParamsValidator.validateParams(grantType, code, redirectUri, username, password, scope, assertion, refreshToken, oxAuthExchangeToken)) {
log.trace("Failed to validate request parameters");
builder = error(400, TokenErrorResponseType.INVALID_REQUEST);
} else {
log.trace("Request parameters are right");
GrantType gt = GrantType.fromString(grantType);
log.debug("Grant type: '{}'", gt);
SessionClient sessionClient = identity.getSetSessionClient();
Client client = null;
if (sessionClient != null) {
client = sessionClient.getClient();
log.debug("Get sessionClient: '{}'", sessionClient);
}
if (client != null) {
log.debug("Get client from session: '{}'", client.getClientId());
}
if (gt == GrantType.AUTHORIZATION_CODE) {
if (client == null) {
return response(error(400, TokenErrorResponseType.INVALID_GRANT));
}
log.debug("Attempting to find authorizationCodeGrant by clinetId: '{}', code: '{}'", client.getClientId(), code);
AuthorizationCodeGrant authorizationCodeGrant = authorizationGrantList.getAuthorizationCodeGrant(client.getClientId(), code);
log.trace("AuthorizationCodeGrant : '{}'", authorizationCodeGrant);
if (authorizationCodeGrant != null) {
validatePKCE(authorizationCodeGrant, codeVerifier);
authorizationCodeGrant.setIsCachedWithNoPersistence(false);
authorizationCodeGrant.save();
AccessToken accToken = authorizationCodeGrant.createAccessToken();
log.debug("Issuing access token: {}", accToken.getCode());
RefreshToken reToken = authorizationCodeGrant.createRefreshToken();
if (scope != null && !scope.isEmpty()) {
scope = authorizationCodeGrant.checkScopesPolicy(scope);
}
IdToken idToken = null;
if (authorizationCodeGrant.getScopes().contains("openid")) {
String nonce = authorizationCodeGrant.getNonce();
boolean includeIdTokenClaims = Boolean.TRUE.equals(appConfiguration.getLegacyIdTokenClaims());
idToken = authorizationCodeGrant.createIdToken(nonce, null, accToken, authorizationCodeGrant, includeIdTokenClaims);
}
builder.entity(getJSonResponse(accToken, accToken.getTokenType(), accToken.getExpiresIn(), reToken, scope, idToken));
oAuth2AuditLog.updateOAuth2AuditLog(authorizationCodeGrant, true);
grantService.removeByCode(authorizationCodeGrant.getAuthorizationCode().getCode(), authorizationCodeGrant.getClientId());
} else {
log.debug("AuthorizationCodeGrant is empty by clinetId: '{}', code: '{}'", client.getClientId(), code);
// if authorization code is not found then code was already used = remove all grants with this auth code
grantService.removeAllByAuthorizationCode(code);
builder = error(400, TokenErrorResponseType.INVALID_GRANT);
}
} else if (gt == GrantType.REFRESH_TOKEN) {
if (client == null) {
return response(error(401, TokenErrorResponseType.INVALID_GRANT));
}
AuthorizationGrant authorizationGrant = authorizationGrantList.getAuthorizationGrantByRefreshToken(client.getClientId(), refreshToken);
if (authorizationGrant != null) {
AccessToken accToken = authorizationGrant.createAccessToken();
/*
The authorization server MAY issue a new refresh token, in which case
the client MUST discard the old refresh token and replace it with the
new refresh token.
*/
RefreshToken reToken = authorizationGrant.createRefreshToken();
grantService.removeByCode(refreshToken, client.getClientId());
if (scope != null && !scope.isEmpty()) {
scope = authorizationGrant.checkScopesPolicy(scope);
}
builder.entity(getJSonResponse(accToken, accToken.getTokenType(), accToken.getExpiresIn(), reToken, scope, null));
oAuth2AuditLog.updateOAuth2AuditLog(authorizationGrant, true);
} else {
builder = error(401, TokenErrorResponseType.INVALID_GRANT);
}
} else if (gt == GrantType.CLIENT_CREDENTIALS) {
if (client == null) {
return response(error(401, TokenErrorResponseType.INVALID_GRANT));
}
// TODO: fix the user arg
ClientCredentialsGrant clientCredentialsGrant = authorizationGrantList.createClientCredentialsGrant(new User(), client);
AccessToken accessToken = clientCredentialsGrant.createAccessToken();
if (scope != null && !scope.isEmpty()) {
scope = clientCredentialsGrant.checkScopesPolicy(scope);
}
IdToken idToken = null;
if (clientCredentialsGrant.getScopes().contains("openid")) {
boolean includeIdTokenClaims = Boolean.TRUE.equals(appConfiguration.getLegacyIdTokenClaims());
idToken = clientCredentialsGrant.createIdToken(null, null, null, clientCredentialsGrant, includeIdTokenClaims);
}
oAuth2AuditLog.updateOAuth2AuditLog(clientCredentialsGrant, true);
builder.entity(getJSonResponse(accessToken, accessToken.getTokenType(), accessToken.getExpiresIn(), null, scope, idToken));
} else if (gt == GrantType.RESOURCE_OWNER_PASSWORD_CREDENTIALS) {
if (client == null) {
log.error("Invalid client", new RuntimeException("Client is empty"));
return response(error(401, TokenErrorResponseType.INVALID_CLIENT));
}
User user = null;
if (authenticationFilterService.isEnabled()) {
String userDn = authenticationFilterService.processAuthenticationFilters(request.getParameterMap());
if (StringHelper.isNotEmpty(userDn)) {
user = userService.getUserByDn(userDn);
}
}
if (user == null) {
boolean authenticated = authenticationService.authenticate(username, password);
if (authenticated) {
user = authenticationService.getAuthenticatedUser();
}
}
if (user != null) {
ResourceOwnerPasswordCredentialsGrant resourceOwnerPasswordCredentialsGrant = authorizationGrantList.createResourceOwnerPasswordCredentialsGrant(user, client);
AccessToken accessToken = resourceOwnerPasswordCredentialsGrant.createAccessToken();
RefreshToken reToken = resourceOwnerPasswordCredentialsGrant.createRefreshToken();
if (scope != null && !scope.isEmpty()) {
scope = resourceOwnerPasswordCredentialsGrant.checkScopesPolicy(scope);
}
IdToken idToken = null;
if (resourceOwnerPasswordCredentialsGrant.getScopes().contains("openid")) {
boolean includeIdTokenClaims = Boolean.TRUE.equals(appConfiguration.getLegacyIdTokenClaims());
idToken = resourceOwnerPasswordCredentialsGrant.createIdToken(null, null, null, resourceOwnerPasswordCredentialsGrant, includeIdTokenClaims);
}
oAuth2AuditLog.updateOAuth2AuditLog(resourceOwnerPasswordCredentialsGrant, true);
builder.entity(getJSonResponse(accessToken, accessToken.getTokenType(), accessToken.getExpiresIn(), reToken, scope, idToken));
} else {
log.error("Invalid user", new RuntimeException("User is empty"));
builder = error(401, TokenErrorResponseType.INVALID_CLIENT);
}
} else if (gt == GrantType.EXTENSION) {
builder = error(501, TokenErrorResponseType.INVALID_GRANT);
} else if (gt == GrantType.OXAUTH_EXCHANGE_TOKEN) {
AuthorizationGrant authorizationGrant = authorizationGrantList.getAuthorizationGrantByAccessToken(oxAuthExchangeToken);
if (authorizationGrant != null) {
final AccessToken accessToken = authorizationGrant.createLongLivedAccessToken();
oAuth2AuditLog.updateOAuth2AuditLog(authorizationGrant, true);
builder.entity(getJSonResponse(accessToken, accessToken.getTokenType(), accessToken.getExpiresIn(), null, null, null));
} else {
builder = error(401, TokenErrorResponseType.INVALID_GRANT);
}
}
}
} catch (WebApplicationException e) {
throw e;
} catch (SignatureException e) {
builder = Response.status(500);
log.error(e.getMessage(), e);
} catch (StringEncrypter.EncryptionException e) {
builder = Response.status(500);
log.error(e.getMessage(), e);
} catch (InvalidJwtException e) {
builder = Response.status(500);
log.error(e.getMessage(), e);
} catch (InvalidJweException e) {
builder = Response.status(500);
log.error(e.getMessage(), e);
} catch (Exception e) {
builder = Response.status(500);
log.error(e.getMessage(), e);
}
applicationAuditLogger.sendMessage(oAuth2AuditLog);
return response(builder);
}
Aggregations