您当前的位置: 首页 >  Java

JAVA RSA加密解密代码范例(byte[]版)

柳鲲鹏 发布时间:2021-09-23 08:21:04 ,浏览量:0

具体代码:

package tsoffice;


import javax.crypto.Cipher;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;

public final class TestRSA
{
    private final static String ALGORITHM = "RSA";
    private final static String CHARSET   = "utf-8";

    /**
     * 密钥长度 于原文长度对应 以及越长速度越慢
     */
    private final static int KEY_SIZE = 512;

    private static PublicKey  publicKey;
    private static PrivateKey privateKey;
    
    /**
     * 随机生成密钥对
     */
    public static void genKeyPair() throws NoSuchAlgorithmException {
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(ALGORITHM);
        keyPairGen.initialize(KEY_SIZE, new SecureRandom());
        KeyPair keyPair = keyPairGen.generateKeyPair();
        publicKey  = keyPair.getPublic();
        privateKey = keyPair.getPrivate();
    }

    public static byte[] encrypt(String str, PublicKey pubKey) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        
        return cipher.doFinal(str.getBytes(CHARSET));
    }

    public static byte[] decrypt(byte[] inputByte, PrivateKey priKey) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, priKey);
        return cipher.doFinal(inputByte);
    }

    public static void main(String[] args) throws Exception {
        long temp = System.currentTimeMillis();
        //生成公钥和私钥
        genKeyPair();
        System.out.println("生成密钥消耗时间:" + (System.currentTimeMillis() - temp) / 1000.0 + "秒");
        
        String message = "公钥加密测试-:泰山Office";
        
        System.out.println("原文:" + message);
        temp = System.currentTimeMillis();
        byte[] messageEn = encrypt(message, publicKey);
        System.out.println("密文:" + messageEn.length);
        System.out.println("加密消耗时间:" + (System.currentTimeMillis() - temp) / 1000.0 + "秒");
        
        temp = System.currentTimeMillis();
        byte[] messageDe = decrypt(messageEn, privateKey);
        System.out.println("解密:" + new String(messageDe));
        System.out.println("解密消耗时间:" + (System.currentTimeMillis() - temp) / 1000.0 + "秒");
        
    }
}

关注
打赏
1688896170
查看更多评论

柳鲲鹏

暂无认证

  • 0浏览

    0关注

    4641博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文
立即登录/注册

微信扫码登录

0.0453s