org.apache.xml.security.algorithms.JCEMapper Java Examples

The following examples show how to use org.apache.xml.security.algorithms.JCEMapper. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SignatureUtils.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public static MessageDigest getDigestInstance(String algorithmURI) throws NoSuchAlgorithmException {
   String algorithmID = JCEMapper.translateURItoJCEID(algorithmURI);
   if (algorithmID == null) {
      throw new NoSuchAlgorithmException("Could not translate algorithmURI [" + algorithmURI + "]");
   } else {
      String provider = JCEMapper.getProviderId();

      try {
         MessageDigest md;
         if (provider == null) {
            md = MessageDigest.getInstance(algorithmID);
         } else {
            md = MessageDigest.getInstance(algorithmID, provider);
         }

         return md;
      } catch (NoSuchProviderException var5) {
         throw new NoSuchAlgorithmException("Could not find provider for [" + algorithmID + "]", var5);
      }
   }
}
 
Example #2
Source File: DefaultMessageDigestProvider.java    From xades4j with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public MessageDigest getEngine(String digestAlgorithmURI) throws UnsupportedAlgorithmException
{

    String digestAlgorithmName = JCEMapper.translateURItoJCEID(digestAlgorithmURI);
    if (null == digestAlgorithmName) {
        throw new UnsupportedAlgorithmException("Digest algorithm not supported by the provider", digestAlgorithmURI);
    }
    try {
        return this.messageDigestProvider == null ?
                MessageDigest.getInstance(digestAlgorithmName) :
                MessageDigest.getInstance(digestAlgorithmName, this.messageDigestProvider);
    } catch (NoSuchAlgorithmException nsae) {
        throw new UnsupportedAlgorithmException(nsae.getMessage(), digestAlgorithmURI, nsae);
    } catch (NoSuchProviderException nspe) {
        // We checked that the provider existed on construction, but throw anyway
        throw new UnsupportedAlgorithmException("Provider not available", digestAlgorithmURI, nspe);
    }
}
 
Example #3
Source File: SignatureUtils.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public static MessageDigest getDigestInstance(String algorithmURI) throws NoSuchAlgorithmException {
   String algorithmID = JCEMapper.translateURItoJCEID(algorithmURI);
   if (algorithmID == null) {
      throw new NoSuchAlgorithmException("Could not translate algorithmURI [" + algorithmURI + "]");
   } else {
      String provider = JCEMapper.getProviderId();

      try {
         MessageDigest md;
         if (provider == null) {
            md = MessageDigest.getInstance(algorithmID);
         } else {
            md = MessageDigest.getInstance(algorithmID, provider);
         }

         return md;
      } catch (NoSuchProviderException var5) {
         throw new NoSuchAlgorithmException("Could not find provider for [" + algorithmID + "]", var5);
      }
   }
}
 
Example #4
Source File: SecurityHelper.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Get the length of the key indicated by the algorithm URI, if applicable and available.
 * 
 * @param algorithmURI the algorithm URI to evaluate
 * @return the length of the key indicated by the algorithm URI, or null if the length is either unavailable or
 *         indeterminable from the URI
 */
public static Integer getKeyLengthFromURI(String algorithmURI) {
    Logger log = getLogger();
    String algoClass = DatatypeHelper.safeTrimOrNullString(JCEMapper.getAlgorithmClassFromURI(algorithmURI));

    if (ApacheXMLSecurityConstants.ALGO_CLASS_BLOCK_ENCRYPTION.equals(algoClass)
            || ApacheXMLSecurityConstants.ALGO_CLASS_SYMMETRIC_KEY_WRAP.equals(algoClass)) {

        try {
            int keyLength = JCEMapper.getKeyLengthFromURI(algorithmURI);
            return new Integer(keyLength);
        } catch (NumberFormatException e) {
            log.warn("XML Security config contained invalid key length value for algorithm URI: " + algorithmURI);
        }
    }

    log.info("Mapping from algorithm URI {} to key length not available", algorithmURI);
    return null;
}
 
Example #5
Source File: SignatureUtils.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public static MessageDigest getDigestInstance(String algorithmURI) throws NoSuchAlgorithmException {
   String algorithmID = JCEMapper.translateURItoJCEID(algorithmURI);
   if (algorithmID == null) {
      throw new NoSuchAlgorithmException("Could not translate algorithmURI [" + algorithmURI + "]");
   } else {
      String provider = JCEMapper.getProviderId();

      try {
         MessageDigest md;
         if (provider == null) {
            md = MessageDigest.getInstance(algorithmID);
         } else {
            md = MessageDigest.getInstance(algorithmID, provider);
         }

         return md;
      } catch (NoSuchProviderException var5) {
         throw new NoSuchAlgorithmException("Could not find provider for [" + algorithmID + "]", var5);
      }
   }
}
 
Example #6
Source File: SignatureUtils.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public static MessageDigest getDigestInstance(String algorithmURI) throws NoSuchAlgorithmException {
   String algorithmID = JCEMapper.translateURItoJCEID(algorithmURI);
   if (algorithmID == null) {
      throw new NoSuchAlgorithmException("Could not translate algorithmURI [" + algorithmURI + "]");
   } else {
      String provider = JCEMapper.getProviderId();

      try {
         MessageDigest md;
         if (provider == null) {
            md = MessageDigest.getInstance(algorithmID);
         } else {
            md = MessageDigest.getInstance(algorithmID, provider);
         }

         return md;
      } catch (NoSuchProviderException var5) {
         throw new NoSuchAlgorithmException("Could not find provider for [" + algorithmID + "]", var5);
      }
   }
}
 
Example #7
Source File: SignatureUtils.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public static MessageDigest getDigestInstance(String algorithmURI) throws NoSuchAlgorithmException {
   String algorithmID = JCEMapper.translateURItoJCEID(algorithmURI);
   if (algorithmID == null) {
      throw new NoSuchAlgorithmException("Could not translate algorithmURI [" + algorithmURI + "]");
   } else {
      String provider = JCEMapper.getProviderId();

      try {
         MessageDigest md;
         if (provider == null) {
            md = MessageDigest.getInstance(algorithmID);
         } else {
            md = MessageDigest.getInstance(algorithmID, provider);
         }

         return md;
      } catch (NoSuchProviderException var5) {
         throw new NoSuchAlgorithmException("Could not find provider for [" + algorithmID + "]", var5);
      }
   }
}
 
Example #8
Source File: TimeStampGeneratorImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
private SignRequest generateSignRequest(String requestId, String digestAlgoURI, byte[] transformed) throws TechnicalConnectorException {
   SignRequest request = new SignRequest();
   request.setRequestID(requestId);
   request.setProfile(SignatureUtils.getOption("SignatureTimestampProfile", this.options, "urn:ehealth:profiles:timestamping:2.1-cert"));
   InputDocuments inputDocuments = new InputDocuments();
   DocumentHash docHash = new DocumentHash();
   docHash.setDigestMethod(new DigestMethod());
   docHash.getDigestMethod().setAlgorithm(digestAlgoURI);
   docHash.setDigestValue(ConnectorCryptoUtils.calculateDigest(JCEMapper.translateURItoJCEID(digestAlgoURI), transformed));
   inputDocuments.getDocumentHash().add(docHash);
   request.setInputDocuments(inputDocuments);
   return request;
}
 
Example #9
Source File: AuthnRequestParser.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
private void validateSeparateSignature(Idp idp, String sigAlg, String signature, String relayState,
                                       String samlRequest, String realm) throws Exception {
    // Check signature
    X509Certificate validatingCert = getValidatingCertificate(idp, realm);

    // Process the received SigAlg parameter - fall back to RSA SHA1
    String processedSigAlg = null;
    if (sigAlg != null && SIG_ALGS.contains(sigAlg)) {
        processedSigAlg = sigAlg;
    } else {
        LOG.debug("Supplied SigAlg parameter is either null or not known, so falling back to use RSA-SHA1");
        processedSigAlg = SSOConstants.RSA_SHA1;
    }

    java.security.Signature sig =
        java.security.Signature.getInstance(JCEMapper.translateURItoJCEID(processedSigAlg));
    sig.initVerify(validatingCert);

    // Recreate request to sign
    String requestToSign =
            SSOConstants.SAML_REQUEST + "=" + URLEncoder.encode(samlRequest, StandardCharsets.UTF_8.name())
            + "&" + SSOConstants.RELAY_STATE + "=" + URLEncoder.encode(relayState, StandardCharsets.UTF_8.name())
            + "&" + SSOConstants.SIG_ALG + "=" + URLEncoder.encode(processedSigAlg, StandardCharsets.UTF_8.name());

    sig.update(requestToSign.getBytes(StandardCharsets.UTF_8));

    if (!sig.verify(Base64.getDecoder().decode(signature))) {
        LOG.debug("Signature validation failed");
        throw new ProcessingException(TYPE.BAD_REQUEST);
    }
}
 
Example #10
Source File: SAML2ReaderWriter.java    From syncope with Apache License 2.0 5 votes vote down vote up
public void init() {
    X509KeyInfoGeneratorFactory keyInfoGeneratorFactory = new X509KeyInfoGeneratorFactory();
    keyInfoGeneratorFactory.setEmitEntityCertificate(true);
    keyInfoGenerator = keyInfoGeneratorFactory.newInstance();

    // Try to load a signature algorithm
    if (loader.getSignatureAlgorithm() != null) {
        SignatureAlgorithm loadedSignatureAlgorithm =
                SignatureAlgorithm.valueOf(loader.getSignatureAlgorithm());
        sigAlgo = loadedSignatureAlgorithm.getAlgorithm();
        jceSigAlgo = JCEMapper.translateURItoJCEID(sigAlgo);
        if (jceSigAlgo == null) {
            LOG.warn("Signature algorithm {} is not valid. Using default algorithm instead.",
                    loader.getSignatureAlgorithm());
            sigAlgo = null;
        }
    }

    if (sigAlgo == null) {
        sigAlgo = SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1;
        String pubKeyAlgo = loader.getCredential().getPublicKey().getAlgorithm();
        if (pubKeyAlgo.equalsIgnoreCase("DSA")) {
            sigAlgo = SignatureConstants.ALGO_ID_SIGNATURE_DSA_SHA1;
        } else if (pubKeyAlgo.equalsIgnoreCase("EC")) {
            sigAlgo = SignatureConstants.ALGO_ID_SIGNATURE_ECDSA_SHA1;
        }
        jceSigAlgo = JCEMapper.translateURItoJCEID(sigAlgo);
    }

    callbackHandler = new SAMLSPCallbackHandler(loader.getKeyPass());
}
 
Example #11
Source File: SecurityHelper.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Get the Java security JCA/JCE key algorithm specifier associated with an algorithm URI.
 * 
 * @param algorithmURI the algorithm URI to evaluate
 * @return the Java key algorithm specifier, or null if the mapping is unavailable or indeterminable from the URI
 */
public static String getKeyAlgorithmFromURI(String algorithmURI) {
    // The default Apache config file currently only includes the key algorithm for
    // the block ciphers and key wrap URI's. Note: could use a custom config file which contains others.
    String apacheValue = DatatypeHelper.safeTrimOrNullString(JCEMapper.getJCEKeyAlgorithmFromURI(algorithmURI));
    if (apacheValue != null) {
        return apacheValue;
    }

    // HMAC uses any symmetric key, so there is no implied specific key algorithm
    if (isHMAC(algorithmURI)) {
        return null;
    }

    // As a last ditch fallback, check some known common and supported ones.
    if (rsaAlgorithmURIs.contains(algorithmURI)) {
        return "RSA";
    }
    if (dsaAlgorithmURIs.contains(algorithmURI)) {
        return "DSA";
    }
    if (ecdsaAlgorithmURIs.contains(algorithmURI)) {
        return "EC";
    }

    return null;
}
 
Example #12
Source File: Ref.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public byte[] getDigestValue() {
   try {
      return ConnectorCryptoUtils.calculateDigest(JCEMapper.translateURItoJCEID("http://www.w3.org/2001/04/xmlenc#sha256"), this.getEncoded());
   } catch (Exception var2) {
      throw new IllegalArgumentException(var2);
   }
}
 
Example #13
Source File: Ref.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public byte[] getDigestValue() {
   try {
      return ConnectorCryptoUtils.calculateDigest(JCEMapper.translateURItoJCEID("http://www.w3.org/2001/04/xmlenc#sha256"), this.getEncoded());
   } catch (Exception var2) {
      throw new IllegalArgumentException(var2);
   }
}
 
Example #14
Source File: TimeStampGeneratorImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
private SignRequest generateSignRequest(String requestId, String digestAlgoURI, byte[] transformed) throws TechnicalConnectorException {
   SignRequest request = new SignRequest();
   request.setRequestID(requestId);
   request.setProfile((String)SignatureUtils.getOption("SignatureTimestampProfile", this.options, "urn:ehealth:profiles:timestamping:2.1-cert"));
   InputDocuments inputDocuments = new InputDocuments();
   DocumentHash docHash = new DocumentHash();
   docHash.setDigestMethod(new DigestMethod());
   docHash.getDigestMethod().setAlgorithm(digestAlgoURI);
   docHash.setDigestValue(ConnectorCryptoUtils.calculateDigest(JCEMapper.translateURItoJCEID(digestAlgoURI), transformed));
   inputDocuments.getDocumentHash().add(docHash);
   request.setInputDocuments(inputDocuments);
   return request;
}
 
Example #15
Source File: Ref.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public byte[] getDigestValue() {
   try {
      return ConnectorCryptoUtils.calculateDigest(JCEMapper.translateURItoJCEID("http://www.w3.org/2001/04/xmlenc#sha256"), this.getEncoded());
   } catch (Exception var2) {
      throw new IllegalArgumentException(var2);
   }
}
 
Example #16
Source File: TimeStampGeneratorImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
private SignRequest generateSignRequest(String requestId, String digestAlgoURI, byte[] transformed) throws TechnicalConnectorException {
   SignRequest request = new SignRequest();
   request.setRequestID(requestId);
   request.setProfile((String)SignatureUtils.getOption("SignatureTimestampProfile", this.options, "urn:ehealth:profiles:timestamping:2.1-cert"));
   InputDocuments inputDocuments = new InputDocuments();
   DocumentHash docHash = new DocumentHash();
   docHash.setDigestMethod(new DigestMethod());
   docHash.getDigestMethod().setAlgorithm(digestAlgoURI);
   docHash.setDigestValue(ConnectorCryptoUtils.calculateDigest(JCEMapper.translateURItoJCEID(digestAlgoURI), transformed));
   inputDocuments.getDocumentHash().add(docHash);
   request.setInputDocuments(inputDocuments);
   return request;
}
 
Example #17
Source File: Ref.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public byte[] getDigestValue() {
   try {
      return ConnectorCryptoUtils.calculateDigest(JCEMapper.translateURItoJCEID("http://www.w3.org/2001/04/xmlenc#sha256"), this.getEncoded());
   } catch (Exception var2) {
      throw new IllegalArgumentException(var2);
   }
}
 
Example #18
Source File: TimeStampGeneratorImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
private SignRequest generateSignRequest(String requestId, String digestAlgoURI, byte[] transformed) throws TechnicalConnectorException {
   SignRequest request = new SignRequest();
   request.setRequestID(requestId);
   request.setProfile((String)SignatureUtils.getOption("SignatureTimestampProfile", this.options, "urn:ehealth:profiles:timestamping:2.1-cert"));
   InputDocuments inputDocuments = new InputDocuments();
   DocumentHash docHash = new DocumentHash();
   docHash.setDigestMethod(new DigestMethod());
   docHash.getDigestMethod().setAlgorithm(digestAlgoURI);
   docHash.setDigestValue(ConnectorCryptoUtils.calculateDigest(JCEMapper.translateURItoJCEID(digestAlgoURI), transformed));
   inputDocuments.getDocumentHash().add(docHash);
   request.setInputDocuments(inputDocuments);
   return request;
}
 
Example #19
Source File: Ref.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public byte[] getDigestValue() {
   try {
      return ConnectorCryptoUtils.calculateDigest(JCEMapper.translateURItoJCEID("http://www.w3.org/2001/04/xmlenc#sha256"), this.getEncoded());
   } catch (Exception var2) {
      throw new IllegalArgumentException(var2);
   }
}
 
Example #20
Source File: TimeStampGeneratorImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
private SignRequest generateSignRequest(String requestId, String digestAlgoURI, byte[] transformed) throws TechnicalConnectorException {
   SignRequest request = new SignRequest();
   request.setRequestID(requestId);
   request.setProfile((String)SignatureUtils.getOption("SignatureTimestampProfile", this.options, "urn:ehealth:profiles:timestamping:2.1-cert"));
   InputDocuments inputDocuments = new InputDocuments();
   DocumentHash docHash = new DocumentHash();
   docHash.setDigestMethod(new DigestMethod());
   docHash.getDigestMethod().setAlgorithm(digestAlgoURI);
   docHash.setDigestValue(ConnectorCryptoUtils.calculateDigest(JCEMapper.translateURItoJCEID(digestAlgoURI), transformed));
   inputDocuments.getDocumentHash().add(docHash);
   request.setInputDocuments(inputDocuments);
   return request;
}
 
Example #21
Source File: SantuarioInitializer.java    From dss with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Dynamically initialise the library by registering the default
 * algorithms/implementations
 */
private static void dynamicInit() {
	//
	// Load the Resource Bundle - the default is the English resource bundle.
	// To load another resource bundle, call I18n.init(...) before calling this
	// method.
	//
	I18n.init("en", "US");

	if (LOG.isDebugEnabled()) {
		LOG.debug("Registering default algorithms");
	}
	try {
		//
		// Bind the default prefixes
		//
		ElementProxy.registerDefaultPrefixes();
	} catch (XMLSecurityException ex) {
		LOG.error(ex.getMessage(), ex);
	}

	//
	// Set the default Transforms
	//
	Transform.registerDefaultAlgorithms();

	//
	// Set the default signature algorithms
	//
	SignatureAlgorithm.registerDefaultAlgorithms();

	//
	// Set the default JCE algorithms
	//
	JCEMapper.registerDefaultAlgorithms();

	//
	// Set the default c14n algorithms
	//
	Canonicalizer.registerDefaultAlgorithms();

	//
	// Register the default resolvers (custom)
	//
	registerDefaultResolvers();

	//
	// Register the default key resolvers
	//
	KeyResolver.registerDefaultResolvers();
}
 
Example #22
Source File: AbstractStaxBindingHandler.java    From cxf with Apache License 2.0 4 votes vote down vote up
protected void storeSecurityToken(AbstractToken policyToken, SecurityToken tok) {
    SecurityTokenConstants.TokenType tokenType = WSSecurityTokenConstants.EncryptedKeyToken;
    if (tok.getTokenType() != null) {
        if (tok.getTokenType().startsWith(WSSConstants.NS_KERBEROS11_TOKEN_PROFILE)) {
            tokenType = WSSecurityTokenConstants.KERBEROS_TOKEN;
        } else if (tok.getTokenType().startsWith(WSSConstants.NS_SAML10_TOKEN_PROFILE)
            || tok.getTokenType().startsWith(WSSConstants.NS_SAML11_TOKEN_PROFILE)) {
            tokenType = WSSecurityTokenConstants.SAML_11_TOKEN;
        } else if (tok.getTokenType().startsWith(WSSConstants.NS_WSC_05_02)
            || tok.getTokenType().startsWith(WSSConstants.NS_WSC_05_12)) {
            tokenType = WSSecurityTokenConstants.SECURE_CONVERSATION_TOKEN;
        }
    }

    final Key key = tok.getKey();
    final byte[] secret = tok.getSecret();
    final X509Certificate[] certs = new X509Certificate[1];
    if (tok.getX509Certificate() != null) {
        certs[0] = tok.getX509Certificate();
    }

    final GenericOutboundSecurityToken encryptedKeySecurityToken =
        new GenericOutboundSecurityToken(tok.getId(), tokenType, key, certs) {

            @Override
            public Key getSecretKey(String algorithmURI) throws XMLSecurityException {
                if (secret != null && algorithmURI != null && !"".equals(algorithmURI)) {
                    return KeyUtils.prepareSecretKey(algorithmURI, secret);
                }
                if (key != null) {
                    return key;
                }
                if (secret != null) {
                    String jceAlg = JCEMapper.getJCEKeyAlgorithmFromURI(algorithmURI);
                    if (jceAlg == null || "".equals(jceAlg)) {
                        jceAlg = "HmacSHA1";
                    }
                    return new SecretKeySpec(secret, jceAlg);
                }

                return super.getSecretKey(algorithmURI);
            }
        };

    // Store a DOM Element reference if it exists
    Element ref;
    if (isTokenRequired(policyToken.getIncludeTokenType())) {
        ref = tok.getAttachedReference();
    } else {
        ref = tok.getUnattachedReference();
    }

    if (ref != null && policyToken instanceof IssuedToken) {
        encryptedKeySecurityToken.setCustomTokenReference(ref);
    }
    final SecurityTokenProvider<OutboundSecurityToken> encryptedKeySecurityTokenProvider =
        new SecurityTokenProvider<OutboundSecurityToken>() {

            @Override
            public OutboundSecurityToken getSecurityToken() throws XMLSecurityException {
                return encryptedKeySecurityToken;
            }

            @Override
            public String getId() {
                return encryptedKeySecurityToken.getId();
            }

        };
    encryptedKeySecurityToken.setSha1Identifier(tok.getSHA1());

    outboundSecurityContext.registerSecurityTokenProvider(
            encryptedKeySecurityTokenProvider.getId(), encryptedKeySecurityTokenProvider);
    outboundSecurityContext.put(XMLSecurityConstants.PROP_USE_THIS_TOKEN_ID_FOR_ENCRYPTION,
            encryptedKeySecurityTokenProvider.getId());
    outboundSecurityContext.put(XMLSecurityConstants.PROP_USE_THIS_TOKEN_ID_FOR_SIGNATURE,
            encryptedKeySecurityTokenProvider.getId());
    outboundSecurityContext.put(WSSConstants.PROP_USE_THIS_TOKEN_ID_FOR_CUSTOM_TOKEN,
            encryptedKeySecurityTokenProvider.getId());
}
 
Example #23
Source File: SamlRedirectBindingFilter.java    From cxf with Apache License 2.0 4 votes vote down vote up
/**
 * Sign a request according to the redirect binding spec for Web SSO
 */
private void signRequest(
    String authnRequest,
    String relayState,
    UriBuilder ub
) throws Exception {
    Crypto crypto = getSignatureCrypto();
    if (crypto == null) {
        LOG.warning("No crypto instance of properties file configured for signature");
        throw ExceptionUtils.toInternalServerErrorException(null, null);
    }
    String signatureUser = getSignatureUsername();
    if (signatureUser == null) {
        LOG.warning("No user configured for signature");
        throw ExceptionUtils.toInternalServerErrorException(null, null);
    }
    CallbackHandler callbackHandler = getCallbackHandler();
    if (callbackHandler == null) {
        LOG.warning("No CallbackHandler configured to supply a password for signature");
        throw ExceptionUtils.toInternalServerErrorException(null, null);
    }

    CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
    cryptoType.setAlias(signatureUser);
    X509Certificate[] issuerCerts = crypto.getX509Certificates(cryptoType);
    if (issuerCerts == null) {
        throw new Exception(
            "No issuer certs were found to sign the request using name: " + signatureUser
        );
    }

    String sigAlgo = getSignatureAlgorithm();
    String pubKeyAlgo = issuerCerts[0].getPublicKey().getAlgorithm();
    LOG.fine("automatic sig algo detection: " + pubKeyAlgo);
    if ("DSA".equalsIgnoreCase(pubKeyAlgo)) {
        sigAlgo = SSOConstants.DSA_SHA1;
    }

    LOG.fine("Using Signature algorithm " + sigAlgo);
    ub.queryParam(SSOConstants.SIG_ALG, URLEncoder.encode(sigAlgo, StandardCharsets.UTF_8.name()));

    // Get the password
    WSPasswordCallback[] cb = {new WSPasswordCallback(signatureUser, WSPasswordCallback.SIGNATURE)};
    callbackHandler.handle(cb);
    String password = cb[0].getPassword();

    // Get the private key
    PrivateKey privateKey = crypto.getPrivateKey(signatureUser, password);

    // Sign the request
    String jceSigAlgo = JCEMapper.translateURItoJCEID(sigAlgo);
    Signature signature = Signature.getInstance(jceSigAlgo);
    signature.initSign(privateKey);

    String requestToSign =
        SSOConstants.SAML_REQUEST + "=" + authnRequest + "&"
        + SSOConstants.RELAY_STATE + "=" + relayState + "&"
        + SSOConstants.SIG_ALG + "=" + URLEncoder.encode(sigAlgo, StandardCharsets.UTF_8.name());

    signature.update(requestToSign.getBytes(StandardCharsets.UTF_8));
    byte[] signBytes = signature.sign();

    String encodedSignature = Base64.getEncoder().encodeToString(signBytes);

    // Clean the private key from memory when we're done
    try {
        privateKey.destroy();
    } catch (DestroyFailedException ex) {
        // ignore
    }

    ub.queryParam(SSOConstants.SIGNATURE, URLEncoder.encode(encodedSignature, StandardCharsets.UTF_8.name()));

}
 
Example #24
Source File: SecurityHelper.java    From lams with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Randomly generates a Java JCE symmetric Key object from the specified XML Encryption algorithm URI.
 * 
 * @param algoURI  The XML Encryption algorithm URI
 * @return a randomly-generated symmteric key
 * @throws NoSuchProviderException  provider not found
 * @throws NoSuchAlgorithmException algorithm not found
 */
public static SecretKey generateKeyFromURI(String algoURI) 
        throws NoSuchAlgorithmException, NoSuchProviderException {
    String jceAlgorithmName = JCEMapper.getJCEKeyAlgorithmFromURI(algoURI);
    int keyLength = JCEMapper.getKeyLengthFromURI(algoURI);
    return generateKey(jceAlgorithmName, keyLength, null);
}
 
Example #25
Source File: SecurityHelper.java    From lams with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Get the Java security JCA/JCE algorithm identifier associated with an algorithm URI.
 * 
 * @param algorithmURI the algorithm URI to evaluate
 * @return the Java algorithm identifier, or null if the mapping is unavailable or indeterminable from the URI
 */
public static String getAlgorithmIDFromURI(String algorithmURI) {
    return DatatypeHelper.safeTrimOrNullString(JCEMapper.translateURItoJCEID(algorithmURI));
}
 
Example #26
Source File: SecurityHelper.java    From lams with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Check whether the signature method algorithm URI indicates HMAC.
 * 
 * @param signatureAlgorithm the signature method algorithm URI
 * @return true if URI indicates HMAC, false otherwise
 */
public static boolean isHMAC(String signatureAlgorithm) {
    String algoClass = DatatypeHelper.safeTrimOrNullString(JCEMapper.getAlgorithmClassFromURI(signatureAlgorithm));
    return ApacheXMLSecurityConstants.ALGO_CLASS_MAC.equals(algoClass);
}
 
Example #27
Source File: SecurityHelper.java    From lams with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Randomly generates a Java JCE KeyPair object from the specified XML Encryption algorithm URI.
 * 
 * @param algoURI  The XML Encryption algorithm URI
 * @param keyLength  the length of key to generate
 * @return a randomly-generated KeyPair
 * @throws NoSuchProviderException  provider not found
 * @throws NoSuchAlgorithmException  algorithm not found
 */
public static KeyPair generateKeyPairFromURI(String algoURI, int keyLength) 
        throws NoSuchAlgorithmException, NoSuchProviderException {
    String jceAlgorithmName = JCEMapper.getJCEKeyAlgorithmFromURI(algoURI);
    return generateKeyPair(jceAlgorithmName, keyLength, null);
}