RSAUtils


创建RSA私钥:openssl genrsa -out rsa_private_key.pem 1024
创建RSA公钥:openssl rsa -in rsa_private_key.pem -out rsa_public_key.pem -pubout
私钥PKcs8编码:openssl pkcs8 -topk8 -in rsa_private_key.pem -out pkcs8_rsa_private_key.pem -nocrypt

OpenSSL生成的RSA公私钥进行数据加解密

http://blog.csdn.net/chaijunkun/article/details/7275632/


package com.csdn.test;



import org.apache.commons.codec.binary.Base64;


import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;


public class RSAUtils {
    public static final String KEY_ALGORITHM = "RSA";
    public static final String SIGNATURE_ALGORITHM = "MD5withRSA";
    private static final String CIPHER_ALGORITHM = "RSA/ECB/PKCS1Padding";


    // 1024->117,2048->245
    private static final int KEY_LEANGTH = 1024;
    private static final KeyFactory keyFactory = getKeyFactory();
    private static final KeyPairGenerator keyPairGen = getKeyPairGenerator();


    private static final int MAX_ENCRYPT_BLOCK = 117;


    private static final int MAX_DECRYPT_BLOCK = 128;


    /**
     * 获取钥匙工厂
     */
    private static KeyFactory getKeyFactory() {
        try {
            return KeyFactory.getInstance(KEY_ALGORITHM);
        } catch (Exception e) {
            return null;
        }
    }


    /**
     * 获取钥匙串生成器
     */


    private static KeyPairGenerator getKeyPairGenerator() {
        try {
            KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
            keyPairGen.initialize(KEY_LEANGTH);
            return keyPairGen;
        } catch (Exception e) {
            return null;
        }
    }


    /**
     * 获取Cipher
     */


    public static Cipher getCipher(byte[] keyBytes, boolean isPublic, boolean isEncrypt) throws Exception {
        if (isPublic) {
            X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
            Key publicKey = keyFactory.generatePublic(x509KeySpec);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            cipher.init(isEncrypt ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE, publicKey);
            return cipher;
        } else {
            PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
            Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            cipher.init(isEncrypt ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE, privateKey);
            return cipher;
        }
    }


    /**
     * 获取Signature
     */


    public static Signature getSignature(byte[] keyBytes, boolean isPublic) throws Exception {
        if (isPublic) {
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
            PublicKey pubKey = keyFactory.generatePublic(keySpec);
            Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
            signature.initVerify(pubKey);
            return signature;
        } else {
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
            PrivateKey priKey = keyFactory.generatePrivate(keySpec);
            Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
            signature.initSign(priKey);
            return signature;
        }
    }


    /**
     * 用私钥对信息生成数字签名
     */


    public static byte[] sign(byte[] data, byte[] privateKeyBytes) throws Exception {
        Signature signature = getSignature(privateKeyBytes, false);
        signature.update(data);
        return signature.sign();
    }


    /**
     * 校验数字签名
     */


    public static boolean verify(byte[] data, byte[] publicKeyBytes, byte[] signBytes) throws Exception {
        Signature signature = getSignature(publicKeyBytes, false);
        signature.update(data);
        return signature.verify(signBytes);
    }


    /**
     * 用私钥解密
     */


    public static byte[] decryptByPrivateKey(byte[] data, byte[] keyBytes) throws Exception {
        return getCipher(keyBytes, false, false).doFinal(data);
    }


    public static String base64DecryptByPrivateKey(String base64Data, String base64Key) throws Exception {


        Cipher cipher = getCipher(decryptBASE64(base64Key), false, false);


        byte[] dataByte = decryptBASE64(base64Data);
        int inputLen = dataByte.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offset = 0;
        byte[] cache;
        int i = 0;


        while (inputLen - offset > 0) {
            if (inputLen - offset > MAX_DECRYPT_BLOCK) {
                cache = cipher.doFinal(dataByte, offset, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(dataByte, offset, inputLen - offset);
            }
            out.write(cache, 0, cache.length);
            i++;
            offset = i * MAX_DECRYPT_BLOCK;
        }
        byte[] decryptData = out.toByteArray();
        out.close();


        return new String(decryptData);
    }


    /**
     * 用私钥加密
     */


    public static byte[] encryptByPrivateKey(byte[] data, byte[] keyBytes) throws Exception {
        return getCipher(keyBytes, false, true).doFinal(data);
    }


    public static String base64EncryptByPrivateKey(String data, String base64Key) throws Exception {


        Cipher cipher = getCipher(decryptBASE64(base64Key), false, true);
        byte[] dataByte = data.getBytes();
        int inputLen = dataByte.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offset = 0;
        byte[] cache;
        int i = 0;


        while (inputLen - offset > 0) {
            if (inputLen - offset > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(dataByte, offset, MAX_ENCRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(dataByte, offset, inputLen - offset);
            }
            out.write(cache, 0, cache.length);
            i++;
            offset = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptData = out.toByteArray();
        out.close();


        return encryptBASE64(encryptData);


    }


    /**
     * 用公钥解密
     */


    public static byte[] decryptByPublicKey(byte[] data, byte[] keyBytes) throws Exception {
        return getCipher(keyBytes, true, false).doFinal(data);
    }


    public static String base64DecryptByPublicKey(String base64Data, String base64Key) throws Exception {


        Cipher cipher = getCipher(decryptBASE64(base64Key), true, false);


        byte[] dataByte = decryptBASE64(base64Data);
        int inputLen = dataByte.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offset = 0;
        byte[] cache;
        int i = 0;


        while (inputLen - offset > 0) {
            if (inputLen - offset > MAX_DECRYPT_BLOCK) {
                cache = cipher.doFinal(dataByte, offset, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(dataByte, offset, inputLen - offset);
            }
            out.write(cache, 0, cache.length);
            i++;
            offset = i * MAX_DECRYPT_BLOCK;
        }
        byte[] decryptData = out.toByteArray();
        out.close();


        return new String(decryptData);
    }


    /**
     * 用公钥加密
     */


    public static byte[] encryptByPublicKey(byte[] data, byte[] keyBytes) throws Exception {
        return getCipher(keyBytes, true, true).doFinal(data);
    }


    public static String base64EncryptByPublicKey(String data, String base64Key) throws Exception {


        Cipher cipher = getCipher(decryptBASE64(base64Key), true, true);
        byte[] dataByte = data.getBytes();
        int inputLen = dataByte.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offset = 0;
        byte[] cache;
        int i = 0;


        while (inputLen - offset > 0) {
            if (inputLen - offset > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(dataByte, offset, MAX_ENCRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(dataByte, offset, inputLen - offset);
            }
            out.write(cache, 0, cache.length);
            i++;
            offset = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptData = out.toByteArray();
        out.close();


        return encryptBASE64(encryptData);
    }


    /**
     * 初始化公钥密钥
     */


    public static KeyPair initKey() throws Exception {
        return keyPairGen.generateKeyPair();
    }


    public static byte[] getPublicKeyBytes(KeyPair keyPair) throws Exception {
        return keyPair.getPublic().getEncoded();
    }


    public static String getPublicKeyBase64(KeyPair keyPair) throws Exception {
        return encryptBASE64(getPublicKeyBytes(keyPair));
    }


    public static byte[] getPrivateKeyBytes(KeyPair keyPair) throws Exception {
        return keyPair.getPrivate().getEncoded();
    }


    public static String getPrivateKeyBase64(KeyPair keyPair) throws Exception {
        return encryptBASE64(getPrivateKeyBytes(keyPair));
    }


    /**
     * BASE64加密
     *
     * @param key
     * @return
     * @throws Exception
     */
    public static String encryptBASE64(byte[] key) throws Exception {
        return new String(Base64.encodeBase64(key));
    }


    /**
     * BASE64解密
     *
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] decryptBASE64(String key) throws Exception {
        return Base64.decodeBase64(key.getBytes());
    }


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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值