Search in sources :

Example 1 with KeyChain

use of com.disney.http.auth.keychain.KeyChain in project groovity by disney.

the class TestKeyStoreKeyLoader method setupKeyLoader.

private KeyChainKeyLoader setupKeyLoader(String keystorePassword) {
    Map<String, Object> config = new HashMap<String, Object>();
    config.put(KeyStoreValueHandler.KEYSTORE_PASSWORD, keystorePassword);
    config.put(KeyStoreValueHandler.KEYSTORE_TYPE, "JCEKS");
    URIParcel<KeyStore> parcel = new URIParcel<KeyStore>(KeyStore.class, new File("src/test/resources/testKey.store").toURI(), config);
    KeyChain chain = new KeyStoreKeyChainImpl(parcel, "".toCharArray());
    KeyChainKeyLoader loader = new KeyChainKeyLoader(chain);
    return loader;
}
Also used : KeyStoreKeyChainImpl(com.disney.http.auth.keychain.KeyStoreKeyChainImpl) HashMap(java.util.HashMap) URIParcel(com.disney.uriparcel.URIParcel) KeyChainKeyLoader(com.disney.http.auth.client.keyloader.KeyChainKeyLoader) KeyChain(com.disney.http.auth.keychain.KeyChain) KeyStore(java.security.KeyStore) File(java.io.File)

Example 2 with KeyChain

use of com.disney.http.auth.keychain.KeyChain 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 3 with KeyChain

use of com.disney.http.auth.keychain.KeyChain 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 4 with KeyChain

use of com.disney.http.auth.keychain.KeyChain in project groovity by disney.

the class VerifierFactory method processSignature.

@SuppressWarnings({ "unchecked", "rawtypes" })
private SignatureVerifierImpl processSignature(Map signature, Class<Script> scriptClass) throws InstantiationException, IllegalAccessException, ClassNotFoundException, MalformedURLException, URISyntaxException, NoSuchAlgorithmException, InvalidKeySpecException, CertificateException {
    SignatureVerifierImpl verifier = new SignatureVerifierImpl();
    processCommon(verifier, signature, scriptClass);
    List<KeyChain> keyChains = new ArrayList<KeyChain>();
    List headers = (List) signature.get("headers");
    if (headers != null) {
        verifier.setRequiredHeaders(headers);
    }
    Number drift = (Number) signature.get("drift");
    if (drift != null) {
        verifier.setMaxDateDrift(drift.longValue());
    }
    Map<Object, Map> keys = (Map) signature.get("keys");
    if (keys != null) {
        // we need to convert to proper Key objects
        Map<String, Key> realKeys = new HashMap<String, Key>();
        for (Entry<Object, Map> entry : keys.entrySet()) {
            String algorithm = (String) entry.getValue().get("algorithm");
            Object secret = entry.getValue().get("key");
            String signingAlg = Algorithms.getSecurityAlgorithm(algorithm);
            Key key;
            if (signingAlg.startsWith("Hmac")) {
                // expect base 64 encoding
                key = new SecretKeySpec(DatatypeConverter.parseBase64Binary(secret.toString()), signingAlg);
            } else {
                // expect x509 encoding
                CertificateFactory certificateFactory = CertificateFactory.getInstance("X509");
                Certificate certificate = certificateFactory.generateCertificate(new ByteArrayInputStream(DatatypeConverter.parseBase64Binary(secret.toString())));
                key = certificate.getPublicKey();
            /*X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(DatatypeConverter.parseBase64Binary(secret.toString()));
					KeyFactory factory = KeyFactory.getInstance("rsa");
					key = factory.generatePublic(pubKeySpec);
					*/
            }
            realKeys.put(entry.getKey().toString(), key);
        }
        keyChains.add(new MapKeyChainImpl(realKeys));
    }
    Map keystore = (Map) signature.get("keystore");
    if (keystore != null) {
        keyChains.add(makeKeyStoreLoader(keystore));
    }
    List<Map> keystores = (List<Map>) signature.get("keystores");
    if (keystores != null) {
        for (Map k : keystores) {
            keyChains.add(makeKeyStoreLoader(k));
        }
    }
    Object keychain = signature.get("keychain");
    addKeychain(keychain, keyChains, scriptClass);
    List kcs = (List) signature.get("keychains");
    if (kcs != null) {
        for (Object kc : kcs) {
            addKeychain(kc, keyChains, scriptClass);
        }
    }
    verifier.setKeyChains(keyChains);
    return verifier;
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) KeyChain(com.disney.http.auth.keychain.KeyChain) MapKeyChainImpl(com.disney.http.auth.keychain.MapKeyChainImpl) CertificateFactory(java.security.cert.CertificateFactory) SignatureVerifierImpl(com.disney.http.auth.server.signature.SignatureVerifierImpl) ByteArrayInputStream(java.io.ByteArrayInputStream) SecretKeySpec(javax.crypto.spec.SecretKeySpec) List(java.util.List) ArrayList(java.util.ArrayList) Map(java.util.Map) HashMap(java.util.HashMap) Key(java.security.Key) PrivateKey(java.security.PrivateKey) SecretKey(javax.crypto.SecretKey) PublicKey(java.security.PublicKey) Certificate(java.security.cert.Certificate)

Example 5 with KeyChain

use of com.disney.http.auth.keychain.KeyChain in project groovity by disney.

the class TestKeyUtils method TestKeyGeneration.

@Test
public void TestKeyGeneration() throws Exception {
    KeyPair pair = KeyUtils.generateKeyPair(2048);
    Assert.assertNotNull(pair);
    PrivateKey privateKey = pair.getPrivate();
    Assert.assertNotNull(privateKey);
    Assert.assertEquals(privateKey.getAlgorithm(), "RSA");
    PublicKey publicKey = pair.getPublic();
    Assert.assertNotNull(publicKey);
    Assert.assertEquals(publicKey.getAlgorithm(), "RSA");
    String alias = "apiUser123";
    // Store private key
    File privateKeyFile = new File("target/testPrivateKey.pem");
    File privateKeyStore = new File("target/testKey.store");
    String privatePassword = "passwordForPrivateKey";
    URIParcel.put(privateKeyFile.toURI(), pair);
    writePrivateKeystoreToFile(pair, privateKeyStore.getAbsolutePath(), alias, privatePassword);
    // test retrieval of KeyStore
    Map<String, Object> config = new HashMap<String, Object>();
    config.put(KeyStoreValueHandler.KEYSTORE_PASSWORD, privatePassword);
    config.put(KeyStoreValueHandler.KEYSTORE_TYPE, "JCEKS");
    URIParcel<KeyStore> parcel = new URIParcel<KeyStore>(KeyStore.class, privateKeyStore.toURI(), config);
    KeyChain chain = new KeyStoreKeyChainImpl(parcel, "".toCharArray());
    KeyChainKeyLoader privateKeyStoreLoader = new KeyChainKeyLoader(chain);
    privateKeyStoreLoader.setAlias(alias);
    PrivateKey loadedKeyFromKeyStore = (PrivateKey) privateKeyStoreLoader.call();
    Assert.assertEquals(privateKey, loadedKeyFromKeyStore);
    // test retrieval of Key
    URIParcel<KeyPair> pkParcel = new URIParcel<KeyPair>(KeyPair.class, privateKeyFile.toURI());
    KeyPair loadedPrivateKey = pkParcel.call();
    Assert.assertArrayEquals(privateKey.getEncoded(), loadedPrivateKey.getPrivate().getEncoded());
    // check storage and retrieval of public key
    String publicKeyFileName = "testPublicKey.store";
    String password = "publicPassword";
    File publicKeyFile = new File("target/" + publicKeyFileName);
    KeyUtils.writePublicKeyStoreToFile(publicKey, publicKeyFile.getAbsolutePath(), alias, password);
    PublicKey loadedPublicKey = loadPublicKeyStore(publicKeyFile.getAbsolutePath(), alias, password);
    Assert.assertArrayEquals(publicKey.getEncoded(), loadedPublicKey.getEncoded());
    // check if valid key pair by trying to sign and verify a string
    String testString = "This is the message to encode.";
    Signature rsaSign = Signature.getInstance("MD5withRSA");
    rsaSign.initSign(privateKey);
    rsaSign.update(testString.getBytes("UTF-8"));
    byte[] signedMessage = rsaSign.sign();
    Signature rsaVerify = Signature.getInstance("MD5withRSA");
    rsaVerify.initVerify(loadedPublicKey);
    rsaVerify.update(testString.getBytes("UTF-8"));
    boolean valid = rsaVerify.verify(signedMessage);
    Assert.assertTrue(valid);
    // make new key pair and save KeyStore to file.
    KeyPair keyPairForFile = KeyUtils.generateKeyPair();
    String location = new File("target/testKeytool.store").getAbsolutePath();
    writePrivateKeystoreToFile(keyPairForFile, location, "test", "rachel");
    // load from file
    config = new HashMap<String, Object>();
    config.put(KeyStoreValueHandler.KEYSTORE_PASSWORD, "rachel");
    config.put(KeyStoreValueHandler.KEYSTORE_TYPE, "JCEKS");
    URIParcel<KeyStore> ksParcel = new URIParcel<KeyStore>(KeyStore.class, new File(location).toURI(), config);
    KeyChain chain2 = new KeyStoreKeyChainImpl(ksParcel, "".toCharArray());
    KeyChainKeyLoader savedKeyStoreLoader = new KeyChainKeyLoader(chain2);
    savedKeyStoreLoader.setAlias("test");
    Key newKey = savedKeyStoreLoader.call();
    Assert.assertEquals(keyPairForFile.getPrivate(), newKey);
    KeyStore importedKeystore = ksParcel.call();
    Assert.assertEquals(keyPairForFile.getPublic(), importedKeystore.getCertificate("test").getPublicKey());
}
Also used : KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) HashMap(java.util.HashMap) URIParcel(com.disney.uriparcel.URIParcel) PublicKey(java.security.PublicKey) KeyChain(com.disney.http.auth.keychain.KeyChain) KeyStore(java.security.KeyStore) KeyStoreKeyChainImpl(com.disney.http.auth.keychain.KeyStoreKeyChainImpl) KeyChainKeyLoader(com.disney.http.auth.client.keyloader.KeyChainKeyLoader) Signature(java.security.Signature) File(java.io.File) PublicKey(java.security.PublicKey) Key(java.security.Key) PrivateKey(java.security.PrivateKey) Test(org.junit.Test)

Aggregations

KeyChain (com.disney.http.auth.keychain.KeyChain)8 KeyStoreKeyChainImpl (com.disney.http.auth.keychain.KeyStoreKeyChainImpl)5 HashMap (java.util.HashMap)5 KeyChainKeyLoader (com.disney.http.auth.client.keyloader.KeyChainKeyLoader)4 URIParcel (com.disney.uriparcel.URIParcel)4 File (java.io.File)4 Key (java.security.Key)4 SignatureAuthorization (com.disney.http.auth.SignatureAuthorization)3 SignatureVerifierImpl (com.disney.http.auth.server.signature.SignatureVerifierImpl)3 KeyStore (java.security.KeyStore)3 PrivateKey (java.security.PrivateKey)3 PublicKey (java.security.PublicKey)3 Test (org.junit.Test)3 KeyObjectKeyLoader (com.disney.http.auth.client.keyloader.KeyObjectKeyLoader)2 HttpSignatureSigner (com.disney.http.auth.client.signer.HttpSignatureSigner)2 MapKeyChainImpl (com.disney.http.auth.keychain.MapKeyChainImpl)2 VerifierResult (com.disney.http.auth.server.VerifierResult)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 InvalidKeyException (java.security.InvalidKeyException)2 KeyPair (java.security.KeyPair)2