Nick
Nick

Reputation: 3494

Public-key encryption between Android and Google App Engine

Is there some boilerplate code or libraries to implement a public/private key encryption between an Android app and Google App Engine (Java)? I'd like to encrypt a message in an Android app using a public key, submit it to GAE, and have GAE decrypt the message using the corresponding private key.

Upvotes: 0

Views: 127

Answers (2)

Ray
Ray

Reputation: 16235

Here is one example doing public key encryption on Android

public static byte[] encrypt(String publicKey, String data) {
        if (TextUtils.isEmpty(publicKey) || TextUtils.isEmpty(data)) {
            return null;
        }
        try {
            // Decode the modified public key into a byte[]
            byte[] publicKeyByteArray = Base64.decode(publicKey.getBytes("UTF-8"),Base64.NO_WRAP);

            Cipher mCipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(publicKeyByteArray);
            Key key = keyFactory.generatePublic(x509KeySpec);
            mCipher.init(Cipher.ENCRYPT_MODE, key);
            return mCipher.doFinal(data.getBytes("UTF-8"));
        }
        catch (UnsupportedEncodingException e) {
            Log.e("RSAKEY", e.getMessage());
        }
        catch (NoSuchPaddingException e) {
            Log.e("RSAKEY", e.getMessage());
        } catch (NoSuchAlgorithmException e) {
            Log.e("RSAKEY", e.getMessage());
        } catch (InvalidKeyException e) {
            Log.e("RSAKEY", e.getMessage());
        } catch (InvalidKeySpecException e) {
            Log.e("RSAKEY", e.getMessage());
        } catch (IllegalBlockSizeException e) {
            Log.e("RSAKEY", e.getMessage());
        } catch (BadPaddingException e) {
            Log.e("RSAKEY", e.getMessage());
        }
        return null;
    }

Upvotes: 0

Martin Berends
Martin Berends

Reputation: 4178

Just enable HTTPS, it sends a Google public key to the Android device to encrypt a random client session key and automatically decrypts that session key using a Google private key in the AppEngine server, then bidirectionally transfers messages encrypted with the session key. Session keys use less bandwidth than encrypting and decrypting a whole message using public and private keys.

Upvotes: 2

Related Questions