decrypt By RSA Private Key - Java Security

Java examples for Security:RSA

Description

decrypt By RSA Private Key

Demo Code


//package com.java2s;
import javax.crypto.Cipher;

import java.security.interfaces.RSAPrivateKey;

public class Main {

    public static String decryptByPrivateKey(String data, RSAPrivateKey key)
            throws Exception {
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        //??// w w  w  .j  a v a 2  s.  co  m
        int key_len = 0;
        cipher.init(Cipher.DECRYPT_MODE, key);
        key_len = key.getModulus().bitLength() / 8;
        byte[] x = data.getBytes();
        byte[] x1 = ASCII_To_BCD(x, x.length);
        return new String(cipher.doFinal(x1));
    }

    public static byte[] ASCII_To_BCD(byte[] ascii, int asc_len) {
        byte[] bcd = new byte[asc_len / 2];
        int j = 0;
        for (int i = 0; i < (asc_len + 1) / 2; i++) {
            bcd[i] = asc_to_bcd(ascii[j++]);
            bcd[i] = (byte) (((j >= asc_len) ? 0x00
                    : asc_to_bcd(ascii[j++])) + (bcd[i] << 4));
        }
        return bcd;
    }

    public static byte asc_to_bcd(byte asc) {
        byte bcd;

        if ((asc >= '0') && (asc <= '9'))
            bcd = (byte) (asc - '0');
        else if ((asc >= 'A') && (asc <= 'F'))
            bcd = (byte) (asc - 'A' + 10);
        else if ((asc >= 'a') && (asc <= 'f'))
            bcd = (byte) (asc - 'a' + 10);
        else
            bcd = (byte) (asc - 48);
        return bcd;
    }
}

Related Tutorials