Search in sources :

Example 91 with RSAPublicKey

use of java.security.interfaces.RSAPublicKey in project ddf by codice.

the class OidcTokenValidatorTest method setup.

@Before
public void setup() throws Exception {
    // Generate the RSA key pair
    KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
    gen.initialize(2048);
    KeyPair keyPair = gen.generateKeyPair();
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
    JWK sigJwk = new RSAKey.Builder(publicKey).privateKey(privateKey).keyUse(KeyUse.SIGNATURE).keyID(UUID.randomUUID().toString()).build();
    String jwk = "{\"keys\": [" + sigJwk.toPublicJWK().toJSONString() + "] }";
    when(oidcProviderMetadata.getIDTokenJWSAlgs()).thenReturn(ImmutableList.of(JWSAlgorithm.RS256));
    when(oidcProviderMetadata.getIssuer()).thenReturn(new Issuer("http://localhost:8080/auth/realms/master"));
    when(oidcProviderMetadata.getJWKSetURI()).thenReturn(new URI("http://localhost:8080/auth/realms/master/protocol/openid-connect/certs"));
    Resource resource = new Resource(jwk, APPLICATION_JSON);
    when(resourceRetriever.retrieveResource(any())).thenReturn(resource);
    when(configuration.getClientId()).thenReturn("ddf-client");
    when(configuration.getSecret()).thenReturn("secret");
    when(configuration.isUseNonce()).thenReturn(true);
    when(configuration.findProviderMetadata()).thenReturn(oidcProviderMetadata);
    when(configuration.findResourceRetriever()).thenReturn(resourceRetriever);
    validAlgorithm = Algorithm.RSA256(publicKey, privateKey);
    invalidAlgorithm = Algorithm.HMAC256("WRONG");
    when(oidcClient.getNonceSessionAttributeName()).thenReturn(NONCE_SESSION_ATTRIBUTE);
}
Also used : KeyPair(java.security.KeyPair) RSAPublicKey(java.security.interfaces.RSAPublicKey) Issuer(com.nimbusds.oauth2.sdk.id.Issuer) Resource(com.nimbusds.jose.util.Resource) KeyPairGenerator(java.security.KeyPairGenerator) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) URI(java.net.URI) JWK(com.nimbusds.jose.jwk.JWK) Before(org.junit.Before)

Example 92 with RSAPublicKey

use of java.security.interfaces.RSAPublicKey in project ddf by codice.

the class OAuthSecurityImplTest method setUp.

@Before
public void setUp() throws Exception {
    // Generate the RSA key pair to sign tokens
    KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
    gen.initialize(2048);
    KeyPair keyPair = gen.generateKeyPair();
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
    JWK sigJwk = new RSAKey.Builder(publicKey).privateKey(privateKey).keyUse(KeyUse.SIGNATURE).keyID(UUID.randomUUID().toString()).build();
    String jwk = "{\"keys\": [" + sigJwk.toPublicJWK().toJSONString() + "] }";
    validAlgorithm = Algorithm.RSA256(publicKey, privateKey);
    invalidAlgorithm = Algorithm.HMAC256("WRONG");
    ResourceRetriever resourceRetriever = mock(ResourceRetriever.class);
    Resource jwkResource = new Resource(jwk, APPLICATION_JSON);
    when(resourceRetriever.retrieveResource(eq(new URL(JWK_ENDPOINT)))).thenReturn(jwkResource);
    String content = IOUtils.toString(Objects.requireNonNull(getClass().getClassLoader().getResourceAsStream("metadata.json")), StandardCharsets.UTF_8);
    Resource metadataResource = new Resource(content, APPLICATION_JSON);
    when(resourceRetriever.retrieveResource(eq(new URL(METADATA_ENDPOINT)))).thenReturn(metadataResource);
    tokenStorage = mock(TokenStorage.class);
    oauthSecurity = new OAuthSecurityWithMockWebclient(tokenStorage);
    oauthSecurity.setResourceRetriever(resourceRetriever);
}
Also used : KeyPair(java.security.KeyPair) RSAPublicKey(java.security.interfaces.RSAPublicKey) ResourceRetriever(com.nimbusds.jose.util.ResourceRetriever) Resource(com.nimbusds.jose.util.Resource) KeyPairGenerator(java.security.KeyPairGenerator) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) TokenStorage(org.codice.ddf.security.token.storage.api.TokenStorage) URL(java.net.URL) JWK(com.nimbusds.jose.jwk.JWK) Before(org.junit.Before)

Example 93 with RSAPublicKey

use of java.security.interfaces.RSAPublicKey in project sonarqube by SonarSource.

the class GithubAppSecurityImpl method readApplicationPrivateKey.

private static Algorithm readApplicationPrivateKey(long appId, String encodedPrivateKey) {
    byte[] decodedPrivateKey = encodedPrivateKey.getBytes(UTF_8);
    try (PemReader pemReader = new PemReader(new InputStreamReader(new ByteArrayInputStream(decodedPrivateKey)))) {
        Security.addProvider(new BouncyCastleProvider());
        PemObject pemObject = pemReader.readPemObject();
        if (pemObject == null) {
            throw new IllegalArgumentException("Failed to decode Github Application private key");
        }
        PKCS8EncodedKeySpec keySpec1 = new PKCS8EncodedKeySpec(pemObject.getContent());
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec1);
        return Algorithm.RSA256(new RSAKeyProvider() {

            @Override
            public RSAPublicKey getPublicKeyById(String keyId) {
                throw new UnsupportedOperationException("getPublicKeyById not implemented");
            }

            @Override
            public RSAPrivateKey getPrivateKey() {
                return (RSAPrivateKey) privateKey;
            }

            @Override
            public String getPrivateKeyId() {
                return "github_app_" + appId;
            }
        });
    } catch (Exception e) {
        throw new IllegalArgumentException("Invalid Github Application private key", e);
    } finally {
        Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME);
    }
}
Also used : RSAKeyProvider(com.auth0.jwt.interfaces.RSAKeyProvider) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PrivateKey(java.security.PrivateKey) InputStreamReader(java.io.InputStreamReader) PemReader(org.bouncycastle.util.io.pem.PemReader) PemObject(org.bouncycastle.util.io.pem.PemObject) RSAPublicKey(java.security.interfaces.RSAPublicKey) ByteArrayInputStream(java.io.ByteArrayInputStream) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) KeyFactory(java.security.KeyFactory) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Example 94 with RSAPublicKey

use of java.security.interfaces.RSAPublicKey in project metron by apache.

the class KnoxSSOAuthenticationFilterTest method validateSignatureShouldProperlyValidateToken.

@Test
public void validateSignatureShouldProperlyValidateToken() throws Exception {
    KnoxSSOAuthenticationFilter knoxSSOAuthenticationFilter = spy(new KnoxSSOAuthenticationFilter("userSearchBase", mock(Path.class), "knoxKeyString", "knoxCookie", mock(LdapTemplate.class)));
    SignedJWT jwtToken = mock(SignedJWT.class);
    {
        // Should be invalid if algorithm is not ES256
        JWSHeader jwsHeader = new JWSHeader(JWSAlgorithm.ES384);
        when(jwtToken.getHeader()).thenReturn(jwsHeader);
        assertFalse(knoxSSOAuthenticationFilter.validateSignature(jwtToken));
    }
    {
        // Should be invalid if state is not SIGNED
        JWSHeader jwsHeader = new JWSHeader(JWSAlgorithm.RS256);
        when(jwtToken.getHeader()).thenReturn(jwsHeader);
        when(jwtToken.getState()).thenReturn(JWSObject.State.UNSIGNED);
        assertFalse(knoxSSOAuthenticationFilter.validateSignature(jwtToken));
    }
    {
        // Should be invalid if signature is null
        JWSHeader jwsHeader = new JWSHeader(JWSAlgorithm.RS256);
        when(jwtToken.getHeader()).thenReturn(jwsHeader);
        when(jwtToken.getState()).thenReturn(JWSObject.State.SIGNED);
        assertFalse(knoxSSOAuthenticationFilter.validateSignature(jwtToken));
    }
    {
        Base64URL signature = mock(Base64URL.class);
        when(jwtToken.getSignature()).thenReturn(signature);
        RSAPublicKey rsaPublicKey = mock(RSAPublicKey.class);
        RSASSAVerifier rsaSSAVerifier = mock(RSASSAVerifier.class);
        doReturn(rsaSSAVerifier).when(knoxSSOAuthenticationFilter).getRSASSAVerifier();
        {
            // Should be invalid if token verify throws an exception
            when(jwtToken.verify(rsaSSAVerifier)).thenThrow(new JOSEException("verify exception"));
            assertFalse(knoxSSOAuthenticationFilter.validateSignature(jwtToken));
        }
        {
            // Should be invalid if RSA verification fails
            doReturn(false).when(jwtToken).verify(rsaSSAVerifier);
            assertFalse(knoxSSOAuthenticationFilter.validateSignature(jwtToken));
        }
        {
            // Should be valid if RSA verification succeeds
            doReturn(true).when(jwtToken).verify(rsaSSAVerifier);
            assertTrue(knoxSSOAuthenticationFilter.validateSignature(jwtToken));
        }
    }
}
Also used : RSAPublicKey(java.security.interfaces.RSAPublicKey) RSASSAVerifier(com.nimbusds.jose.crypto.RSASSAVerifier) SignedJWT(com.nimbusds.jwt.SignedJWT) JOSEException(com.nimbusds.jose.JOSEException) JWSHeader(com.nimbusds.jose.JWSHeader) Base64URL(com.nimbusds.jose.util.Base64URL) Test(org.junit.jupiter.api.Test)

Example 95 with RSAPublicKey

use of java.security.interfaces.RSAPublicKey in project metron by apache.

the class SecurityUtils method parseRSAPublicKey.

public static RSAPublicKey parseRSAPublicKey(String pem) throws CertificateException, UnsupportedEncodingException {
    String PEM_HEADER = "-----BEGIN CERTIFICATE-----\n";
    String PEM_FOOTER = "\n-----END CERTIFICATE-----";
    String fullPem = (pem.startsWith(PEM_HEADER) && pem.endsWith(PEM_FOOTER)) ? pem : PEM_HEADER + pem + PEM_FOOTER;
    PublicKey key = null;
    try {
        CertificateFactory fact = CertificateFactory.getInstance("X.509");
        ByteArrayInputStream is = new ByteArrayInputStream(fullPem.getBytes(StandardCharsets.UTF_8));
        X509Certificate cer = (X509Certificate) fact.generateCertificate(is);
        key = cer.getPublicKey();
    } catch (CertificateException ce) {
        String message = null;
        if (pem.startsWith(PEM_HEADER)) {
            message = "CertificateException - be sure not to include PEM header " + "and footer in the PEM configuration element.";
        } else {
            message = "CertificateException - PEM may be corrupt";
        }
        throw new CertificateException(message, ce);
    }
    return (RSAPublicKey) key;
}
Also used : RSAPublicKey(java.security.interfaces.RSAPublicKey) ByteArrayInputStream(java.io.ByteArrayInputStream) RSAPublicKey(java.security.interfaces.RSAPublicKey) PublicKey(java.security.PublicKey) CertificateException(java.security.cert.CertificateException) CertificateFactory(java.security.cert.CertificateFactory) X509Certificate(java.security.cert.X509Certificate)

Aggregations

RSAPublicKey (java.security.interfaces.RSAPublicKey)240 RSAPrivateKey (java.security.interfaces.RSAPrivateKey)65 PublicKey (java.security.PublicKey)50 KeyPair (java.security.KeyPair)48 BigInteger (java.math.BigInteger)44 IOException (java.io.IOException)39 KeyPairGenerator (java.security.KeyPairGenerator)39 KeyFactory (java.security.KeyFactory)37 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)31 ECPublicKey (java.security.interfaces.ECPublicKey)30 X509Certificate (java.security.cert.X509Certificate)29 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)28 X509EncodedKeySpec (java.security.spec.X509EncodedKeySpec)27 Test (org.junit.Test)27 PrivateKey (java.security.PrivateKey)26 RSAPublicKeySpec (java.security.spec.RSAPublicKeySpec)26 CertificateException (java.security.cert.CertificateException)24 DSAPublicKey (java.security.interfaces.DSAPublicKey)24 InvalidKeyException (java.security.InvalidKeyException)22 ByteArrayInputStream (java.io.ByteArrayInputStream)21