欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

RSA

程序员文章站 2022-07-04 14:38:18
...

package com.client.rsa;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateCrtKey;
import java.security.interfaces.RSAPublicKey;

import com.nettyServer.util.BaseString;
import com.nettyServer.util.ByteUtils;

public class RSAUtil {
    public String[] initGenKey(int keylen) {
        String[] genInfo = new String[5];
        try {
            KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
            kpg.initialize(keylen);
            KeyPair kp = kpg.generateKeyPair();
            RSAPublicKey puk = (RSAPublicKey) kp.getPublic();
            RSAPrivateCrtKey prk = (RSAPrivateCrtKey) kp.getPrivate();
            BigInteger e = puk.getPublicExponent();
            BigInteger n = puk.getModulus();
            log("n len(" + n.toByteArray().length + ")");
            BigInteger d = prk.getPrivateExponent();
            BigInteger p = prk.getPrimeP();
            BigInteger q = prk.getPrimeQ();
            genInfo[0] = e.toString();
            genInfo[1] = n.toString();
            genInfo[2] = d.toString();
            genInfo[3] = p.toString();
            genInfo[4] = q.toString();
            String[] des = { "e", "n", "d", "p", "q" };
            for (int i = 0; i < genInfo.length; i++) {
                log(des[i] + "=" + genInfo[i]);
            }
        } catch (NoSuchAlgorithmException ex) {
            ex.printStackTrace();
        }
        return genInfo;
    }

    //encrypt data
    public byte[] encrypt(byte[] ptext, String eStr, String nStr) throws IOException {
        log("*******************************encrypt start*************************************");
        BigInteger e = new BigInteger(eStr);//publickey param d
        BigInteger n = new BigInteger(nStr);//publickey param d
        int len = (n.toByteArray().length - 1), i = 0;
        int inputLen = ptext.length;
        BigInteger m = null;
        BigInteger c = null;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache=null;
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > len) {
                cache = new byte[len];
            } else {
                cache = new byte[inputLen - offSet];
            }
            System.arraycopy(ptext, offSet, cache, 0, cache.length);
            m = new BigInteger(cache);
            c = m.modPow(e, n);
            out.write(c.toByteArray());
            log("encrypt before:len(" + cache.length + "),data("+i+"):"
                    + ByteUtils.bytesToHexString(cache));
            log("encrypt after data("+i+"):"
                    + ByteUtils.bytesToHexString(c.toByteArray()));
            i++;
            offSet = i * len;
        }
        byte[] encryptData=out.toByteArray();
        out.close();
        log("*******************************encrypt end*************************************");
        return encryptData;
    }

    //decrypt data
    public byte[] decrypt(byte[] miwen, String dStr, String nStr) throws IOException {
        log("*******************************decrypt start*************************************");
        BigInteger d = new BigInteger(dStr);//privatekey param d
        BigInteger n = new BigInteger(nStr);//privatekey param n
        BigInteger c = null;
        BigInteger m = null;
        int len = n.toByteArray().length;
        int i = 0;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int inputLen = miwen.length;
        int offSet = 0;
        byte[] cache = null;
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > len) {
                cache = new byte[len];
            } else {
                cache = new byte[inputLen - offSet];
            }
            System.arraycopy(miwen, offSet, cache, 0, cache.length);
            c = new BigInteger(cache);
            m = c.modPow(d, n);
            byte[] dData = m.toByteArray();
            out.write(dData);
            log("decrypt before data("+i+"):"
                    + ByteUtils.bytesToHexString(cache));
            log("decrypt after:len(" + dData.length + "),data("+i+"):"
                    + ByteUtils.bytesToHexString(dData));
            i++;
            offSet = i * len;
        }
        byte[] entryDataB=out.toByteArray();
        out.close();
        log("*******************************decrypt end*************************************");
        return entryDataB;
    }
   
    private void log(String log){
        System.out.println(log);
    }

    public static void main(String[] args) throws IOException {
        RSAUtil rsaUtil = new RSAUtil();
        String[] p = rsaUtil.initGenKey(1023);// 1023
        //中文需要采用base编码后再加密
        String data = "18BB49FBC8AE1A82EECFECF8BB89C9D35FAAB857CC0C3B959DA3C3D513CAB255A0B627FDDE15813629A00FBF464740A32C7907B5B845245D9CDAC3F5F68A666EAFDE3FCE21A8096A61BABB659DDDB899F8CD29B2604199BC1F42993DFAB09ABFBE6BE69B7C299CBA6797EEE21665AF6B67A8061DBE6FA2EB0825C366DD812129";
        //String text = Base64.encodeBase64String(data.getBytes("GBK"));
        rsaUtil.log("(" + data.length() + ")" + data);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        out.write(BaseString.getBytes(data));
        byte[] minwen = out.toByteArray();
        out.close();
        byte[] hex = rsaUtil.encrypt(minwen, p[0], p[1]);
        byte[] decodeData = rsaUtil.decrypt(hex, p[2], p[1]);
        data = BaseString.byteToString(decodeData);
        //data = BaseString.byteToString(Base64.decodeBase64(decodeData));
        rsaUtil.log("(" + data.length() + ")" + data);
    }
}


 

output:

n len(128)
e=65537
n=79878443116477431723910720076331964206927196983187460111829662096543709950682705577119366644900259032296548146226108881718640174009506648698055329399979826968504236032315385550029317396676828095359442971095598662249798287465446643154424521383364489258800969007909367639398542203155486245540834166630656463551
d=26360849103913421324209851744982341606534040562619259155876099483101871596401506877366032345024990499267737969491711291237175178654464040130636749687394346556715475310635822940069011833047004651164959543795626563240523875100964945568109834945618143409494207572709757223766144562392543175635168401408831807649
p=12388121363302700405059571893776373129179128456352582548743075852274073073044285422961339481772197365397373993998587373598128718142470712954759279729185579
q=6447986807192665658869257921655147348637730988762875266579286105565709187930397704433502779690215309166895026920782468729159257017248953918267942262113469
(256)18BB49FBC8AE1A82EECFECF8BB89C9D35FAAB857CC0C3B959DA3C3D513CAB255A0B627FDDE15813629A00FBF464740A32C7907B5B845245D9CDAC3F5F68A666EAFDE3FCE21A8096A61BABB659DDDB899F8CD29B2604199BC1F42993DFAB09ABFBE6BE69B7C299CBA6797EEE21665AF6B67A8061DBE6FA2EB0825C366DD812129
*******************************encrypt start*************************************
encrypt before:len(127),data(0):31384242343946424338414531413832454543464543463842423839433944333546414142383537434330433342393539444133433344353133434142323535413042363237464444453135383133363239413030464246343634373430413332433739303742354238343532343544394344414333463546363841363636
encrypt after data(0):0A393732881F8FD5347AC6EA5DD17D862567608038C39FDB57E0E0FCFA6C6BD2795FE9A7B52C9D60B57B70E867C692B907140A784C1C86E61E00E4CCBBC4541A83C97F7478C0F0A662066755A390022EB76ADA8948893564DF56524C58E47ACC672624C0EB9CE6822B703F69D851F9D68C84FB75D0A6636DE14E3A995AB38D3C
encrypt before:len(127),data(1):45414644453346434532314138303936413631424142423635394444444238393946384344323942323630343139394243314634323939334446414230394142464245364245363942374332393943424136373937454545323136363541463642363741383036314442453646413245423038323543333636444438313231
encrypt after data(1):48845A09A4FF5B012BBE42FC83F250B0AEA5D4FE1EA6A59BE813166C561EB1BA4F1744E79F50FC072016FF68384DCA1CA86B90BE50753956B9F1D5B68983F67C63EAF8ECFD62F1A6C3491469F6E6CFD8E895694678B2A24A9098FA120EF826C461B0ABF8B1B0C9E4EFD8E70547553068BA8560B61F7691E435E947E999A4B5C0
encrypt before:len(2),data(2):3239
encrypt after data(2):3D940F0A14DA5A9838AAF70049C978529569667BB5D3191A7075A3DA53205EA2C74E4F3CF21814514A45275246CBB579F9768ED321BFEAA8CCED6C6EA683DD866CB5660B513360799D69C4CF6BEBDCD0A1976510A6C6FF19E6A4915B85A5533FE5644E4CD761B0A37F3D19004685C52C8A931F074DE15D615DA88C3E98D99FD4
*******************************encrypt end*************************************
*******************************decrypt start*************************************
decrypt before data(0):0A393732881F8FD5347AC6EA5DD17D862567608038C39FDB57E0E0FCFA6C6BD2795FE9A7B52C9D60B57B70E867C692B907140A784C1C86E61E00E4CCBBC4541A83C97F7478C0F0A662066755A390022EB76ADA8948893564DF56524C58E47ACC672624C0EB9CE6822B703F69D851F9D68C84FB75D0A6636DE14E3A995AB38D3C
decrypt after:len(127),data(0):31384242343946424338414531413832454543464543463842423839433944333546414142383537434330433342393539444133433344353133434142323535413042363237464444453135383133363239413030464246343634373430413332433739303742354238343532343544394344414333463546363841363636
decrypt before data(1):48845A09A4FF5B012BBE42FC83F250B0AEA5D4FE1EA6A59BE813166C561EB1BA4F1744E79F50FC072016FF68384DCA1CA86B90BE50753956B9F1D5B68983F67C63EAF8ECFD62F1A6C3491469F6E6CFD8E895694678B2A24A9098FA120EF826C461B0ABF8B1B0C9E4EFD8E70547553068BA8560B61F7691E435E947E999A4B5C0
decrypt after:len(127),data(1):45414644453346434532314138303936413631424142423635394444444238393946384344323942323630343139394243314634323939334446414230394142464245364245363942374332393943424136373937454545323136363541463642363741383036314442453646413245423038323543333636444438313231
decrypt before data(2):3D940F0A14DA5A9838AAF70049C978529569667BB5D3191A7075A3DA53205EA2C74E4F3CF21814514A45275246CBB579F9768ED321BFEAA8CCED6C6EA683DD866CB5660B513360799D69C4CF6BEBDCD0A1976510A6C6FF19E6A4915B85A5533FE5644E4CD761B0A37F3D19004685C52C8A931F074DE15D615DA88C3E98D99FD4
decrypt after:len(2),data(2):3239
*******************************decrypt end*************************************
(256)18BB49FBC8AE1A82EECFECF8BB89C9D35FAAB857CC0C3B959DA3C3D513CAB255A0B627FDDE15813629A00FBF464740A32C7907B5B845245D9CDAC3F5F68A666EAFDE3FCE21A8096A61BABB659DDDB899F8CD29B2604199BC1F42993DFAB09ABFBE6BE69B7C299CBA6797EEE21665AF6B67A8061DBE6FA2EB0825C366DD812129

相关标签: RSA