Search in sources :

Example 1 with RSAPublicKeySpec

use of java.security.spec.RSAPublicKeySpec 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 2 with RSAPublicKeySpec

use of java.security.spec.RSAPublicKeySpec 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 3 with RSAPublicKeySpec

use of java.security.spec.RSAPublicKeySpec 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 4 with RSAPublicKeySpec

use of java.security.spec.RSAPublicKeySpec in project platformlayer by platformlayer.

the class KeyParser method parse.

public Object parse(String s) {
    Object key = null;
    if (key == null) {
        if (s.contains(BEGIN_PRIVATE_KEY)) {
            String payload = s.substring(s.indexOf(BEGIN_PRIVATE_KEY) + BEGIN_PRIVATE_KEY.length());
            if (payload.contains(END_PRIVATE_KEY)) {
                payload = payload.substring(0, payload.indexOf(END_PRIVATE_KEY));
                key = tryParsePemFormat(payload);
            }
        }
    }
    if (key == null) {
        try {
            PemReader reader = new PemReader(new StringReader(s));
            PemObject pemObject = reader.readPemObject();
            reader.close();
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pemObject.getContent());
            KeyFactory kf = KeyFactory.getInstance("RSA");
            PrivateKey privateKey = kf.generatePrivate(keySpec);
            if (privateKey instanceof RSAPrivateCrtKey) {
                RSAPrivateCrtKey rsaPrivateCrtKey = (RSAPrivateCrtKey) privateKey;
                RSAPublicKeySpec publicKeySpec = new java.security.spec.RSAPublicKeySpec(rsaPrivateCrtKey.getModulus(), rsaPrivateCrtKey.getPublicExponent());
                PublicKey publicKey = kf.generatePublic(publicKeySpec);
                key = new KeyPair(publicKey, privateKey);
            } else {
                key = privateKey;
            }
        } catch (Exception e) {
            log.debug("Error reading pem data", e);
            return null;
        }
    }
    if (key == null) {
        try {
            // TODO: Check if looks like base64??
            byte[] fromBase64 = Base64.decode(s);
            key = parse(fromBase64);
        } catch (Exception e) {
            log.debug("Cannot decode as base64", e);
        }
    }
    return key;
}
Also used : KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) RSAPrivateCrtKey(java.security.interfaces.RSAPrivateCrtKey) PublicKey(java.security.PublicKey) RSAPublicKeySpec(java.security.spec.RSAPublicKeySpec) PemReader(org.bouncycastle.util.io.pem.PemReader) PemObject(org.bouncycastle.util.io.pem.PemObject) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) StringReader(java.io.StringReader) PemObject(org.bouncycastle.util.io.pem.PemObject) KeyFactory(java.security.KeyFactory)

Example 5 with RSAPublicKeySpec

use of java.security.spec.RSAPublicKeySpec in project robovm by robovm.

the class RSAPublicKeySpecTest method testGetPublicExponent.

/**
     * Test for <code>getPublicExponent()</code> method<br>
     * Assertion: returns public exponent
     */
public final void testGetPublicExponent() {
    RSAPublicKeySpec rpks = new RSAPublicKeySpec(BigInteger.valueOf(3L), BigInteger.valueOf(1234567890L));
    assertTrue(BigInteger.valueOf(1234567890L).equals(rpks.getPublicExponent()));
}
Also used : RSAPublicKeySpec(java.security.spec.RSAPublicKeySpec)

Aggregations

RSAPublicKeySpec (java.security.spec.RSAPublicKeySpec)82 KeyFactory (java.security.KeyFactory)59 PublicKey (java.security.PublicKey)46 RSAPublicKey (java.security.interfaces.RSAPublicKey)29 BigInteger (java.math.BigInteger)23 Signature (java.security.Signature)22 PrivateKey (java.security.PrivateKey)20 RSAPrivateKeySpec (java.security.spec.RSAPrivateKeySpec)17 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)13 PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)12 Cipher (javax.crypto.Cipher)12 RSAPrivateKey (java.security.interfaces.RSAPrivateKey)10 SecretKeyFactory (javax.crypto.SecretKeyFactory)10 X509EncodedKeySpec (java.security.spec.X509EncodedKeySpec)9 IOException (java.io.IOException)8 KeySpec (java.security.spec.KeySpec)8 KeyPair (java.security.KeyPair)6 RSAPrivateCrtKey (java.security.interfaces.RSAPrivateCrtKey)6 RSAPrivateCrtKeySpec (java.security.spec.RSAPrivateCrtKeySpec)6 InvalidKeyException (java.security.InvalidKeyException)5