RSA Encrypt - Android java.security

Android examples for java.security:RSA

Description

RSA Encrypt

Demo Code


//package com.java2s;
import android.util.Base64;

import java.security.KeyFactory;

import java.security.PublicKey;

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

public class Main {
    public static byte[] RSAEncrypt(String rawString, String key)
            throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        byte[] pubKeyBytes = Base64.decode(key, Base64.CRLF);
        PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(
                new X509EncodedKeySpec(pubKeyBytes));

        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] encryptedBytes = cipher.doFinal(rawString.getBytes());
        return encryptedBytes;
    }//w  w  w.j  a  v a 2  s  .c o  m
}

Related Tutorials