Search in sources :

Example 11 with URIParcel

use of com.disney.uriparcel.URIParcel in project groovity by disney.

the class TestKeyUtils method loadPublicKeyStore.

private PublicKey loadPublicKeyStore(String fileName, String alias, String password) throws Exception {
    Map<String, Object> config = new HashMap<String, Object>();
    config.put(KeyStoreValueHandler.KEYSTORE_PASSWORD, password);
    config.put(KeyStoreValueHandler.KEYSTORE_TYPE, "JCEKS");
    URIParcel<KeyStore> parcel = new URIParcel<KeyStore>(KeyStore.class, new File(fileName).toURI(), config);
    KeyStore ks = parcel.call();
    PublicKey publicKey = (PublicKey) ks.getKey(alias, password.toCharArray());
    return publicKey;
}
Also used : HashMap(java.util.HashMap) URIParcel(com.disney.uriparcel.URIParcel) PublicKey(java.security.PublicKey) KeyStore(java.security.KeyStore) File(java.io.File)

Example 12 with URIParcel

use of com.disney.uriparcel.URIParcel in project groovity by disney.

the class TestSignatureAuth method testRSA.

@Test
public void testRSA() throws Exception {
    HttpGet request = new HttpGet("http://localhost:8080/");
    HttpClientContext localContext = new HttpClientContext();
    HttpSignatureSigner signer = new HttpSignatureSigner();
    signer.setHeaderName(SIGNATURE_HEADER);
    String keyId = "apiUser123";
    String headers = "(request-target) host x-date";
    KeyPair pair = KeyUtils.generateKeyPair();
    PrivateKey privateKey = pair.getPrivate();
    PublicKey publicKey = pair.getPublic();
    KeyObjectKeyLoader privateKeyLoader = new KeyObjectKeyLoader(privateKey);
    signer.setAlgorithm("rsa-sha256");
    signer.setKeyId(keyId);
    signer.setHeaders(Arrays.asList(headers.split(" ")));
    signer.setKeyLoader(privateKeyLoader);
    signer.process(request, localContext);
    SignatureAuthorization testAuth = new SignatureAuthorization();
    testAuth.setAlgorithm("rsa-sha256");
    testAuth.setHeaders(signer.getHeaders());
    String signingString = testAuth.generateSigningString(new ClientAuthorizationRequest(request));
    byte[] encryptedString = signer.doAuthorization(request).getSignature();
    boolean verify = verifyRsa("SHA256withRSA", publicKey, signingString, encryptedString);
    Assert.assertTrue(verify);
    // can choose algorithm
    signer.setAlgorithm("rsa-md5");
    signer.process(request, localContext);
    encryptedString = signer.doAuthorization(request).getSignature();
    verify = verifyRsa("MD5withRSA", publicKey, signingString, encryptedString);
    Assert.assertTrue(verify);
    // wrong keyid, not a key loader so no effect
    signer.setAlgorithm("rsa-sha256");
    signer.setKeyId("something else");
    signer.process(request, localContext);
    encryptedString = signer.doAuthorization(request).getSignature();
    verify = verifyRsa("SHA256withRSA", publicKey, signingString, encryptedString);
    Assert.assertTrue(verify);
    // different headers
    signer.setHeaders(Arrays.asList("host", "x-date"));
    signer.process(request, localContext);
    encryptedString = signer.doAuthorization(request).getSignature();
    verify = verifyRsa("SHA256withRSA", publicKey, signingString, encryptedString);
    Assert.assertFalse(verify);
    // load plain key from file;
    String location = "target/priv.pem";
    File pemFile = new File(location);
    URIParcel.put(pemFile.toURI(), pair);
    URIParcel<KeyPair> pemParcel = new URIParcel<KeyPair>(KeyPair.class, pemFile.toURI());
    signer = new HttpSignatureSigner();
    signer.setHeaderName(SIGNATURE_HEADER);
    signer.setKeyId("defaultValue");
    signer.setAlgorithm("rsa-sha256");
    signer.setHeaders(Arrays.asList(headers.split(" ")));
    signer.setKeyPairLoader(pemParcel);
    signingString = testAuth.generateSigningString(new ClientAuthorizationRequest(request));
    encryptedString = signer.doAuthorization(request).getSignature();
    verify = verifyRsa("SHA256withRSA", publicKey, signingString, encryptedString);
    Assert.assertTrue(verify);
    // try using a KeyStoreLoader
    signer = new HttpSignatureSigner();
    signer.setHeaderName(SIGNATURE_HEADER);
    signer.setAlgorithm("rsa-sha256");
    location = "target/testKeytool.store";
    Map<String, Object> config = new HashMap<String, Object>();
    config.put(KeyStoreValueHandler.KEYSTORE_PASSWORD, "rachel");
    config.put(KeyStoreValueHandler.KEYSTORE_TYPE, "JCEKS");
    URIParcel<KeyStore> parcel = new URIParcel<KeyStore>(KeyStore.class, new File(location).toURI(), config);
    KeyChain chain = new KeyStoreKeyChainImpl(parcel, "".toCharArray());
    KeyChainKeyLoader keystoreLoader = new KeyChainKeyLoader(chain);
    keystoreLoader.setAlias("test");
    signer.setKeyId("test");
    signer.setHeaders(Arrays.asList(headers.split(" ")));
    signer.setKeyLoader(keystoreLoader);
    signer.process(request, localContext);
    signingString = testAuth.generateSigningString(new ClientAuthorizationRequest(request));
    encryptedString = signer.doAuthorization(request).getSignature();
    // check again public key
    KeyStore importedKeystore = parcel.call();
    PublicKey loadedPublicKey = importedKeystore.getCertificate("test").getPublicKey();
    verifyRsa("SHA256withRSA", loadedPublicKey, signingString, encryptedString);
    Assert.assertTrue(verify);
}
Also used : URIParcel(com.disney.uriparcel.URIParcel) HashMap(java.util.HashMap) HttpGet(org.apache.http.client.methods.HttpGet) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) KeyChain(com.disney.http.auth.keychain.KeyChain) KeyStoreKeyChainImpl(com.disney.http.auth.keychain.KeyStoreKeyChainImpl) ClientAuthorizationRequest(com.disney.http.auth.client.ClientAuthorizationRequest) SignatureAuthorization(com.disney.http.auth.SignatureAuthorization) KeyChainKeyLoader(com.disney.http.auth.client.keyloader.KeyChainKeyLoader) HttpSignatureSigner(com.disney.http.auth.client.signer.HttpSignatureSigner) KeyObjectKeyLoader(com.disney.http.auth.client.keyloader.KeyObjectKeyLoader) File(java.io.File) Test(org.junit.Test)

Example 13 with URIParcel

use of com.disney.uriparcel.URIParcel in project groovity by disney.

the class XmlPolicyParser method processKeystore.

private static KeyChain processKeystore(Element keystore, ServletContext context) throws MalformedURLException, URISyntaxException {
    String location = null;
    long ttl = -1;
    String password = null;
    String type = "JCEKS";
    NodeList kids = keystore.getChildNodes();
    for (int i = 0; i < kids.getLength(); i++) {
        Node n = kids.item(i);
        if ("location".equals(n.getNodeName())) {
            location = n.getTextContent().trim();
        } else if ("ttl".equals(n.getNodeName())) {
            ttl = Long.parseLong(n.getTextContent().trim());
        } else if ("type".equals(n.getNodeName())) {
            type = n.getTextContent().trim();
        } else if ("password".equals(n.getNodeName())) {
            password = n.getTextContent().trim();
        }
    }
    URL ku = location.contains(":") ? new URL(location) : context.getResource(location);
    Map<String, Object> config = new HashMap<String, Object>();
    config.put(KeyStoreValueHandler.KEYSTORE_PASSWORD, password);
    config.put(KeyStoreValueHandler.KEYSTORE_TYPE, type);
    URIParcel<KeyStore> parcel = new URIParcel<KeyStore>(KeyStore.class, ku.toURI(), ttl, config);
    return new KeyStoreKeyChainImpl(parcel, password.toCharArray());
}
Also used : HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) URIParcel(com.disney.uriparcel.URIParcel) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) KeyStore(java.security.KeyStore) URL(java.net.URL) KeyStoreKeyChainImpl(com.disney.http.auth.keychain.KeyStoreKeyChainImpl)

Example 14 with URIParcel

use of com.disney.uriparcel.URIParcel in project groovity by disney.

the class SampleClient method main.

public static void main(String[] args) throws Exception {
    try {
        HttpClientBuilder clientBuilder = HttpClients.custom();
        // /// Ways to get the private key data (RSA):
        /*
         * Import KeyStore from file/url/etc.
         *   - assumes file has password but alias does not
         *   - must set loader password and type
         */
        Map<String, Object> config = new HashMap<String, Object>();
        config.put(KeyStoreValueHandler.KEYSTORE_PASSWORD, "filePassword");
        config.put(KeyStoreValueHandler.KEYSTORE_TYPE, "JCEKS");
        URIParcel<KeyStore> ks = new URIParcel<KeyStore>(KeyStore.class, new File("client_keystore.jceks").toURI(), config);
        KeyChain chain = new KeyStoreKeyChainImpl(ks, "passwordForPrivateKey".toCharArray());
        KeyChainKeyLoader loader = new KeyChainKeyLoader(chain);
        loader.setAlias("sample_webapp");
        /*
         * Import PrivateKey from PKCS8 pem file
         *   - assumes no password protection or encryption
         */
        // ExternalKeyLoader keyLoader = new ExternalKeyLoader("/client_key.pem", localContext);
        // keyLoader.setAlgorithm("RSA");
        URIParcel<PrivateKey> keyLoader = new URIParcel<PrivateKey>(PrivateKey.class, new java.net.URI("file:client_key.pem"));
        /*
         * Create own key and to set that in the signer. Can write key to file as desired
         *
         * Here, generate a KeyPair
         *   - only RSA
         *   - can set bit size to 1024 or 2048
         *   - must save the public key for verification use
         */
        KeyPair pair = KeyUtils.generateKeyPair(2048);
        // // Write privateKey to a file (PKCS8, uses base64encoding)
        // KeyUtils.writePrivateKeyToFile(pair,"/Users/kobar004/misc/auth-backup/newKey-priv.pem");
        KeyObjectKeyLoader privateKeyLoader = new KeyObjectKeyLoader(pair.getPrivate());
        // // write public KeyStore to file.
        // String publicKeyStoreLocation = "/Users/kobar004/misc/auth-backup/newKey-pub.store";
        // KeyUtils.writePublicKeyStoreToFile(pair.getPublic(), publicKeyStoreLocation, "RSA", "rachel");
        // Ways to set the symmetric key data (HMAC):
        /*
         * Set Key value explicitly
         */
        KeyObjectKeyLoader simpleLoader = new KeyObjectKeyLoader("hmac-sha256", "someBase64Secret");
        /*
         * Configuring the HttpSignatureSigner (HttpRequestInterceptor)
         *
         *   - must set the keyId / alias
         *   - must set key/encryption/algorithm
         *   - if no headers are set, default to just using the Date header
         *   - Lastly, the signer must be added to the clientBuilder
         */
        // /// Signing for SIGNATURE Authorization with imported RSA key
        // setting the key of the singer either with a loader or a key.
        HttpSignatureSigner signer = new HttpSignatureSigner();
        signer.setKeyId("apiUser123");
        signer.setHeaders(Arrays.asList("(request-target)", "host", "x-date"));
        // set key (choose one)
        // signer.setKey(loader);
        // signer.setKey(keyLoader);
        signer.setKeyLoader(simpleLoader);
        clientBuilder.addInterceptorLast(signer);
        // ///
        CloseableHttpClient client = clientBuilder.build();
        getRequest(client, "http://localhost:8080/");
        client.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HashMap(java.util.HashMap) URIParcel(com.disney.uriparcel.URIParcel) KeyChain(com.disney.http.auth.keychain.KeyChain) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) KeyStoreKeyChainImpl(com.disney.http.auth.keychain.KeyStoreKeyChainImpl) KeyChainKeyLoader(com.disney.http.auth.client.keyloader.KeyChainKeyLoader) HttpSignatureSigner(com.disney.http.auth.client.signer.HttpSignatureSigner) KeyObjectKeyLoader(com.disney.http.auth.client.keyloader.KeyObjectKeyLoader) File(java.io.File)

Example 15 with URIParcel

use of com.disney.uriparcel.URIParcel in project groovity by disney.

the class VerifierFactory method makeKeyStoreLoader.

@SuppressWarnings("rawtypes")
private KeyChain makeKeyStoreLoader(final Map conf) throws MalformedURLException, URISyntaxException {
    Callable<URI> uri;
    final Object loc = conf.get("location");
    if (loc instanceof Closure) {
        uri = new Callable<URI>() {

            public URI call() throws Exception {
                String location = ((Closure) loc).call().toString();
                if (location.startsWith("/")) {
                    // look for webapp resource
                    URL url = viewResolver.getServletContext().getResource(location);
                    if (url != null) {
                        return url.toURI();
                    }
                }
                return new URI(location);
            }
        };
    } else {
        final URI mUri = new URI(loc.toString());
        uri = new Callable<URI>() {

            public URI call() throws Exception {
                return mUri;
            }
        };
    }
    Callable<Long> refresh;
    final Object ttl = (Object) conf.get("ttl");
    if (ttl != null) {
        if (ttl instanceof Closure) {
            refresh = new Callable<Long>() {

                public Long call() throws Exception {
                    return ((Number) (((Closure) ttl).call())).longValue();
                }
            };
        } else {
            refresh = new Callable<Long>() {

                public Long call() throws Exception {
                    return ((Number) ttl).longValue();
                }
            };
        }
    } else {
        refresh = new Callable<Long>() {

            public Long call() throws Exception {
                return 120000l;
            }
        };
    }
    Callable<Map<String, Object>> confg = new Callable<Map<String, Object>>() {

        public Map<String, Object> call() throws Exception {
            String password = resolve(conf, "password", String.class);
            String tp = resolve(conf, "type", String.class);
            String type = tp != null ? (String) tp.toString() : "PKCS12";
            Map<String, Object> config = new HashMap<>();
            config.put(KeyStoreValueHandler.KEYSTORE_PASSWORD, password);
            if (type != null) {
                config.put(KeyStoreValueHandler.KEYSTORE_TYPE, type);
            }
            return config;
        }
    };
    Callable<char[]> passwd = new Callable<char[]>() {

        public char[] call() throws Exception {
            String password = resolve(conf, "password", String.class);
            return password.toCharArray();
        }
    };
    URIParcel<KeyStore> parcel = new URIParcel<KeyStore>(KeyStore.class, uri, refresh, confg);
    return new KeyStoreKeyChainImpl(parcel, passwd);
}
Also used : Closure(groovy.lang.Closure) HashMap(java.util.HashMap) URIParcel(com.disney.uriparcel.URIParcel) URI(java.net.URI) KeyStore(java.security.KeyStore) URISyntaxException(java.net.URISyntaxException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) MalformedURLException(java.net.MalformedURLException) CertificateException(java.security.cert.CertificateException) URL(java.net.URL) Callable(java.util.concurrent.Callable) KeyStoreKeyChainImpl(com.disney.http.auth.keychain.KeyStoreKeyChainImpl) Map(java.util.Map) HashMap(java.util.HashMap)

Aggregations

URIParcel (com.disney.uriparcel.URIParcel)24 URI (java.net.URI)18 Test (org.junit.Test)17 HashMap (java.util.HashMap)11 File (java.io.File)8 KeyStore (java.security.KeyStore)8 KeyStoreKeyChainImpl (com.disney.http.auth.keychain.KeyStoreKeyChainImpl)7 KeyChainKeyLoader (com.disney.http.auth.client.keyloader.KeyChainKeyLoader)5 KeyPair (java.security.KeyPair)5 Date (java.util.Date)5 KeyChain (com.disney.http.auth.keychain.KeyChain)4 Key (java.security.Key)4 KeyPairGenerator (java.security.KeyPairGenerator)4 KeyObjectKeyLoader (com.disney.http.auth.client.keyloader.KeyObjectKeyLoader)3 HttpSignatureSigner (com.disney.http.auth.client.signer.HttpSignatureSigner)3 URL (java.net.URL)3 PublicKey (java.security.PublicKey)3 Map (java.util.Map)3 SecretKeySpec (javax.crypto.spec.SecretKeySpec)3 MemoryPayload (com.disney.uriparcel.MemoryPayload)2