Search in sources :

Example 86 with PrivateKey

use of java.security.PrivateKey in project platform_frameworks_base by android.

the class WifiEnterpriseConfigTest method testSetClientKeyEntryWithNull.

@Test
public void testSetClientKeyEntryWithNull() {
    mEnterpriseConfig.setClientKeyEntry(null, null);
    assertNull(mEnterpriseConfig.getClientCertificateChain());
    assertNull(mEnterpriseConfig.getClientCertificate());
    mEnterpriseConfig.setClientKeyEntryWithCertificateChain(null, null);
    assertNull(mEnterpriseConfig.getClientCertificateChain());
    assertNull(mEnterpriseConfig.getClientCertificate());
    // Setting the client certificate to null should clear the existing chain.
    PrivateKey clientKey = FakeKeys.RSA_KEY1;
    X509Certificate clientCert0 = FakeKeys.CLIENT_CERT;
    X509Certificate clientCert1 = FakeKeys.CA_CERT1;
    mEnterpriseConfig.setClientKeyEntry(clientKey, clientCert0);
    assertNotNull(mEnterpriseConfig.getClientCertificate());
    mEnterpriseConfig.setClientKeyEntry(null, null);
    assertNull(mEnterpriseConfig.getClientCertificate());
    assertNull(mEnterpriseConfig.getClientCertificateChain());
    // Setting the chain to null should clear the existing chain.
    X509Certificate[] clientChain = new X509Certificate[] { clientCert0, clientCert1 };
    mEnterpriseConfig.setClientKeyEntryWithCertificateChain(clientKey, clientChain);
    assertNotNull(mEnterpriseConfig.getClientCertificateChain());
    mEnterpriseConfig.setClientKeyEntryWithCertificateChain(null, null);
    assertNull(mEnterpriseConfig.getClientCertificate());
    assertNull(mEnterpriseConfig.getClientCertificateChain());
}
Also used : PrivateKey(java.security.PrivateKey) X509Certificate(java.security.cert.X509Certificate) SmallTest(android.test.suitebuilder.annotation.SmallTest) Test(org.junit.Test)

Example 87 with PrivateKey

use of java.security.PrivateKey in project spring-security-oauth by spring-projects.

the class CoreOAuthSignatureMethodFactory method getSignatureMethod.

public OAuthSignatureMethod getSignatureMethod(String methodName, SignatureSecret signatureSecret, String tokenSecret) throws UnsupportedSignatureMethodException {
    if (supportPlainText && PlainTextSignatureMethod.SIGNATURE_NAME.equals(methodName)) {
        if (!(signatureSecret instanceof SharedConsumerSecret)) {
            throw new IllegalArgumentException("Invalid secret for signature method " + methodName + ". Expected a " + SharedConsumerSecret.class.getName() + ", got " + (signatureSecret == null ? "null" : signatureSecret.getClass().getName()) + ".");
        }
        String consumerSecret = ((SharedConsumerSecret) signatureSecret).getConsumerSecret();
        if (consumerSecret == null) {
            consumerSecret = "";
        }
        if (tokenSecret == null) {
            tokenSecret = "";
        }
        consumerSecret = oauthEncode(consumerSecret);
        tokenSecret = oauthEncode(tokenSecret);
        Object salt = null;
        if (signatureSecret instanceof SaltedConsumerSecret) {
            salt = ((SaltedConsumerSecret) signatureSecret).getSalt();
        }
        return new PlainTextSignatureMethod(oauthEncode(new StringBuilder(consumerSecret).append('&').append(tokenSecret).toString()), this.plainTextPasswordEncoder, salt);
    } else if (supportHMAC_SHA1 && HMAC_SHA1SignatureMethod.SIGNATURE_NAME.equals(methodName)) {
        if (!(signatureSecret instanceof SharedConsumerSecret)) {
            throw new IllegalArgumentException("Invalid secret for signature method " + methodName + ". Expected a " + SharedConsumerSecret.class.getName() + ", got " + (signatureSecret == null ? "null" : signatureSecret.getClass().getName()) + ".");
        }
        String consumerSecret = ((SharedConsumerSecret) signatureSecret).getConsumerSecret();
        if (consumerSecret == null) {
            consumerSecret = "";
        }
        if (tokenSecret == null) {
            tokenSecret = "";
        }
        consumerSecret = oauthEncode(consumerSecret);
        tokenSecret = oauthEncode(tokenSecret);
        byte[] keyBytes;
        try {
            keyBytes = new StringBuilder(consumerSecret).append('&').append(tokenSecret).toString().getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e.getMessage());
        }
        SecretKeySpec spec = new SecretKeySpec(keyBytes, HMAC_SHA1SignatureMethod.MAC_NAME);
        return new HMAC_SHA1SignatureMethod(spec);
    } else if (supportRSA_SHA1 && RSA_SHA1SignatureMethod.SIGNATURE_NAME.equals(methodName)) {
        if (signatureSecret instanceof RSAKeySecret) {
            PublicKey publicKey = ((RSAKeySecret) signatureSecret).getPublicKey();
            PrivateKey privateKey = ((RSAKeySecret) signatureSecret).getPrivateKey();
            return new RSA_SHA1SignatureMethod(privateKey, publicKey);
        } else {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication.getCredentials() instanceof X509Certificate) {
                X509Certificate certificate = (X509Certificate) authentication.getCredentials();
                if (certificate != null) {
                    return new RSA_SHA1SignatureMethod(certificate.getPublicKey());
                }
            }
        }
    }
    throw new UnsupportedSignatureMethodException("Unsupported signature method: " + methodName);
}
Also used : PrivateKey(java.security.PrivateKey) PublicKey(java.security.PublicKey) UnsupportedEncodingException(java.io.UnsupportedEncodingException) X509Certificate(java.security.cert.X509Certificate) SecretKeySpec(javax.crypto.spec.SecretKeySpec) Authentication(org.springframework.security.core.Authentication)

Example 88 with PrivateKey

use of java.security.PrivateKey in project cas by apereo.

the class BaseSamlObjectSigner method getSignatureSigningConfiguration.

/**
     * Gets signature signing configuration.
     *
     * @return the signature signing configuration
     * @throws Exception the exception
     */
protected SignatureSigningConfiguration getSignatureSigningConfiguration() throws Exception {
    final BasicSignatureSigningConfiguration config = DefaultSecurityConfigurationBootstrap.buildDefaultSignatureSigningConfiguration();
    final SamlIdPProperties samlIdp = casProperties.getAuthn().getSamlIdp();
    if (this.overrideBlackListedSignatureAlgorithms != null && !samlIdp.getAlgs().getOverrideBlackListedSignatureSigningAlgorithms().isEmpty()) {
        config.setBlacklistedAlgorithms(this.overrideBlackListedSignatureAlgorithms);
    }
    if (this.overrideSignatureAlgorithms != null && !this.overrideSignatureAlgorithms.isEmpty()) {
        config.setSignatureAlgorithms(this.overrideSignatureAlgorithms);
    }
    if (this.overrideSignatureReferenceDigestMethods != null && !this.overrideSignatureReferenceDigestMethods.isEmpty()) {
        config.setSignatureReferenceDigestMethods(this.overrideSignatureReferenceDigestMethods);
    }
    if (this.overrideWhiteListedAlgorithms != null && !this.overrideWhiteListedAlgorithms.isEmpty()) {
        config.setWhitelistedAlgorithms(this.overrideWhiteListedAlgorithms);
    }
    if (StringUtils.isNotBlank(samlIdp.getAlgs().getOverrideSignatureCanonicalizationAlgorithm())) {
        config.setSignatureCanonicalizationAlgorithm(samlIdp.getAlgs().getOverrideSignatureCanonicalizationAlgorithm());
    }
    LOGGER.debug("Signature signing blacklisted algorithms: [{}]", config.getBlacklistedAlgorithms());
    LOGGER.debug("Signature signing signature algorithms: [{}]", config.getSignatureAlgorithms());
    LOGGER.debug("Signature signing signature canonicalization algorithm: [{}]", config.getSignatureCanonicalizationAlgorithm());
    LOGGER.debug("Signature signing whitelisted algorithms: [{}]", config.getWhitelistedAlgorithms());
    LOGGER.debug("Signature signing reference digest methods: [{}]", config.getSignatureReferenceDigestMethods());
    final PrivateKey privateKey = getSigningPrivateKey();
    final X509Certificate certificate = getSigningCertificate();
    final List<Credential> creds = new ArrayList<>();
    creds.add(new BasicX509Credential(certificate, privateKey));
    config.setSigningCredentials(creds);
    LOGGER.debug("Signature signing credentials configured");
    return config;
}
Also used : Credential(org.opensaml.security.credential.Credential) BasicX509Credential(org.opensaml.security.x509.BasicX509Credential) PrivateKey(java.security.PrivateKey) SamlIdPProperties(org.apereo.cas.configuration.model.support.saml.idp.SamlIdPProperties) BasicX509Credential(org.opensaml.security.x509.BasicX509Credential) ArrayList(java.util.ArrayList) BasicSignatureSigningConfiguration(org.opensaml.xmlsec.impl.BasicSignatureSigningConfiguration) X509Certificate(java.security.cert.X509Certificate)

Example 89 with PrivateKey

use of java.security.PrivateKey in project cas by apereo.

the class Cas30ResponseViewTests method decryptCredential.

private String decryptCredential(final String cred) {
    try {
        final PrivateKeyFactoryBean factory = new PrivateKeyFactoryBean();
        factory.setAlgorithm("RSA");
        factory.setLocation(new ClassPathResource("RSA1024Private.p8"));
        factory.setSingleton(false);
        final PrivateKey privateKey = factory.getObject();
        LOGGER.debug("Initializing cipher based on [{}]", privateKey.getAlgorithm());
        final Cipher cipher = Cipher.getInstance(privateKey.getAlgorithm());
        LOGGER.debug("Decoding value [{}]", cred);
        final byte[] cred64 = EncodingUtils.decodeBase64(cred);
        LOGGER.debug("Initializing decrypt-mode via private key [{}]", privateKey.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        final byte[] cipherData = cipher.doFinal(cred64);
        return new String(cipherData);
    } catch (final Exception e) {
        throw Throwables.propagate(e);
    }
}
Also used : PrivateKey(java.security.PrivateKey) PrivateKeyFactoryBean(org.apereo.cas.util.crypto.PrivateKeyFactoryBean) Cipher(javax.crypto.Cipher) ClassPathResource(org.springframework.core.io.ClassPathResource)

Example 90 with PrivateKey

use of java.security.PrivateKey in project bazel by bazelbuild.

the class ApkBuilder method getDebugKey.

/**
     * Returns the key and certificate from a given debug store.
     *
     * It is expected that the store password is 'android' and the key alias and password are
     * 'androiddebugkey' and 'android' respectively.
     *
     * @param storeOsPath the OS path to the debug store.
     * @param verboseStream an option {@link PrintStream} to display verbose information
     * @return they key and certificate in a {@link SigningInfo} object or null.
     * @throws ApkCreationException
     */
public static SigningInfo getDebugKey(String storeOsPath, final PrintStream verboseStream) throws ApkCreationException {
    try {
        if (storeOsPath != null) {
            File storeFile = new File(storeOsPath);
            try {
                checkInputFile(storeFile);
            } catch (FileNotFoundException e) {
            // ignore these since the debug store can be created on the fly anyway.
            }
            // get the debug key
            if (verboseStream != null) {
                verboseStream.println(String.format("Using keystore: %s", storeOsPath));
            }
            IKeyGenOutput keygenOutput = null;
            if (verboseStream != null) {
                keygenOutput = new IKeyGenOutput() {

                    @Override
                    public void out(String message) {
                        verboseStream.println(message);
                    }

                    @Override
                    public void err(String message) {
                        verboseStream.println(message);
                    }
                };
            }
            DebugKeyProvider keyProvider = new DebugKeyProvider(storeOsPath, null, /*store type*/
            keygenOutput);
            PrivateKey key = keyProvider.getDebugKey();
            X509Certificate certificate = (X509Certificate) keyProvider.getCertificate();
            if (key == null) {
                throw new ApkCreationException("Unable to get debug signature key");
            }
            // compare the certificate expiration date
            if (certificate != null && certificate.getNotAfter().compareTo(new Date()) < 0) {
                // TODO, regenerate a new one.
                throw new ApkCreationException("Debug Certificate expired on " + DateFormat.getInstance().format(certificate.getNotAfter()));
            }
            return new SigningInfo(key, certificate);
        } else {
            return null;
        }
    } catch (KeytoolException e) {
        if (e.getJavaHome() == null) {
            throw new ApkCreationException(e.getMessage() + "\nJAVA_HOME seems undefined, setting it will help locating keytool automatically\n" + "You can also manually execute the following command\n:" + e.getCommandLine(), e);
        } else {
            throw new ApkCreationException(e.getMessage() + "\nJAVA_HOME is set to: " + e.getJavaHome() + "\nUpdate it if necessary, or manually execute the following command:\n" + e.getCommandLine(), e);
        }
    } catch (ApkCreationException e) {
        throw e;
    } catch (Exception e) {
        throw new ApkCreationException(e);
    }
}
Also used : PrivateKey(java.security.PrivateKey) FileNotFoundException(java.io.FileNotFoundException) X509Certificate(java.security.cert.X509Certificate) Date(java.util.Date) KeytoolException(com.android.sdklib.internal.build.DebugKeyProvider.KeytoolException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) IKeyGenOutput(com.android.sdklib.internal.build.DebugKeyProvider.IKeyGenOutput) KeytoolException(com.android.sdklib.internal.build.DebugKeyProvider.KeytoolException) File(java.io.File) DebugKeyProvider(com.android.sdklib.internal.build.DebugKeyProvider)

Aggregations

PrivateKey (java.security.PrivateKey)517 X509Certificate (java.security.cert.X509Certificate)217 KeyFactory (java.security.KeyFactory)169 PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)144 Certificate (java.security.cert.Certificate)127 PublicKey (java.security.PublicKey)120 ByteArrayInputStream (java.io.ByteArrayInputStream)118 KeyStore (java.security.KeyStore)93 CertificateFactory (java.security.cert.CertificateFactory)92 IOException (java.io.IOException)81 Key (java.security.Key)74 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)73 PrivateKeyEntry (java.security.KeyStore.PrivateKeyEntry)70 Entry (java.security.KeyStore.Entry)60 TrustedCertificateEntry (java.security.KeyStore.TrustedCertificateEntry)60 KeyPair (java.security.KeyPair)59 SecretKey (javax.crypto.SecretKey)48 InvalidKeyException (java.security.InvalidKeyException)47 KeyStoreException (java.security.KeyStoreException)46 RSAPrivateKey (java.security.interfaces.RSAPrivateKey)46