org.opensaml.xml.security.SecurityHelper Java Examples

The following examples show how to use org.opensaml.xml.security.SecurityHelper. 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: SamlHelper.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
public Signature getDigitalSignature(KeyStore.PrivateKeyEntry keystoreEntry) {
    Signature signature = (Signature) Configuration.getBuilderFactory().getBuilder(Signature.DEFAULT_ELEMENT_NAME)
            .buildObject(Signature.DEFAULT_ELEMENT_NAME);

    Credential signingCredential = initializeCredentialsFromKeystore(keystoreEntry);
    signature.setSigningCredential(signingCredential);

    signature.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1);

    SecurityConfiguration secConfig = Configuration.getGlobalSecurityConfiguration();
    try {
        SecurityHelper.prepareSignatureParams(signature, signingCredential, secConfig, null);
    } catch (org.opensaml.xml.security.SecurityException  ex) {
        LOG.error("Error composing artifact resolution request: Failed to generate digital signature");
        throw new IllegalArgumentException("Couldn't compose artifact resolution request", ex);
    }

    return signature;
}
 
Example #2
Source File: KeyInfoHelper.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Build an {@link X509Digest} containing the digest of the specified certificate.
 * 
 * @param javaCert the Java X509Certificate to digest
 * @param algorithmURI  digest algorithm URI
 * @return a new X509Digest object
 * @throws NoSuchAlgorithmException if the algorithm specified cannot be used
 * @throws CertificateEncodingException if the certificate cannot be encoded
 */
public static X509Digest buildX509Digest(X509Certificate javaCert, String algorithmURI)
        throws NoSuchAlgorithmException, CertificateEncodingException {
    
    String jceAlg = SecurityHelper.getAlgorithmIDFromURI(algorithmURI);
    if (jceAlg == null) {
        throw new NoSuchAlgorithmException("No JCE algorithm found for " + algorithmURI);
    }
    MessageDigest md = MessageDigest.getInstance(jceAlg);
    byte[] hash = md.digest(javaCert.getEncoded());
    
    X509Digest xmlDigest = (X509Digest) Configuration.getBuilderFactory()
        .getBuilder(X509Digest.DEFAULT_ELEMENT_NAME)
        .buildObject(X509Digest.DEFAULT_ELEMENT_NAME);
    xmlDigest.setAlgorithm(algorithmURI);
    xmlDigest.setValue(Base64.encodeBytes(hash));
    
    return xmlDigest;
}
 
Example #3
Source File: EvaluableKeyLengthCredentialCriteria.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
public Boolean evaluate(Credential target) {
    if (target == null) {
        log.error("Credential target was null");
        return null;
    }
    Key key = getKey(target);
    if (key == null) {
        log.info("Could not evaluate criteria, credential contained no key");
        return null;
    }
    Integer length = SecurityHelper.getKeyLength(key);
    if (length == null) {
        log.info("Could not evaluate criteria, can not determine length of key");
        return null;
    }

    Boolean result = keyLength.equals(length);
    return result;
}
 
Example #4
Source File: Signer.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Signs a single XMLObject.
 * 
 * @param signature the signature to computer the signature on
 * @throws SignatureException thrown if there is an error computing the signature
 */
public static void signObject(Signature signature) throws SignatureException {
    Logger log = getLogger();
    try {
        XMLSignature xmlSignature = ((SignatureImpl) signature).getXMLSignature();

        if (xmlSignature == null) {
            log.error("Unable to compute signature, Signature XMLObject does not have the XMLSignature "
                    + "created during marshalling.");
            throw new SignatureException("XMLObject does not have an XMLSignature instance, unable to compute signature");
        }
        log.debug("Computing signature over XMLSignature object");
        xmlSignature.sign(SecurityHelper.extractSigningKey(signature.getSigningCredential()));
    } catch (XMLSecurityException e) {
        log.error("An error occured computing the digital signature", e);
        throw new SignatureException("Signature computation error", e);
    }
}
 
Example #5
Source File: SAML2HTTPRedirectDeflateSignatureValidator.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * @param queryString
 * @param issuer
 * @param alias
 * @param domainName
 * @return
 * @throws SecurityException
 * @throws IdentitySAML2SSOException
 */
@Override
public boolean validateSignature(String queryString, String issuer, String alias,
                                 String domainName) throws SecurityException,
        IdentitySAML2SSOException {
    byte[] signature = getSignature(queryString);
    byte[] signedContent = getSignedContent(queryString);
    String algorithmUri = getSigAlg(queryString);
    CriteriaSet criteriaSet = buildCriteriaSet(issuer);

    // creating the SAML2HTTPRedirectDeflateSignatureRule
    X509CredentialImpl credential =
            SAMLSSOUtil.getX509CredentialImplForTenant(domainName,
                    alias);

    List<Credential> credentials = new ArrayList<Credential>();
    credentials.add(credential);
    CollectionCredentialResolver credResolver = new CollectionCredentialResolver(credentials);
    KeyInfoCredentialResolver kiResolver = SecurityHelper.buildBasicInlineKeyInfoResolver();
    SignatureTrustEngine engine = new ExplicitKeySignatureTrustEngine(credResolver, kiResolver);
    return engine.validate(signature, signedContent, algorithmUri, criteriaSet, null);
}
 
Example #6
Source File: X509Util.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Determines the certificate, from the collection, associated with the private key.
 * 
 * @param certs certificates to check
 * @param privateKey entity's private key
 * 
 * @return the certificate associated with entity's private key or null if not certificate in the collection is
 *         associated with the given private key
 * 
 * @throws SecurityException thrown if the public or private keys checked are of an unsupported type
 * 
 * @since 1.2
 */
public static X509Certificate determineEntityCertificate(Collection<X509Certificate> certs, PrivateKey privateKey)
        throws SecurityException {
    if (certs == null || privateKey == null) {
        return null;
    }

    for (X509Certificate certificate : certs) {
        try {
            if (SecurityHelper.matchKeyPair(certificate.getPublicKey(), privateKey)) {
                return certificate;
            }
        } catch (SecurityException e) {
            // An exception here is just a false match.
            // Java 7 apparently throws in this case.
        }
    }

    return null;
}
 
Example #7
Source File: Encrypter.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Check key encryption parameters for consistency and required values.
 * 
 * @param kekParams the key encryption parameters to check
 * @param allowEmpty if false, a null parameter is treated as an error
 * 
 * @throws EncryptionException thrown if any parameters are missing or have invalid values
 */
protected void checkParams(KeyEncryptionParameters kekParams, boolean allowEmpty) throws EncryptionException {
    if (kekParams == null) {
        if (allowEmpty) {
            return;
        } else {
            log.error("Key encryption parameters are required");
            throw new EncryptionException("Key encryption parameters are required");
        }
    }
    Key key = SecurityHelper.extractEncryptionKey(kekParams.getEncryptionCredential());
    if (key == null) {
        log.error("Key encryption credential and contained key are required");
        throw new EncryptionException("Key encryption credential and contained key are required");
    } else if (key instanceof DSAPublicKey) {
        log.error("Attempt made to use DSA key for encrypted key transport");
        throw new EncryptionException("DSA keys may not be used for encrypted key transport");
    } else if (key instanceof ECPublicKey) {
        log.error("Attempt made to use EC key for encrypted key transport");
        throw new EncryptionException("EC keys may not be used for encrypted key transport");
    } else if (DatatypeHelper.isEmpty(kekParams.getAlgorithm())) {
        log.error("Key encryption algorithm URI is required");
        throw new EncryptionException("Key encryption algorithm URI is required");
    }
}
 
Example #8
Source File: Encrypter.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Encrypts a key.
 * 
 * @param key the key to encrypt
 * @param kekParams parameters for encrypting the key
 * @param containingDocument the document that will own the DOM element underlying the resulting EncryptedKey object
 * 
 * @return the resulting EncryptedKey object
 * 
 * @throws EncryptionException exception thrown on encryption errors
 */
public EncryptedKey encryptKey(Key key, KeyEncryptionParameters kekParams, Document containingDocument)
        throws EncryptionException {

    checkParams(kekParams, false);

    Key encryptionKey = SecurityHelper.extractEncryptionKey(kekParams.getEncryptionCredential());
    String encryptionAlgorithmURI = kekParams.getAlgorithm();

    EncryptedKey encryptedKey = encryptKey(key, encryptionKey, encryptionAlgorithmURI, containingDocument);

    if (kekParams.getKeyInfoGenerator() != null) {
        KeyInfoGenerator generator = kekParams.getKeyInfoGenerator();
        log.debug("Dynamically generating KeyInfo from Credential for EncryptedKey using generator: {}",
                generator.getClass().getName());
        try {
            encryptedKey.setKeyInfo(generator.generate(kekParams.getEncryptionCredential()));
        } catch (SecurityException e) {
            log.error("Error during EncryptedKey KeyInfo generation", e);
            throw new EncryptionException("Error during EncryptedKey KeyInfo generation", e);
        }
    }

    if (kekParams.getRecipient() != null) {
        encryptedKey.setRecipient(kekParams.getRecipient());
    }

    return encryptedKey;
}
 
Example #9
Source File: DefaultSSOEncrypter.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
@Override
public EncryptedAssertion doEncryptedAssertion(Assertion assertion, X509Credential cred, String alias, String encryptionAlgorithm) throws IdentityException {
    try {

        Credential symmetricCredential = SecurityHelper.getSimpleCredential(
                SecurityHelper.generateSymmetricKey(EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES256));

        EncryptionParameters encParams = new EncryptionParameters();
        encParams.setAlgorithm(EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES256);
        encParams.setEncryptionCredential(symmetricCredential);

        KeyEncryptionParameters keyEncryptionParameters = new KeyEncryptionParameters();
        keyEncryptionParameters.setAlgorithm(EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSA15);
        keyEncryptionParameters.setEncryptionCredential(cred);

        Encrypter encrypter = new Encrypter(encParams, keyEncryptionParameters);
        encrypter.setKeyPlacement(Encrypter.KeyPlacement.INLINE);

        EncryptedAssertion encrypted = encrypter.encrypt(assertion);
        return encrypted;
    } catch (Exception e) {
        throw IdentityException.error("Error while Encrypting Assertion", e);
    }
}
 
Example #10
Source File: Encrypter.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Encrypt the specified XMLObject, and return it as an instance of the specified QName,
 * which should be one of the types derived from {@link org.opensaml.saml2.core.EncryptedElementType}.
 * 
 * @param xmlObject the XMLObject to encrypt
 * @param encElementName the QName of the specialization of EncryptedElementType to return
 * @return a specialization of {@link org.opensaml.saml2.core.EncryptedElementType}
 * @throws EncryptionException thrown when encryption generates an error
 */
private EncryptedElementType encrypt(XMLObject xmlObject, QName encElementName) throws EncryptionException {
    
    checkParams(encParams, kekParamsList);
   
    EncryptedElementType encElement = 
        (EncryptedElementType) builderFactory.getBuilder(encElementName).buildObject(encElementName);
    
    // Marshall the containing element, we will need its Document context to pass 
    // to the key encryption method
    checkAndMarshall(encElement);
    Document ownerDocument = encElement.getDOM().getOwnerDocument();
    
    String encryptionAlgorithmURI = encParams.getAlgorithm();
    Key encryptionKey = SecurityHelper.extractEncryptionKey(encParams.getEncryptionCredential());
    if (encryptionKey == null) {
        encryptionKey = generateEncryptionKey(encryptionAlgorithmURI);
    }
    
    EncryptedData encryptedData = encryptElement(xmlObject, encryptionKey, encryptionAlgorithmURI, false);
    if (encParams.getKeyInfoGenerator() != null) {
        KeyInfoGenerator generator = encParams.getKeyInfoGenerator();
        log.debug("Dynamically generating KeyInfo from Credential for EncryptedData using generator: {}",
                generator.getClass().getName());
        try {
            encryptedData.setKeyInfo( generator.generate(encParams.getEncryptionCredential()) );
        } catch (SecurityException e) {
            throw new EncryptionException("Error generating EncryptedData KeyInfo", e);
        }
    }
    
    List<EncryptedKey> encryptedKeys = new ArrayList<EncryptedKey>();
    if (kekParamsList != null && ! kekParamsList.isEmpty()) {
        encryptedKeys.addAll( encryptKey(encryptionKey, kekParamsList, ownerDocument) );
    }
    
    return processElements(encElement, encryptedData, encryptedKeys);
}
 
Example #11
Source File: HTTPPostSimpleSignEncoder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
protected void populateVelocityContext(VelocityContext velocityContext, SAMLMessageContext messageContext,
        String endpointURL) throws MessageEncodingException {

    super.populateVelocityContext(velocityContext, messageContext, endpointURL);

    Credential signingCredential = messageContext.getOuboundSAMLMessageSigningCredential();
    if (signingCredential == null) {
        log.debug("No signing credential was supplied, skipping HTTP-Post simple signing");
        return;
    }

    // TODO pull SecurityConfiguration from SAMLMessageContext? needs to be added
    // TODO pull binding-specific keyInfoGenName from encoder setting, etc?
    String sigAlgURI = getSignatureAlgorithmURI(signingCredential, null);
    velocityContext.put("SigAlg", sigAlgURI);

    String formControlData = buildFormDataToSign(velocityContext, messageContext, sigAlgURI);
    velocityContext.put("Signature", generateSignature(signingCredential, sigAlgURI, formControlData));

    KeyInfoGenerator kiGenerator = SecurityHelper.getKeyInfoGenerator(signingCredential, null, null);
    if (kiGenerator != null) {
        String kiBase64 = buildKeyInfo(signingCredential, kiGenerator);
        if (!DatatypeHelper.isEmpty(kiBase64)) {
            velocityContext.put("KeyInfo", kiBase64);
        }
    }
}
 
Example #12
Source File: Encrypter.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Check the encryption parameters and key encryption parameters for valid combinations of options.
 * 
 * @param encParams the encryption parameters to use
 * @param kekParamsList the key encryption parameters to use
 * @throws EncryptionException exception thrown on encryption errors
 */
protected void checkParams(EncryptionParameters encParams, List<KeyEncryptionParameters> kekParamsList)
        throws EncryptionException {

    checkParams(encParams);
    checkParams(kekParamsList, true);

    if (SecurityHelper.extractEncryptionKey(encParams.getEncryptionCredential()) == null
            && (kekParamsList == null || kekParamsList.isEmpty())) {
        log.error("Using a generated encryption key requires a KeyEncryptionParameters "
                + "object and key encryption key");
        throw new EncryptionException("Using a generated encryption key requires a KeyEncryptionParameters "
                + "object and key encryption key");
    }
}
 
Example #13
Source File: Encrypter.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Encrypts the given XMLObject using the specified encryption key, algorithm URI and content mode flag.
 * EncryptedKeys, if any, are placed inline within the KeyInfo of the resulting EncryptedData.
 * 
 * @param xmlObject the XMLObject to be encrypted
 * @param encParams the encryption parameters to use
 * @param kekParamsList the key encryption parameters to use
 * @param encryptContentMode whether just the content of the XMLObject should be encrypted
 * 
 * @return the resulting EncryptedData object
 * @throws EncryptionException exception thrown on encryption errors
 */
private EncryptedData encryptElement(XMLObject xmlObject, EncryptionParameters encParams,
        List<KeyEncryptionParameters> kekParamsList, boolean encryptContentMode) throws EncryptionException {

    checkParams(encParams, kekParamsList);

    String encryptionAlgorithmURI = encParams.getAlgorithm();
    Key encryptionKey = SecurityHelper.extractEncryptionKey(encParams.getEncryptionCredential());
    if (encryptionKey == null) {
        encryptionKey = generateEncryptionKey(encryptionAlgorithmURI);
    }

    EncryptedData encryptedData = encryptElement(xmlObject, encryptionKey, encryptionAlgorithmURI,
            encryptContentMode);
    Document ownerDocument = encryptedData.getDOM().getOwnerDocument();

    if (encParams.getKeyInfoGenerator() != null) {
        KeyInfoGenerator generator = encParams.getKeyInfoGenerator();
        log.debug("Dynamically generating KeyInfo from Credential for EncryptedData using generator: {}",
                generator.getClass().getName());
        try {
            encryptedData.setKeyInfo(generator.generate(encParams.getEncryptionCredential()));
        } catch (SecurityException e) {
            log.error("Error during EncryptedData KeyInfo generation", e);
            throw new EncryptionException("Error during EncryptedData KeyInfo generation", e);
        }
    }

    for (KeyEncryptionParameters kekParams : kekParamsList) {
        EncryptedKey encryptedKey = encryptKey(encryptionKey, kekParams, ownerDocument);
        if (encryptedData.getKeyInfo() == null) {
            KeyInfo keyInfo = keyInfoBuilder.buildObject();
            encryptedData.setKeyInfo(keyInfo);
        }
        encryptedData.getKeyInfo().getEncryptedKeys().add(encryptedKey);
    }

    return encryptedData;
}
 
Example #14
Source File: Decrypter.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Dynamically construct key length credential criteria based on the specified algorithm URI.
 * 
 * @param encAlgorithmURI the algorithm URI
 * @return a new key length credential criteria instance, or null if the value could not be determined
 */
private KeyLengthCriteria buildKeyLengthCriteria(String encAlgorithmURI) {
    if (!DatatypeHelper.isEmpty(encAlgorithmURI)) {
        return null;
    }

    Integer keyLength = SecurityHelper.getKeyLengthFromURI(encAlgorithmURI);
    if (keyLength != null) {
        return new KeyLengthCriteria(keyLength);
    }

    return null;
}
 
Example #15
Source File: Decrypter.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Dynamically construct key algorithm credential criteria based on the specified algorithm URI.
 * 
 * @param encAlgorithmURI the algorithm URI
 * @return a new key algorithm credential criteria instance, or null if criteria could not be determined
 */
private KeyAlgorithmCriteria buildKeyAlgorithmCriteria(String encAlgorithmURI) {
    if (DatatypeHelper.isEmpty(encAlgorithmURI)) {
        return null;
    }

    String jcaKeyAlgorithm = SecurityHelper.getKeyAlgorithmFromURI(encAlgorithmURI);
    if (!DatatypeHelper.isEmpty(jcaKeyAlgorithm)) {
        return new KeyAlgorithmCriteria(jcaKeyAlgorithm);
    }

    return null;
}
 
Example #16
Source File: PKIXSignatureTrustEngine.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
public boolean validate(byte[] signature, byte[] content, String algorithmURI, CriteriaSet trustBasisCriteria,
        Credential candidateCredential) throws SecurityException {

    if (candidateCredential == null || SecurityHelper.extractVerificationKey(candidateCredential) == null) {
        log.debug("Candidate credential was either not supplied or did not contain verification key");
        log.debug("PKIX trust engine requires supplied key, skipping PKIX trust evaluation");
        return false;
    }

    checkParamsRaw(signature, content, algorithmURI, trustBasisCriteria);

    Pair<Set<String>, Iterable<PKIXValidationInformation>> validationPair = 
        resolveValidationInfo(trustBasisCriteria);

    try {
        if (SigningUtil.verifyWithURI(candidateCredential, algorithmURI, signature, content)) {
            log.debug("Successfully verified raw signature using supplied candidate credential");
            log.debug("Attempting to establish trust of supplied candidate credential");
            if (evaluateTrust(candidateCredential, validationPair)) {
                log.debug("Successfully established trust of supplied candidate credential");
                return true;
            } else {
                log.debug("Failed to establish trust of supplied candidate credential");
            }
        } else {
            log.debug("Cryptographic verification of raw signature failed with candidate credential");
        }
    } catch (SecurityException e) {
        // Java 7 now throws this exception under conditions such as mismatched key sizes.
        // Swallow this, it's logged by the verifyWithURI method already.
    }

    log.debug("PKIX validation of raw signature failed, "
            + "unable to establish trust of supplied verification credential");
    return false;
}
 
Example #17
Source File: ExplicitKeySignatureTrustEngine.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
public boolean validate(Signature signature, CriteriaSet trustBasisCriteria) throws SecurityException {

    checkParams(signature, trustBasisCriteria);

    CriteriaSet criteriaSet = new CriteriaSet();
    criteriaSet.addAll(trustBasisCriteria);
    if (!criteriaSet.contains(UsageCriteria.class)) {
        criteriaSet.add(new UsageCriteria(UsageType.SIGNING));
    }
    String jcaAlgorithm = SecurityHelper.getKeyAlgorithmFromURI(signature.getSignatureAlgorithm());
    if (!DatatypeHelper.isEmpty(jcaAlgorithm)) {
        criteriaSet.add(new KeyAlgorithmCriteria(jcaAlgorithm), true);
    }

    Iterable<Credential> trustedCredentials = getCredentialResolver().resolve(criteriaSet);

    if (validate(signature, trustedCredentials)) {
        return true;
    }

    // If the credentials extracted from Signature's KeyInfo (if any) did not verify the
    // signature and/or establish trust, as a fall back attempt to verify the signature with
    // the trusted credentials directly.
    log.debug("Attempting to verify signature using trusted credentials");

    for (Credential trustedCredential : trustedCredentials) {
        if (verifySignature(signature, trustedCredential)) {
            log.debug("Successfully verified signature using resolved trusted credential");
            return true;
        }
    }
    log.debug("Failed to verify signature using either KeyInfo-derived or directly trusted credentials");
    return false;
}
 
Example #18
Source File: SignatureValidator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
public void validate(Signature signature) throws ValidationException {
    log.debug("Attempting to validate signature using key from supplied credential");

    XMLSignature xmlSig = buildSignature(signature);

    Key validationKey = SecurityHelper.extractVerificationKey(validationCredential);
    if (validationKey == null) {
        log.debug("Supplied credential contained no key suitable for signature validation");
        throw new ValidationException("No key available to validate signature");
    }
    
    log.debug("Validating signature with signature algorithm URI: {}", signature.getSignatureAlgorithm());
    log.debug("Validation credential key algorithm '{}', key instance class '{}'", 
            validationKey.getAlgorithm(), validationKey.getClass().getName());

    try {
        if (xmlSig.checkSignatureValue(validationKey)) {
            log.debug("Signature validated with key from supplied credential");
            return;
        }
    } catch (XMLSignatureException e) {
        throw new ValidationException("Unable to evaluate key against signature", e);
    }

    log.debug("Signature did not validate against the credential's key");

    throw new ValidationException("Signature did not validate against the credential's key");
}
 
Example #19
Source File: BasicProviderKeyInfoCredentialResolver.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Construct a basic credential containing the specified key and set of key names.
 * 
 * @param key the key to include in the credential
 * @param keyNames the key names to include in the credential
 * @return a basic credential with the specified key and key names
 * @throws SecurityException if there is an error building the credential
 */
protected Credential buildBasicCredential(Key key, Set<String> keyNames) throws SecurityException {
    if (key == null) {
        log.debug("Key supplied was null, could not build credential");
        return null;
    }

    BasicCredential basicCred = new BasicCredential();

    basicCred.getKeyNames().addAll(keyNames);

    if (key instanceof PublicKey) {
        basicCred.setPublicKey((PublicKey) key);
    } else if (key instanceof SecretKey) {
        basicCred.setSecretKey((SecretKey) key);
    } else if (key instanceof PrivateKey) {
        // This would be unusual for most KeyInfo use cases,
        // but go ahead and try and handle it
        PrivateKey privateKey = (PrivateKey) key;
        try {
            PublicKey publicKey = SecurityHelper.derivePublicKey(privateKey);
            if (publicKey != null) {
                basicCred.setPublicKey(publicKey);
                basicCred.setPrivateKey(privateKey);
            } else {
                log.error("Failed to derive public key from private key");
                return null;
            }
        } catch (KeyException e) {
            log.error("Could not derive public key from private key", e);
            return null;
        }
    } else {
        log.error(String.format("Key was of an unsupported type '%s'", key.getClass().getName()));
        return null;
    }

    return basicCred;
}
 
Example #20
Source File: WebServicePostEncoder.java    From MaxKey with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("rawtypes")
protected void populateVelocityContext(VelocityContext velocityContext,
		SAMLMessageContext messageContext) throws MessageEncodingException {

	log.debug("Marshalling and Base64 encoding SAML message");
	if (messageContext.getOutboundSAMLMessage().getDOM() == null) {
		marshallMessage(messageContext.getOutboundSAMLMessage());
	}
	try {
		String messageXML = XMLHelper.nodeToString(messageContext.getOutboundSAMLMessage().getDOM());
		String encodedMessage = Base64.encodeBytes(
				messageXML.getBytes("UTF-8"), Base64.DONT_BREAK_LINES);
		if (messageContext.getOutboundSAMLMessage() instanceof RequestAbstractType) {
			velocityContext.put("SAMLRequest", encodedMessage);
		} else if (messageContext.getOutboundSAMLMessage() instanceof StatusResponseType) {
			velocityContext.put("SAMLResponse", encodedMessage);
		} else {
			throw new MessageEncodingException(
					"SAML message is neither a SAML RequestAbstractType or StatusResponseType");
		}
	} catch (UnsupportedEncodingException e) {
		log.error("UTF-8 encoding is not supported, this VM is not Java compliant.");
		throw new MessageEncodingException(
				"Unable to encode message, UTF-8 encoding is not supported");
	}

	Credential signingCredential = messageContext.getOuboundSAMLMessageSigningCredential();
	if (signingCredential == null) {
		log.debug("No signing credential was supplied, skipping HTTP-Post simple signing");
		return;
	}

	String sigAlgURI = getSignatureAlgorithmURI(signingCredential, null);
	velocityContext.put("SigAlg", sigAlgURI);

	String formControlData = buildFormDataToSign(velocityContext,messageContext, sigAlgURI);
	velocityContext.put("Signature",generateSignature(signingCredential, sigAlgURI,formControlData));

	KeyInfoGenerator kiGenerator = SecurityHelper.getKeyInfoGenerator(signingCredential, null, null);
	
	if (kiGenerator != null) {
		String kiBase64 = buildKeyInfo(signingCredential, kiGenerator);
		if (!DatatypeHelper.isEmpty(kiBase64)) {
			velocityContext.put("KeyInfo", kiBase64);
		}
	}
}