Github user ahgittin commented on a diff in the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#discussion_r23522095
  
    --- 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);
    --- End diff --
    
    +1 adding the word `deprecated`.  But I really want this one brought to our 
attention so leaving it log warning.  We can exclude the logger or (better) 
patch.


---
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.
---

Reply via email to