Search in sources :

Example 46 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)

Example 47 with KeyFactory

use of java.security.KeyFactory in project remusic by aa112901.

the class RSAUtils method getPublicKey.

/**
     * 使用模和指数生成RSA公钥
     * 注意:【此代码用了默认补位方式,为RSA/None/PKCS1Padding,不同JDK默认的补位方式可能不同,如Android默认是RSA
     * /None/NoPadding】
     *
     * @param modulus  模
     * @param exponent 指数
     * @return
     */
public static RSAPublicKey getPublicKey(String modulus, String exponent) {
    try {
        BigInteger b1 = new BigInteger(modulus);
        BigInteger b2 = new BigInteger(exponent);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        RSAPublicKeySpec keySpec = new RSAPublicKeySpec(b1, b2);
        return (RSAPublicKey) keyFactory.generatePublic(keySpec);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
Also used : RSAPublicKey(java.security.interfaces.RSAPublicKey) BigInteger(java.math.BigInteger) RSAPublicKeySpec(java.security.spec.RSAPublicKeySpec) KeyFactory(java.security.KeyFactory) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 48 with KeyFactory

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

the class VerifyUtil method generatePrivateKey.

/**
     * read private key
     *
     * @param filename
     * @return
     */
public static PrivateKey generatePrivateKey(final String filename) {
    try {
        File f = new File(filename);
        FileInputStream fis = new FileInputStream(f);
        DataInputStream dis = new DataInputStream(fis);
        byte[] keyBytes = new byte[(int) f.length()];
        dis.readFully(keyBytes);
        dis.close();
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory kf = KeyFactory.getInstance(ALGORITHM_RSA);
        return kf.generatePrivate(spec);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
Also used : PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) DataInputStream(java.io.DataInputStream) File(java.io.File) FileInputStream(java.io.FileInputStream) KeyFactory(java.security.KeyFactory) SignatureException(java.security.SignatureException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException)

Example 49 with KeyFactory

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

the class VerifyUtil method generatePublicKey.

/**
     * read public key
     *
     * @param filename
     * @return
     */
private static PublicKey generatePublicKey(final String filename) {
    try {
        File f = new File(filename);
        FileInputStream fis = new FileInputStream(f);
        DataInputStream dis = new DataInputStream(fis);
        byte[] keyBytes = new byte[(int) f.length()];
        dis.readFully(keyBytes);
        dis.close();
        X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
        KeyFactory kf = KeyFactory.getInstance(ALGORITHM_RSA);
        return kf.generatePublic(spec);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
Also used : X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) DataInputStream(java.io.DataInputStream) File(java.io.File) FileInputStream(java.io.FileInputStream) KeyFactory(java.security.KeyFactory) SignatureException(java.security.SignatureException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException)

Example 50 with KeyFactory

use of java.security.KeyFactory in project android_frameworks_base by ParanoidAndroid.

the class PackageParser method parseVerifier.

private static VerifierInfo parseVerifier(Resources res, XmlPullParser parser, AttributeSet attrs, int flags, String[] outError) throws XmlPullParserException, IOException {
    final TypedArray sa = res.obtainAttributes(attrs, com.android.internal.R.styleable.AndroidManifestPackageVerifier);
    final String packageName = sa.getNonResourceString(com.android.internal.R.styleable.AndroidManifestPackageVerifier_name);
    final String encodedPublicKey = sa.getNonResourceString(com.android.internal.R.styleable.AndroidManifestPackageVerifier_publicKey);
    sa.recycle();
    if (packageName == null || packageName.length() == 0) {
        Slog.i(TAG, "verifier package name was null; skipping");
        return null;
    } else if (encodedPublicKey == null) {
        Slog.i(TAG, "verifier " + packageName + " public key was null; skipping");
    }
    EncodedKeySpec keySpec;
    try {
        final byte[] encoded = Base64.decode(encodedPublicKey, Base64.DEFAULT);
        keySpec = new X509EncodedKeySpec(encoded);
    } catch (IllegalArgumentException e) {
        Slog.i(TAG, "Could not parse verifier " + packageName + " public key; invalid Base64");
        return null;
    }
    /* First try the key as an RSA key. */
    try {
        final KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        final PublicKey publicKey = keyFactory.generatePublic(keySpec);
        return new VerifierInfo(packageName, publicKey);
    } catch (NoSuchAlgorithmException e) {
        Log.wtf(TAG, "Could not parse public key because RSA isn't included in build");
        return null;
    } catch (InvalidKeySpecException e) {
    // Not a RSA public key.
    }
    /* Now try it as a DSA key. */
    try {
        final KeyFactory keyFactory = KeyFactory.getInstance("DSA");
        final PublicKey publicKey = keyFactory.generatePublic(keySpec);
        return new VerifierInfo(packageName, publicKey);
    } catch (NoSuchAlgorithmException e) {
        Log.wtf(TAG, "Could not parse public key because DSA isn't included in build");
        return null;
    } catch (InvalidKeySpecException e) {
    // Not a DSA public key.
    }
    return null;
}
Also used : PublicKey(java.security.PublicKey) TypedArray(android.content.res.TypedArray) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) KeyFactory(java.security.KeyFactory) EncodedKeySpec(java.security.spec.EncodedKeySpec) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec)

Aggregations

KeyFactory (java.security.KeyFactory)425 PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)187 PrivateKey (java.security.PrivateKey)181 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)125 PublicKey (java.security.PublicKey)125 X509EncodedKeySpec (java.security.spec.X509EncodedKeySpec)119 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)109 CertificateFactory (java.security.cert.CertificateFactory)103 ByteArrayInputStream (java.io.ByteArrayInputStream)93 Certificate (java.security.cert.Certificate)89 X509Certificate (java.security.cert.X509Certificate)87 RSAPublicKeySpec (java.security.spec.RSAPublicKeySpec)62 PrivateKeyEntry (java.security.KeyStore.PrivateKeyEntry)59 IOException (java.io.IOException)53 Entry (java.security.KeyStore.Entry)53 TrustedCertificateEntry (java.security.KeyStore.TrustedCertificateEntry)53 BigInteger (java.math.BigInteger)47 RSAPublicKey (java.security.interfaces.RSAPublicKey)46 RSAPrivateKey (java.security.interfaces.RSAPrivateKey)45 Signature (java.security.Signature)40