Github user ahgittin commented on a diff in the pull request:
https://github.com/apache/incubator-brooklyn/pull/465#discussion_r23522109
--- Diff: core/src/main/java/brooklyn/util/crypto/SecureKeys.java ---
@@ -19,182 +19,149 @@
package brooklyn.util.crypto;
import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.security.KeyPair;
-import java.security.KeyPairGenerator;
-import java.security.KeyStore;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
+import java.security.PrivateKey;
+import java.security.PublicKey;
import java.security.Security;
-import java.security.cert.CertificateException;
-import java.security.cert.X509Certificate;
-import java.util.NoSuchElementException;
-
-import javax.net.ssl.TrustManager;
-import javax.net.ssl.TrustManagerFactory;
-import javax.net.ssl.X509TrustManager;
-import javax.security.auth.x500.X500Principal;
+import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.jce.X509Principal;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
+import org.bouncycastle.openssl.PEMDecryptorProvider;
+import org.bouncycastle.openssl.PEMEncryptedKeyPair;
+import org.bouncycastle.openssl.PEMKeyPair;
+import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.PEMReader;
import org.bouncycastle.openssl.PEMWriter;
import org.bouncycastle.openssl.PasswordFinder;
+import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
+import org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import brooklyn.util.exceptions.Exceptions;
+import brooklyn.util.stream.Streams;
+import com.google.common.base.Objects;
import com.google.common.base.Throwables;
/**
* Utility methods for generating and working with keys
*/
-public class SecureKeys {
+public class SecureKeys extends SecureKeysWithoutBouncyCastle {
+ private static final Logger log =
LoggerFactory.getLogger(SecureKeys.class);
+
static { Security.addProvider(new BouncyCastleProvider()); }
- private static KeyPairGenerator defaultKeyPairGenerator =
newKeyPairGenerator("RSA", 1024);
-
- private SecureKeys() {}
-
- public static KeyPairGenerator newKeyPairGenerator(String algorithm,
int bits) {
- KeyPairGenerator keyPairGenerator;
- try {
- keyPairGenerator = KeyPairGenerator.getInstance(algorithm);
- } catch (NoSuchAlgorithmException e) {
- throw Exceptions.propagate(e);
- }
- keyPairGenerator.initialize(bits);
- return keyPairGenerator;
+ public static class PassphraseProblem extends IllegalStateException {
+ private static final long serialVersionUID = -3382824813899223447L;
+ public PassphraseProblem() { super("Passphrase problem with this
key"); }
+ public PassphraseProblem(String message) { super("Passphrase
problem with this key: "+message); }
}
- public static KeyPair newKeyPair() {
- return defaultKeyPairGenerator.generateKeyPair();
+ private SecureKeys() {}
+
+ /** RFC1773 order, with None for other values. Normally prefer
X500Principal. */
+ public static X509Principal getX509PrincipalWithCommonName(String
commonName) {
+ return new X509Principal("" + "C=None," + "L=None," + "O=None," +
"OU=None," + "CN=" + commonName);
}
- public static KeyPair newKeyPair(String algorithm, int bits) {
- return newKeyPairGenerator(algorithm, bits).generateKeyPair();
- }
+ /** reads RSA or DSA / pem style private key files (viz {@link
#toPem(KeyPair)}), extracting also the public key if possible
+ * @throws IllegalStateException on errors, in particular {@link
PassphraseProblem} if that is the problem */
+ public static KeyPair readPem(InputStream input, final String
passphrase) {
+ // TODO cache is only for fallback "reader" strategy
+ byte[] cache = Streams.readFully(input);
+ input = new ByteArrayInputStream(cache);
- /** returns a new keystore, of the default type, and initialized to be
empty.
- * (everyone always forgets to load(null,null).) */
- public static KeyStore newKeyStore() {
try {
- KeyStore store =
KeyStore.getInstance(KeyStore.getDefaultType());
- store.load(null, null);
- return store;
- } catch (Exception e) {
- throw Exceptions.propagate(e);
- }
- }
+ PEMParser pemParser = new PEMParser(new
InputStreamReader(input));
+
+ Object object = pemParser.readObject();
+ pemParser.close();
+
+ JcaPEMKeyConverter converter = new
JcaPEMKeyConverter().setProvider("BC");
+ KeyPair kp = null;
+ if (object==null) {
+ throw new IllegalStateException("PEM parsing failed:
missing or invalid data");
+ } else if (object instanceof PEMEncryptedKeyPair) {
+ if (passphrase==null) throw new
PassphraseProblem("passphrase required");
+ try {
+ PEMDecryptorProvider decProv = new
JcePEMDecryptorProviderBuilder().build(passphrase.toCharArray());
+ kp = converter.getKeyPair(((PEMEncryptedKeyPair)
object).decryptKeyPair(decProv));
+ } catch (Exception e) {
+ Exceptions.propagateIfFatal(e);
+ throw new PassphraseProblem("wrong passphrase");
+ }
+ } else if (object instanceof PEMKeyPair) {
+ kp = converter.getKeyPair((PEMKeyPair) object);
+ } else if (object instanceof PrivateKeyInfo) {
+ PrivateKey privKey =
converter.getPrivateKey((PrivateKeyInfo) object);
+ kp = new KeyPair(null, privKey);
+ } else {
+ throw new IllegalStateException("PEM parser support
missing for: "+object);
+ }
+
+ return kp;
- /** returns keystore of default type read from given source */
- public static KeyStore newKeyStore(InputStream source, String
passphrase) {
- try {
- KeyStore store =
KeyStore.getInstance(KeyStore.getDefaultType());
- store.load(source, passphrase!=null ? passphrase.toCharArray()
: new char[0]);
- return store;
} catch (Exception e) {
- throw Exceptions.propagate(e);
- }
- }
+ Exceptions.propagateIfFatal(e);
+
+ // older code relied on PEMReader, now deprecated
+ // replaced with above based on
http://stackoverflow.com/questions/14919048/bouncy-castle-pemreader-pemparser
+ // passes the same tests (Jan 2015) but leaving the old code
as a fallback for the time being
+
+ input = new ByteArrayInputStream(cache);
+ try {
+ Security.addProvider(new BouncyCastleProvider());
+ PEMReader pr = new PEMReader(new InputStreamReader(input),
new PasswordFinder() {
+ public char[] getPassword() {
+ return passphrase!=null ? passphrase.toCharArray()
: new char[0];
+ }
+ });
+ KeyPair result = (KeyPair) pr.readObject();
+ pr.close();
+ if (result==null)
+ throw Exceptions.propagate(e);
+
+ log.warn("PEMParser failed when PEMReader succeeded, with
"+result+"; had: "+e);
- /** see {@link #getTrustManager(KeyStore, Class)}, matching any type */
- public static TrustManager getTrustManager(KeyStore trustStore) {
- return getTrustManager(trustStore, null);
- }
- /** returns the trust manager inferred from trustStore, matching the
type (if not null);
- * throws exception if there are none, or if there are multiple */
- @SuppressWarnings("unchecked")
- public static <T extends TrustManager> T getTrustManager(KeyStore
trustStore, Class<T> type) {
- try {
- TrustManagerFactory tmf = TrustManagerFactory.getInstance(
- TrustManagerFactory.getDefaultAlgorithm());
- tmf.init(trustStore);
- T result = null;
- for (TrustManager tm: tmf.getTrustManagers()) {
- if (type==null || type.isInstance(tm)) {
- if (result!=null)
- throw new IllegalStateException("Multiple trust
managers matching "+type+" inferred from "+trustStore);
- result = (T)tm;
- }
- }
- if (result!=null)
return result;
- throw new NoSuchElementException("No trust manager matching
"+type+" can be inferred from "+trustStore);
- } catch (Exception e) {
- throw Exceptions.propagate(e);
- }
- }
-
- public static X509TrustManager getTrustManager(X509Certificate
certificate) {
- try {
- KeyStore ks = newKeyStore();
- ks.setCertificateEntry("", certificate);
- return getTrustManager(ks, X509TrustManager.class);
- } catch (KeyStoreException e) {
- throw Exceptions.propagate(e);
+
+ } catch (Exception e2) {
+ Exceptions.propagateIfFatal(e2);
+ throw Exceptions.propagate(e);
+ }
}
}
- /** converts a certificate to the canonical implementation, commonly
sun.security.x509.X509CertImpl,
- * which is required in some places -- the Bouncy Castle X509 impl is
not accepted
- * (e.g. where certs are chained, passed to trust manager) */
- public static X509Certificate getCanonicalImpl(X509Certificate inCert)
{
- try {
- KeyStore store = SecureKeys.newKeyStore();
- store.setCertificateEntry("to-canonical", inCert);
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- store.store(out, "".toCharArray());
-
- KeyStore store2 =
KeyStore.getInstance(KeyStore.getDefaultType());
- store2.load(new ByteArrayInputStream(out.toByteArray()),
"".toCharArray());
- return (X509Certificate) store2.getCertificate("to-canonical");
- } catch (Exception e) {
- throw Exceptions.propagate(e);
- }
+ /** because KeyPair.equals is not implemented :( */
+ public static boolean equal(KeyPair k1, KeyPair k2) {
+ return Objects.equal(k2.getPrivate(), k1.getPrivate()) &&
Objects.equal(k2.getPrivate(), k1.getPrivate());
--- End diff --
yes - good spot
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at [email protected] or file a JIRA ticket
with INFRA.
---