Rsa加密解密工具类

直接上代码没什么好说的。

import com.hxypt.exception.DecryptException;
import com.hxypt.exception.EncryptException;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * 加密和解密工具
 */
public class RSAUtil {

    private static final String KEY_ALGORITHM = "RSA";

    /**
     * RSA最大加密明文大小
     */
    private static final int MAX_ENCRYPT_BLOCK = 245;

    /**
     * RSA最大解密密文大小
     */
    private static final int MAX_DECRYPT_BLOCK = 256;

    /**
     * 公钥加解密
     * @param data
     * @param publicKeyData
     * @param encrypt true表示加密,false解密
     * @return
     * @throws Exception
     */
    public static String encryptByPublicKey(byte[] data,String publicKeyData,boolean encrypt)throws Exception{
        byte[] decodedKey = Base64.decodeBase64(publicKeyData);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decodedKey);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        PublicKey publicKey = keyFactory.generatePublic(keySpec);
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        if(encrypt){
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] encryptedData = null;
            int dataLen = data.length;
            int offset = 0;
            int i = 0;
            ByteArrayOutputStream baos = null;
            byte[] cache = null;
            try {
                baos = new ByteArrayOutputStream();
                while(dataLen-offset > 0){
                    if(dataLen-offset > MAX_ENCRYPT_BLOCK){
                        cache = cipher.doFinal(data, offset, MAX_ENCRYPT_BLOCK);
                    }else{
                        cache = cipher.doFinal(data, offset, dataLen-offset);
                    }
                    baos.write(cache,0,cache.length);
                    i++;
                    offset = i * MAX_ENCRYPT_BLOCK;
                }
                encryptedData = baos.toByteArray();
            } catch (Exception e) {
                throw new EncryptException();
            }finally{
                try {
                    if(baos != null){
                        baos.close();
                    }
                } catch (Exception e2) {}
            }
            return Base64.encodeBase64String(encryptedData);
        }else{
            cipher.init(Cipher.DECRYPT_MODE, publicKey);
            byte[] decryptedData = null;
            data = Base64.decodeBase64(data);
            int dataLen = data.length;
            int offset = 0;
            int i = 0;
            byte[] cache = null;
            ByteArrayOutputStream baos = null;
            try {
                baos = new ByteArrayOutputStream();
                while(dataLen-offset > 0){
                    if(dataLen-offset > MAX_DECRYPT_BLOCK){
                        cache = cipher.doFinal(data, offset, MAX_DECRYPT_BLOCK);
                    }else{
                        cache = cipher.doFinal(data, offset, dataLen-offset);
                    }
                    baos.write(cache, 0, cache.length);
                    i++;
                    offset = i * MAX_DECRYPT_BLOCK;
                }
                decryptedData = baos.toByteArray();
            } catch (Exception e) {
                throw new DecryptException();
            }finally{
                try {
                    if(baos != null){
                        baos.close();
                    }
                } catch (Exception e2) {}
            }
            return new String(decryptedData,"utf-8");
        }
    }

    /**
     * 私钥加解密
     * @param data
     * @param privateKeyData
     * @param encrypt true表示加密,false解密
     * @return
     */
    public static String encryptByPrivateKey(byte[] data,String privateKeyData,boolean encrypt)throws Exception{
        byte[] encodedKey = Base64.decodeBase64(privateKeyData);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encodedKey);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        if(encrypt){
            cipher.init(Cipher.ENCRYPT_MODE, privateKey);
            byte[] encryptedData = null;
            int dataLen = data.length;
            int offset = 0;
            int i = 0;
            byte[] cache = null;
            ByteArrayOutputStream baos = null;
            try {
                baos = new ByteArrayOutputStream();
                while(dataLen-offset > 0){
                    if(dataLen-offset > MAX_ENCRYPT_BLOCK){
                        cache = cipher.doFinal(data,offset,MAX_ENCRYPT_BLOCK);
                    }else{
                        cache = cipher.doFinal(data,offset,dataLen-offset);
                    }
                    baos.write(cache, 0, cache.length);
                    i++;
                    offset = i * MAX_ENCRYPT_BLOCK;
                }
                encryptedData = baos.toByteArray();
            } catch (Exception e) {
                throw new EncryptException();
            }finally{
                try {
                    if(baos != null){
                        baos.close();
                    }
                } catch (Exception e2) {}
            }
            return Base64.encodeBase64String(encryptedData);
        }else{
            //解密
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            byte[] decryptedData = null;
            data = Base64.decodeBase64(data);
            int dataLen = data.length;
            int offset = 0;
            int i = 0;
            byte[] cache = null;
            ByteArrayOutputStream baos = null;
            try {
                baos = new ByteArrayOutputStream();

                while(dataLen-offset > 0){
                    if(dataLen-offset > MAX_DECRYPT_BLOCK){
                        cache = cipher.doFinal(data, offset, MAX_DECRYPT_BLOCK);
                    }else{
                        cache = cipher.doFinal(data, offset, dataLen-offset);
                    }
                    baos.write(cache, 0, cache.length);
                    i++;
                    offset = i * MAX_DECRYPT_BLOCK;
                }
                decryptedData = baos.toByteArray();
            } catch (Exception e) {
                throw new DecryptException();
            }finally{
                try {
                    if(baos != null){
                        baos.close();
                    }
                } catch (Exception e2) {}
            }
            return new String(decryptedData,"utf-8");
        }
    }

    public static void main(String[] args) throws Exception {


        String key = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCif5fXhEgEWqhYeGXvxgfTZWGNHrO802yahokIhf8YyYTV+6gvetDjc1dS3WzsnXnxn+stKNrAtiiI60T6IqLkkWuCa4ZGWoiaUHpV5g1ASY2ObxsBIT8Kt7yjEzD315LrxF5lQZUl4Rhg/ve5QIDAQAB";
        String encryptStr = RSAUtil.encryptByPublicKey("password".getBytes(), key, true);

        System.out.println(encryptStr);
    }

}

就是一个工具类,可以不用关心其生成的原理,在main方法里调用生成对应的密文或明文就行了,需要注意的是,这里使用的解密方法需要又加密方提供公钥,就是key ,解密的话私钥也是要获取到。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值