常用加密解密(3)——非对称加密

原文链接:https://www.dubby.cn/detail.html?id=9124

最常用的非对称加密算法应该就是RSA,而且非对称加密算法的实现比较复杂,所以这里只介绍RSA。

密钥长度密钥默认长度工作模式填充方式
512~65536(必须是64的倍数)密钥默认长度:1024工作模式:ECB填充方式:NoPadding,PKCS1Padding等其他

RSA加密有两种方式,一种是私钥加密,公钥解密:

另一种是公钥加密,私钥解密:

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * 密钥长度:512~65536
 * 密钥默认长度:1024
 * 工作模式:ECB
 * 填充方式:NoPadding,PKCS1Padding等其他
 */
public class RSA {

    private static final String key_algorithm = "RSA";

    private static final String cipher_algorithm = "RSA/ECB/PKCS1Padding";

    public static byte[] encryptWithPrivateKey(byte[] keyBytes, byte[] dataBytes) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(key_algorithm);
        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);

        Cipher cipher = Cipher.getInstance(cipher_algorithm);
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);
        return cipher.doFinal(dataBytes);
    }

    public static byte[] decryptWithPrivateKey(byte[] keyBytes, byte[] dataBytes) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeySpecException, BadPaddingException, IllegalBlockSizeException, InvalidKeyException {
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(key_algorithm);
        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);

        Cipher cipher = Cipher.getInstance(cipher_algorithm);
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        return cipher.doFinal(dataBytes);
    }

    public static byte[] encryptWithPublicKey(byte[] keyBytes, byte[] dataBytes) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, BadPaddingException, IllegalBlockSizeException, InvalidKeyException {
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(key_algorithm);
        PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);

        Cipher cipher = Cipher.getInstance(cipher_algorithm);
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        return cipher.doFinal(dataBytes);
    }

    public static byte[] decryptWithPublicKey(byte[] keyBytes, byte[] dataBytes) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, BadPaddingException, IllegalBlockSizeException, InvalidKeyException {
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(key_algorithm);
        PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);

        Cipher cipher = Cipher.getInstance(cipher_algorithm);
        cipher.init(Cipher.DECRYPT_MODE, publicKey);
        return cipher.doFinal(dataBytes);
    }
}

测试代码:

import org.junit.Assert;
import org.junit.Test;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.util.Base64;

public class RSATest {

    private static final String key_algorithm = "RSA";

    private static final int key_size = 1024;

    private static final String data = "Hello, Dubby";

    @Test
    public void test() throws NoSuchAlgorithmException, IllegalBlockSizeException, InvalidKeyException, BadPaddingException, InvalidKeySpecException, NoSuchPaddingException {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(key_algorithm);
        keyPairGenerator.initialize(key_size);

        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

        //公钥加密,私钥解密
        {
            byte[] encryptBytes = RSA.encryptWithPublicKey(publicKey.getEncoded(), data.getBytes(Charset.forName("UTF-8")));
            System.out.println(Base64.getEncoder().encodeToString(encryptBytes));
            byte[] decryptBytes = RSA.decryptWithPrivateKey(privateKey.getEncoded(), encryptBytes);
            String result = new String(decryptBytes, Charset.forName("UTF-8"));
            System.out.println(result);
            Assert.assertEquals(result, data);
        }

        //私钥加密,公钥解密
        {
            byte[] encryptBytes = RSA.encryptWithPrivateKey(privateKey.getEncoded(), data.getBytes(Charset.forName("UTF-8")));
            System.out.println(Base64.getEncoder().encodeToString(encryptBytes));
            byte[] decryptBytes = RSA.decryptWithPublicKey(publicKey.getEncoded(), encryptBytes);
            String result = new String(decryptBytes, Charset.forName("UTF-8"));
            System.out.println(result);
            Assert.assertEquals(result, data);
        }
    }
}

要注意,RSA对待加密的明文长度限制很大,如key长度是1024,那么最多可加密1024/8 - 11 = 117bytes,如果密钥长度是2048 ,那么2048/8 - 11 = 245bytes。而这很容易超出限制,这在使用时要特别注意。事实上,一般只用非对称加密来传递密钥,之后的传输就直接密钥来做对称加密即可,比如HTTPS。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值