org.opensaml.security.x509.BasicX509Credential Java Examples

The following examples show how to use org.opensaml.security.x509.BasicX509Credential. 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: MockSamlIdpServer.java    From deprecated-security-advanced-modules with Apache License 2.0 6 votes vote down vote up
void loadSigningKeys(String path, String alias) {
    try {
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());

        KeyStore keyStore = KeyStore.getInstance("JKS");
        InputStream keyStream = new FileInputStream(FileHelper.getAbsoluteFilePathFromClassPath(path).toFile());

        keyStore.load(keyStream, "changeit".toCharArray());
        kmf.init(keyStore, "changeit".toCharArray());

        this.signingCertificate = (X509Certificate) keyStore.getCertificate(alias);

        this.signingCredential = new BasicX509Credential(this.signingCertificate,
                (PrivateKey) keyStore.getKey(alias, "changeit".toCharArray()));

    } catch (NoSuchAlgorithmException | KeyStoreException | CertificateException | IOException
            | UnrecoverableKeyException e) {
        throw new RuntimeException(e);
    }
}
 
Example #2
Source File: WSXACMLMessageReceiver.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Create basic credentials needed to generate signature using EntitlementServiceComponent
 *
 * @return basicX509Credential
 */
private static BasicX509Credential createBasicCredentials() {

    Certificate certificate = null;
    PrivateKey issuerPK = null;

    KeyStoreManager keyMan = KeyStoreManager.getInstance(-1234);

    try {
        certificate = keyMan.getDefaultPrimaryCertificate();
        issuerPK = keyMan.getDefaultPrivateKey();
    } catch (Exception e) {
        log.error("Error occurred while getting the KeyStore from KeyManger.", e);
    }

    BasicX509Credential basicCredential = new BasicX509Credential((java.security.cert.X509Certificate) certificate, issuerPK);

    return basicCredential;
}
 
Example #3
Source File: MockSamlIdpServer.java    From deprecated-security-advanced-modules with Apache License 2.0 5 votes vote down vote up
private SignatureTrustEngine buildSignatureTrustEngine(X509Certificate certificate) {
    CredentialResolver credentialResolver = new StaticCredentialResolver(new BasicX509Credential(certificate));
    KeyInfoCredentialResolver keyInfoCredentialResolver = new StaticKeyInfoCredentialResolver(
            new BasicX509Credential(certificate));

    return new ExplicitKeySignatureTrustEngine(credentialResolver, keyInfoCredentialResolver);
}
 
Example #4
Source File: SamlClient.java    From saml-client with MIT License 5 votes vote down vote up
/**
 * generate an X509Credential from the provided key and cert.
 *
 * @param publicKey  the public key
 * @param privateKey the private key
 * @throws SamlException if publicKey and privateKey don't form a valid credential
 */
private BasicX509Credential generateBasicX509Credential(String publicKey, String privateKey) throws SamlException {
  if (publicKey == null || privateKey == null) {
    throw new SamlException("No credentials provided");
  }
  PrivateKey pk = loadPrivateKey(privateKey);
  X509Certificate cert = loadCertificate(publicKey);
  return new BasicX509Credential(cert, pk);
}
 
Example #5
Source File: IdpTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
private static void signAuthnRequest(SignableSAMLObject signableObject) throws Exception {
    Crypto crypto = CryptoFactory.getInstance("stsKeystoreA.properties");

    CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
    cryptoType.setAlias("realma");
    X509Certificate[] issuerCerts = crypto.getX509Certificates(cryptoType);

    String sigAlgo = SSOConstants.RSA_SHA1;

    // Get the private key
    PrivateKey privateKey = crypto.getPrivateKey("realma", "realma");

    // Create the signature
    Signature signature = OpenSAMLUtil.buildSignature();
    signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
    signature.setSignatureAlgorithm(sigAlgo);

    BasicX509Credential signingCredential = new BasicX509Credential(issuerCerts[0], privateKey);

    signature.setSigningCredential(signingCredential);

    X509KeyInfoGeneratorFactory kiFactory = new X509KeyInfoGeneratorFactory();
    kiFactory.setEmitEntityCertificate(true);

    try {
        KeyInfo keyInfo = kiFactory.newInstance().generate(signingCredential);
        signature.setKeyInfo(keyInfo);
    } catch (org.opensaml.security.SecurityException ex) {
        throw new Exception(
                "Error generating KeyInfo from signing credential", ex);
    }

    signableObject.setSignature(signature);
    signableObject.releaseDOM();
    signableObject.releaseChildrenDOM(true);

}
 
Example #6
Source File: MockSamlIdpServer.java    From deprecated-security-advanced-modules with Apache License 2.0 4 votes vote down vote up
private String createMetadata() {
    try {
        EntityDescriptor idpEntityDescriptor = createSamlElement(EntityDescriptor.class);
        idpEntityDescriptor.setEntityID(idpEntityId);

        IDPSSODescriptor idpSsoDescriptor = createSamlElement(IDPSSODescriptor.class);
        idpEntityDescriptor.getRoleDescriptors().add(idpSsoDescriptor);

        idpSsoDescriptor.setWantAuthnRequestsSigned(wantAuthnRequestsSigned);
        idpSsoDescriptor.addSupportedProtocol(SAMLConstants.SAML20P_NS);

        SingleLogoutService redirectSingleLogoutService = createSamlElement(SingleLogoutService.class);
        idpSsoDescriptor.getSingleLogoutServices().add(redirectSingleLogoutService);

        redirectSingleLogoutService.setBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect");
        redirectSingleLogoutService.setLocation(getSamlSloUri());

        idpSsoDescriptor.getNameIDFormats()
                .add(createNameIDFormat("urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified"));

        SingleSignOnService redirectSingleSignOnService = createSamlElement(SingleSignOnService.class);
        idpSsoDescriptor.getSingleSignOnServices().add(redirectSingleSignOnService);

        redirectSingleSignOnService.setBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect");
        redirectSingleSignOnService.setLocation(getSamlSsoUri());

        X509KeyInfoGeneratorFactory keyInfoGeneratorFactory = new X509KeyInfoGeneratorFactory();
        keyInfoGeneratorFactory.setEmitEntityCertificate(true);
        KeyInfoGenerator keyInfoGenerator = keyInfoGeneratorFactory.newInstance();

        KeyDescriptor signingKeyDescriptor = createSamlElement(KeyDescriptor.class);
        idpSsoDescriptor.getKeyDescriptors().add(signingKeyDescriptor);

        signingKeyDescriptor.setUse(UsageType.SIGNING);

        signingKeyDescriptor
                .setKeyInfo(keyInfoGenerator.generate(new BasicX509Credential(this.signingCertificate)));

        return marshallSamlXml(idpEntityDescriptor);
    } catch (org.opensaml.security.SecurityException e) {
        throw new RuntimeException(e);
    }
}
 
Example #7
Source File: SamlClient.java    From saml-client with MIT License 4 votes vote down vote up
private static Credential getCredential(X509Certificate certificate) {
  BasicX509Credential credential = new BasicX509Credential(certificate);
  credential.setCRLs(Collections.emptyList());
  return credential;
}
 
Example #8
Source File: SAMLResponseValidatorTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
/**
 * Sign a SAML Response
 * @throws Exception
 */
private void signResponse(
    Response response,
    String issuerKeyName,
    String issuerKeyPassword,
    Crypto issuerCrypto,
    boolean useKeyInfo
) throws Exception {
    //
    // Create the signature
    //
    Signature signature = OpenSAMLUtil.buildSignature();
    signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);

    // prepare to sign the SAML token
    CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
    cryptoType.setAlias(issuerKeyName);
    X509Certificate[] issuerCerts = issuerCrypto.getX509Certificates(cryptoType);
    if (issuerCerts == null) {
        throw new Exception(
                "No issuer certs were found to sign the SAML Assertion using issuer name: "
                        + issuerKeyName);
    }

    String sigAlgo = SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1;
    String pubKeyAlgo = issuerCerts[0].getPublicKey().getAlgorithm();

    if ("DSA".equalsIgnoreCase(pubKeyAlgo)) {
        sigAlgo = SignatureConstants.ALGO_ID_SIGNATURE_DSA;
    }

    PrivateKey privateKey = issuerCrypto.getPrivateKey(issuerKeyName, issuerKeyPassword);

    signature.setSignatureAlgorithm(sigAlgo);

    BasicX509Credential signingCredential =
        new BasicX509Credential(issuerCerts[0], privateKey);
    signature.setSigningCredential(signingCredential);

    if (useKeyInfo) {
        X509KeyInfoGeneratorFactory kiFactory = new X509KeyInfoGeneratorFactory();
        kiFactory.setEmitEntityCertificate(true);

        try {
            KeyInfo keyInfo = kiFactory.newInstance().generate(signingCredential);
            signature.setKeyInfo(keyInfo);
        } catch (org.opensaml.security.SecurityException ex) {
            throw new Exception(
                    "Error generating KeyInfo from signing credential", ex);
        }
    }

    // add the signature to the assertion
    SignableSAMLObject signableObject = response;
    signableObject.setSignature(signature);
    signableObject.releaseDOM();
    signableObject.releaseChildrenDOM(true);
}
 
Example #9
Source File: SAMLSSOResponseValidatorTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
/**
 * Sign a SAML Response
 * @throws Exception
 */
private void signResponse(
    Response response,
    String issuerKeyName,
    String issuerKeyPassword,
    Crypto issuerCrypto,
    boolean useKeyInfo
) throws Exception {
    //
    // Create the signature
    //
    Signature signature = OpenSAMLUtil.buildSignature();
    signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);

    // prepare to sign the SAML token
    CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
    cryptoType.setAlias(issuerKeyName);
    X509Certificate[] issuerCerts = issuerCrypto.getX509Certificates(cryptoType);
    if (issuerCerts == null) {
        throw new Exception(
                "No issuer certs were found to sign the SAML Assertion using issuer name: "
                        + issuerKeyName);
    }

    String sigAlgo = SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1;
    String pubKeyAlgo = issuerCerts[0].getPublicKey().getAlgorithm();

    if ("DSA".equalsIgnoreCase(pubKeyAlgo)) {
        sigAlgo = SignatureConstants.ALGO_ID_SIGNATURE_DSA;
    }

    PrivateKey privateKey = issuerCrypto.getPrivateKey(issuerKeyName, issuerKeyPassword);

    signature.setSignatureAlgorithm(sigAlgo);

    BasicX509Credential signingCredential = new BasicX509Credential(issuerCerts[0], privateKey);

    signature.setSigningCredential(signingCredential);

    if (useKeyInfo) {
        X509KeyInfoGeneratorFactory kiFactory = new X509KeyInfoGeneratorFactory();
        kiFactory.setEmitEntityCertificate(true);

        try {
            KeyInfo keyInfo = kiFactory.newInstance().generate(signingCredential);
            signature.setKeyInfo(keyInfo);
        } catch (org.opensaml.security.SecurityException ex) {
            throw new Exception(
                    "Error generating KeyInfo from signing credential", ex);
        }
    }

    // add the signature to the assertion
    SignableSAMLObject signableObject = response;
    signableObject.setSignature(signature);
    signableObject.releaseDOM();
    signableObject.releaseChildrenDOM(true);
}
 
Example #10
Source File: CombinedValidatorTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
private void signResponse(
    Response response,
    String issuerKeyName,
    String issuerKeyPassword,
    Crypto issuerCrypto,
    boolean useKeyInfo
) throws Exception {
    //
    // Create the signature
    //
    Signature signature = OpenSAMLUtil.buildSignature();
    signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);

    // prepare to sign the SAML token
    CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
    cryptoType.setAlias(issuerKeyName);
    X509Certificate[] issuerCerts = issuerCrypto.getX509Certificates(cryptoType);
    if (issuerCerts == null) {
        throw new Exception(
            "No issuer certs were found to sign the SAML Assertion using issuer name: " + issuerKeyName);
    }

    String sigAlgo = SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1;
    String pubKeyAlgo = issuerCerts[0].getPublicKey().getAlgorithm();

    if ("DSA".equalsIgnoreCase(pubKeyAlgo)) {
        sigAlgo = SignatureConstants.ALGO_ID_SIGNATURE_DSA;
    }

    PrivateKey privateKey = issuerCrypto.getPrivateKey(issuerKeyName, issuerKeyPassword);

    signature.setSignatureAlgorithm(sigAlgo);

    BasicX509Credential signingCredential =
        new BasicX509Credential(issuerCerts[0], privateKey);
    signature.setSigningCredential(signingCredential);

    if (useKeyInfo) {
        X509KeyInfoGeneratorFactory kiFactory = new X509KeyInfoGeneratorFactory();
        kiFactory.setEmitEntityCertificate(true);

        try {
            KeyInfo keyInfo = kiFactory.newInstance().generate(signingCredential);
            signature.setKeyInfo(keyInfo);
        } catch (org.opensaml.security.SecurityException ex) {
            throw new Exception("Error generating KeyInfo from signing credential", ex);
        }
    }

    // add the signature to the assertion
    SignableSAMLObject signableObject = response;
    signableObject.setSignature(signature);
    signableObject.releaseDOM();
    signableObject.releaseChildrenDOM(true);
}
 
Example #11
Source File: SAMLProcessorImpl.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
private void decryptEncryptedAssertions(org.opensaml.saml.saml2.core.Response responseObject, FedizContext config)
        throws ProcessingException {
    if (responseObject.getEncryptedAssertions() != null && !responseObject.getEncryptedAssertions().isEmpty()) {
        KeyManager decryptionKeyManager = config.getDecryptionKey();
        if (decryptionKeyManager == null || decryptionKeyManager.getCrypto() == null) {
            LOG.debug("We must have a decryption Crypto instance configured to decrypt encrypted tokens");
            throw new ProcessingException(TYPE.BAD_REQUEST);
        }
        String keyPassword = decryptionKeyManager.getKeyPassword();
        if (keyPassword == null) {
            LOG.debug("We must have a decryption key password to decrypt encrypted tokens");
            throw new ProcessingException(TYPE.BAD_REQUEST);
        }
 
        String keyAlias = decryptionKeyManager.getKeyAlias();
        if (keyAlias == null) {
            LOG.debug("No alias configured for decrypt");
            throw new ProcessingException(TYPE.BAD_REQUEST);
        }
        
        try {
            // Get the private key
            PrivateKey privateKey = decryptionKeyManager.getCrypto().getPrivateKey(keyAlias, keyPassword);
            if (privateKey == null) {
                LOG.debug("No private key available");
                throw new ProcessingException(TYPE.BAD_REQUEST);
            }
            
            BasicX509Credential cred = new BasicX509Credential(
                CertsUtils.getX509CertificateFromCrypto(decryptionKeyManager.getCrypto(), keyAlias));
            cred.setPrivateKey(privateKey);
            
            StaticKeyInfoCredentialResolver resolver = new StaticKeyInfoCredentialResolver(cred);
            
            ChainingEncryptedKeyResolver keyResolver = new ChainingEncryptedKeyResolver(
                    Arrays.<EncryptedKeyResolver>asList(
                            new InlineEncryptedKeyResolver(),
                            new EncryptedElementTypeEncryptedKeyResolver(), 
                            new SimpleRetrievalMethodEncryptedKeyResolver(),
                            new SimpleKeyInfoReferenceEncryptedKeyResolver()));
            
            Decrypter decrypter = new Decrypter(null, resolver, keyResolver);
            
            for (EncryptedAssertion encryptedAssertion : responseObject.getEncryptedAssertions()) {
            
                Assertion decrypted = decrypter.decrypt(encryptedAssertion);
                Element decryptedToken = decrypted.getDOM();
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Decrypted assertion: {}", DOM2Writer.nodeToString(decryptedToken));
                }
                responseObject.getAssertions().add(decrypted);
                // Add the decrypted Assertion to the Response DOM, as otherwise there's a problem with
                // doc.getElementById() when trying to verify the signature of the decrypted assertion
                decryptedToken.getOwnerDocument().getDocumentElement().appendChild(decryptedToken);
            }
        } catch (Exception e) {
            LOG.debug("Cannot decrypt assertions", e);
            throw new ProcessingException(TYPE.BAD_REQUEST);
        }
    }
}
 
Example #12
Source File: SamlClient.java    From saml-client with MIT License 3 votes vote down vote up
/**
 * Set service provider keys.
 *
 * @param certificate the certificate
 * @param privateKey the private key
 * @throws SamlException if publicKey and privateKey don't form a valid credential
 */
public void setSPKeys(X509Certificate certificate, PrivateKey privateKey) throws SamlException {
  if (certificate == null || privateKey == null) {
    throw new SamlException("No credentials provided");
  }
  spCredential = new BasicX509Credential(certificate, privateKey);
}
 
Example #13
Source File: SamlClient.java    From saml-client with MIT License 2 votes vote down vote up
/**
 * Add an additional service provider certificate/key pair for decryption.
 *
 * @param certificate the certificate
 * @param privateKey the private key
 * @throws SamlException if publicKey and privateKey don't form a valid credential
 */
public void addAdditionalSPKey(X509Certificate certificate, PrivateKey privateKey) throws SamlException {
  additionalSpCredentials.add(new BasicX509Credential(certificate, privateKey));
}