encode Rsa Message - Android java.security

Android examples for java.security:RSA

Description

encode Rsa Message

Demo Code


//package com.java2s;
import android.util.Base64;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

import java.security.InvalidKeyException;

import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;

public class Main {
    private static final String RSA_TRANSFORMATION_TYPE = "RSA/None/PKCS1Padding";

    public static String encodeRsaMessage(PublicKey publicKey,
            String message) throws InvalidKeyException,
            BadPaddingException, IllegalBlockSizeException,
            NoSuchPaddingException, NoSuchAlgorithmException {
        final Cipher cipher = Cipher.getInstance(RSA_TRANSFORMATION_TYPE);
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] cipherData = cipher.doFinal(message.getBytes());
        String encodedMessage = Base64
                .encodeToString(cipherData, Base64.DEFAULT)
                .replace("\n", "").replace("\r", "");

        return encodedMessage;
    }/*from w  w  w. j a v a  2  s. co  m*/
}

Related Tutorials