Example of use Certs in android

Posted on Actualizado enn

Even this is just an example, it was not easy to build it, there are a lot little information everywhere (stackoverflow)… but this code works, the you can test in a backend server the decrypt part…



button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {

        try {
            Open o=new Open();

        } catch (Exception e) {
});//closing the setOnClickListener method</pre>
import android.content.Context;
import android.util.Base64;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.ArrayList;
import java.util.List;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

 * @author hemc
public class Open {

    public Open(){}

    public void HelloA(Context mContext) {
        try {
            PublicKey publicKey = readPublicKey(mContext);
            PrivateKey privateKey = readPrivateKey(mContext);
            byte[] message = "Hello World".getBytes("UTF8");
            byte[] secret = encrypt(publicKey, message);
            //byte[] recovered_message = decryptRSA(privateKey, x.getBytes("UTF8"));
            byte[] recovered_message = decrypt(privateKey, secret);

            Log.d("---",new String(recovered_message, "UTF8"));

        } catch (Exception e) {

    public PublicKey readPublicKey(Context mContext) throws Exception{
        String filename=getFile(mContext.getResources().openRawResource(R.raw.publiccert));

        X509EncodedKeySpec publicSpec = new X509EncodedKeySpec(readFileBytes(filename));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePublic(publicSpec);

    public PrivateKey readPrivateKey(Context mContext) throws Exception{
        String filename=getFile(mContext.getResources().openRawResource(R.raw.keypair));

        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(readFileBytes(filename));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePrivate(keySpec);
    public byte[] encrypt(PublicKey key, byte[] plaintext) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        return cipher.doFinal(plaintext);

    public byte[] decrypt(PrivateKey key, byte[] ciphertext) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, key);
        return cipher.doFinal(ciphertext);

    public byte[] readFileBytes(String filename) throws IOException {
        return Base64.decode(filename.getBytes("utf-8"), Base64.DEFAULT);
    public String getFile(InputStream is){
        String keyString="";
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            List<String> lines = new ArrayList<String>();
            String line = null;
            while ((line = br.readLine()) != null)

            // removes the first and last lines of the file (comments)
            if (lines.size() > 1 && lines.get(0).startsWith("-----") && lines.get(lines.size() - 1).startsWith("-----")) {
                lines.remove(lines.size() - 1);
            // concats the remaining lines to a single String
            StringBuilder sb = new StringBuilder();
            for (String aLine : lines)
            keyString = sb.toString();
        }catch(Exception e){
        return keyString;



Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión /  Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión /  Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión /  Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión /  Cambiar )


Conectando a %s