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

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

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

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

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

image

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

image
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。

你可能感兴趣的:(常用加密解密(3)——非对称加密)