RSA encode Data - Android java.security

Android examples for java.security:RSA

Description

RSA encode Data

Demo Code


//package com.java2s;
import android.util.Base64;
import java.io.ByteArrayOutputStream;
import java.security.Key;
import java.security.KeyFactory;

import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;

public class Main {

    private static final int MAX_ENCRYPT_BLOCK = 117;
    private static String sPublicKey = null;

    public static byte[] encodeData(byte[] data) throws Exception {
        byte[] encodeData = encryptByPublicKey(data, sPublicKey);
        return encodeData;
    }/*w ww .j  av a2  s  .  com*/

    public static byte[] encryptByPublicKey(byte[] data, String publicKey)
            throws Exception {
        //Log.i("MyApplication", "src data="+new String(data,"UTF-8"));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] bytePublicKey = Base64.decode(publicKey, Base64.DEFAULT);
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(
                bytePublicKey);
        Key publicK = keyFactory.generatePublic(x509EncodedKeySpec);


        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); //Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, publicK);
        int inputLen = data.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;

        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(data, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * 117;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();
        return encryptedData;
    }
}

Related Tutorials