Search in sources :

Example 16 with KeyFactory

use of java.security.KeyFactory in project druid by alibaba.

the class ConfigTools method getPublicKey.

public static PublicKey getPublicKey(String publicKeyText) {
    if (publicKeyText == null || publicKeyText.length() == 0) {
        publicKeyText = ConfigTools.DEFAULT_PUBLIC_KEY_STRING;
    }
    try {
        byte[] publicKeyBytes = Base64.base64ToByteArray(publicKeyText);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(publicKeyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA", "SunRsaSign");
        return keyFactory.generatePublic(x509KeySpec);
    } catch (Exception e) {
        throw new IllegalArgumentException("Failed to get public key", e);
    }
}
Also used : X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) KeyFactory(java.security.KeyFactory) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) NoSuchProviderException(java.security.NoSuchProviderException)

Example 17 with KeyFactory

use of java.security.KeyFactory in project druid by alibaba.

the class ConfigTools method getPublicKeyByPublicKeyFile.

public static PublicKey getPublicKeyByPublicKeyFile(String publicKeyFile) {
    if (publicKeyFile == null || publicKeyFile.length() == 0) {
        return ConfigTools.getPublicKey(null);
    }
    FileInputStream in = null;
    try {
        in = new FileInputStream(publicKeyFile);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int len = 0;
        byte[] b = new byte[512 / 8];
        while ((len = in.read(b)) != -1) {
            out.write(b, 0, len);
        }
        byte[] publicKeyBytes = out.toByteArray();
        X509EncodedKeySpec spec = new X509EncodedKeySpec(publicKeyBytes);
        KeyFactory factory = KeyFactory.getInstance("RSA", "SunRsaSign");
        return factory.generatePublic(spec);
    } catch (Exception e) {
        throw new IllegalArgumentException("Failed to get public key", e);
    } finally {
        JdbcUtils.close(in);
    }
}
Also used : X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) ByteArrayOutputStream(java.io.ByteArrayOutputStream) FileInputStream(java.io.FileInputStream) KeyFactory(java.security.KeyFactory) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) NoSuchProviderException(java.security.NoSuchProviderException)

Example 18 with KeyFactory

use of java.security.KeyFactory in project jersey by jersey.

the class RsaSha1Method method sign.

/**
     * Generates the RSA-SHA1 signature of OAuth request elements.
     *
     * @param baseString the combined OAuth elements to sign.
     * @param secrets the secrets object containing the private key for generating the signature.
     * @return the OAuth signature, in base64-encoded form.
     * @throws InvalidSecretException if the supplied secret is not valid.
     */
@Override
public String sign(final String baseString, final OAuth1Secrets secrets) throws InvalidSecretException {
    final Signature signature;
    try {
        signature = Signature.getInstance(SIGNATURE_ALGORITHM);
    } catch (final NoSuchAlgorithmException nsae) {
        throw new IllegalStateException(nsae);
    }
    byte[] decodedPrivateKey;
    try {
        decodedPrivateKey = Base64.decode(secrets.getConsumerSecret());
    } catch (final IOException ioe) {
        throw new InvalidSecretException(LocalizationMessages.ERROR_INVALID_CONSUMER_SECRET(ioe));
    }
    final KeyFactory keyFactory;
    try {
        keyFactory = KeyFactory.getInstance(KEY_TYPE);
    } catch (final NoSuchAlgorithmException nsae) {
        throw new IllegalStateException(nsae);
    }
    final EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedPrivateKey);
    final RSAPrivateKey rsaPrivateKey;
    try {
        rsaPrivateKey = (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
    } catch (final InvalidKeySpecException ikse) {
        throw new IllegalStateException(ikse);
    }
    try {
        signature.initSign(rsaPrivateKey);
    } catch (final InvalidKeyException ike) {
        throw new IllegalStateException(ike);
    }
    try {
        signature.update(baseString.getBytes());
    } catch (final SignatureException se) {
        throw new IllegalStateException(se);
    }
    final byte[] rsasha1;
    try {
        rsasha1 = signature.sign();
    } catch (final SignatureException se) {
        throw new IllegalStateException(se);
    }
    return Base64.encode(rsasha1);
}
Also used : NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) SignatureException(java.security.SignatureException) InvalidKeyException(java.security.InvalidKeyException) Signature(java.security.Signature) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) KeyFactory(java.security.KeyFactory) EncodedKeySpec(java.security.spec.EncodedKeySpec) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec)

Example 19 with KeyFactory

use of java.security.KeyFactory in project PushSms by koush.

the class MiddlewareService method getOrCreateKeyPair.

// create/read the keypair as necessary
private void getOrCreateKeyPair() {
    String encodedKeyPair = settings.getString("keypair", null);
    if (encodedKeyPair != null) {
        try {
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            ByteArrayInputStream bin = new ByteArrayInputStream(Base64.decode(encodedKeyPair, Base64.DEFAULT));
            ObjectInputStream in = new ObjectInputStream(bin);
            rsaPublicKeySpec = new RSAPublicKeySpec((BigInteger) in.readObject(), (BigInteger) (in.readObject()));
            RSAPrivateKeySpec rsaPrivateKeySpec = new RSAPrivateKeySpec((BigInteger) in.readObject(), (BigInteger) (in.readObject()));
            PublicKey pub = keyFactory.generatePublic(rsaPublicKeySpec);
            PrivateKey priv = keyFactory.generatePrivate(rsaPrivateKeySpec);
            keyPair = new KeyPair(pub, priv);
            return;
        } catch (Exception e) {
            Log.e(LOGTAG, "KeyPair load error", e);
        }
    }
    try {
        KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
        gen.initialize(2048);
        keyPair = gen.generateKeyPair();
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        rsaPublicKeySpec = keyFactory.getKeySpec(keyPair.getPublic(), RSAPublicKeySpec.class);
        RSAPrivateKeySpec privateKeySpec = keyFactory.getKeySpec(keyPair.getPrivate(), RSAPrivateKeySpec.class);
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(bout);
        out.writeObject(rsaPublicKeySpec.getModulus());
        out.writeObject(rsaPublicKeySpec.getPublicExponent());
        out.writeObject(privateKeySpec.getModulus());
        out.writeObject(privateKeySpec.getPrivateExponent());
        out.flush();
        settings.edit().putString("keypair", Base64.encodeToString(bout.toByteArray(), Base64.DEFAULT)).commit();
        settings.edit().putBoolean("needs_register", true).commit();
    } catch (Exception e) {
        Log.wtf(LOGTAG, "KeyPair generation error", e);
        keyPair = null;
    }
}
Also used : KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) PublicKey(java.security.PublicKey) RSAPublicKeySpec(java.security.spec.RSAPublicKeySpec) KeyPairGenerator(java.security.KeyPairGenerator) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ObjectOutputStream(java.io.ObjectOutputStream) RemoteException(android.os.RemoteException) IOException(java.io.IOException) RSAPrivateKeySpec(java.security.spec.RSAPrivateKeySpec) ByteArrayInputStream(java.io.ByteArrayInputStream) BigInteger(java.math.BigInteger) KeyFactory(java.security.KeyFactory) ObjectInputStream(java.io.ObjectInputStream)

Example 20 with KeyFactory

use of java.security.KeyFactory in project PushSms by koush.

the class MiddlewareService method createRegistration.

// fetch/create the gcm and public key info for a phone number
// from the server
private RegistrationFuture createRegistration(final String address, final Registration existing) {
    final RegistrationFuture ret = new RegistrationFuture();
    numberToRegistration.put(address, ret);
    // the server will need to know all the email/number combos when we're attempting
    // to locate the gcm registration id for a given number.
    // this will return HASHED emails, not actual emails. this way the server is not privy
    // to your contact information.
    HashSet<String> emailHash = Helper.getEmailHashesForNumber(this, address);
    if (emailHash.size() == 0) {
        ret.setComplete(new Exception("no emails"));
        return ret;
    }
    JsonObject post = new JsonObject();
    JsonArray authorities = new JsonArray();
    post.add("authorities", authorities);
    post.addProperty("endpoint", address);
    for (String authority : emailHash) {
        authorities.add(new JsonPrimitive(authority));
    }
    logd("Fetching registration for " + address);
    Ion.with(this).load(FIND_URL).setJsonObjectBody(post).asJsonObject().setCallback(new FutureCallback<JsonObject>() {

        @Override
        public void onCompleted(Exception e, JsonObject result) {
            Registration registration;
            boolean wasUnregistered = false;
            String oldRegistrationId = null;
            // from the old registration
            if (existing != null) {
                oldRegistrationId = existing.registrationId;
                wasUnregistered = existing.isUnregistered();
                // reuse the existing registration to preserve sequence numbers, etc.
                registration = existing;
                registration.register();
            } else {
                registration = new Registration();
            }
            try {
                if (e != null) {
                    // or lack of network access on the phone, etc.
                    throw e;
                }
                if (result.has("error"))
                    throw new Exception(result.toString());
                String newRegistrationId = result.get("registration_id").getAsString();
                // the number is available for an encrypted connection, grab
                // the registration info.
                registration.endpoint = address;
                registration.registrationId = newRegistrationId;
                BigInteger publicExponent = new BigInteger(Base64.decode(result.get("public_exponent").getAsString(), Base64.DEFAULT));
                BigInteger publicModulus = new BigInteger(Base64.decode(result.get("public_modulus").getAsString(), Base64.DEFAULT));
                RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(publicModulus, publicExponent);
                KeyFactory keyFactory = KeyFactory.getInstance("RSA");
                registration.remotePublicKey = keyFactory.generatePublic(publicKeySpec);
                logd("Registration complete for " + registration.endpoint);
                // gets hit.
                if (wasUnregistered && TextUtils.equals(newRegistrationId, oldRegistrationId))
                    throw new Exception("unregistered registration was refreshed, still invalid");
            } catch (Exception ex) {
                // mark this number as invalid
                Log.e(LOGTAG, "registration fetch failure", ex);
                registration.invalidate();
            }
            registry.register(address, registration);
            ret.setComplete(registration);
            // that will leverage the new registration id and potentially public key
            if (gcmConnectionManager != null)
                gcmConnectionManager.remove(address);
        }
    });
    return ret;
}
Also used : JsonPrimitive(com.google.gson.JsonPrimitive) JsonObject(com.google.gson.JsonObject) RSAPublicKeySpec(java.security.spec.RSAPublicKeySpec) RemoteException(android.os.RemoteException) IOException(java.io.IOException) JsonArray(com.google.gson.JsonArray) BigInteger(java.math.BigInteger) KeyFactory(java.security.KeyFactory)

Aggregations

KeyFactory (java.security.KeyFactory)407 PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)180 PrivateKey (java.security.PrivateKey)177 PublicKey (java.security.PublicKey)120 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)114 X509EncodedKeySpec (java.security.spec.X509EncodedKeySpec)113 CertificateFactory (java.security.cert.CertificateFactory)103 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)99 ByteArrayInputStream (java.io.ByteArrayInputStream)93 Certificate (java.security.cert.Certificate)89 X509Certificate (java.security.cert.X509Certificate)87 RSAPublicKeySpec (java.security.spec.RSAPublicKeySpec)60 PrivateKeyEntry (java.security.KeyStore.PrivateKeyEntry)59 Entry (java.security.KeyStore.Entry)53 TrustedCertificateEntry (java.security.KeyStore.TrustedCertificateEntry)53 IOException (java.io.IOException)47 BigInteger (java.math.BigInteger)45 RSAPrivateKey (java.security.interfaces.RSAPrivateKey)43 RSAPublicKey (java.security.interfaces.RSAPublicKey)43 Signature (java.security.Signature)40