RSA非对称加密通常运用于对字符串进行加密,通过密钥对(公钥、私钥)实现加密。
通过生成的公钥,对字符串加密后,得到一个加密的字符串,将私钥与这个加密后的字符串进行解密,得到原先的字符串。
补充:如果加密的字符串过长,会报错:javax.crypto.IllegalBlockSizeException: Data must not be longer than 117 byte
这里在文章后面补充两个方法用于解决超出117字节加密和126字节解密问题。
Java代码:
package com.vandet.indwebproject.utils;
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.UrlBase64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;
import sun.security.rsa.RSASignature;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.security.*;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
import static com.vandet.indwebproject.test.Test2.KEY_ALGORITHM;
public class RSAUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(RSAUtils.class);
public static final String KEY_ALGORITHM = "RSA";
public static final String SIGNATURE_ALGORITHM = "SHA1WithRSA";
public static final String ENCODING = "utf-8";
public static final String X509 = "X.509";
/**
* 获取私钥
*
* @param key
* @return
* @throws Exception
*/
public static PrivateKey getPrivateKey(Str

本文介绍了如何使用Java实现RSA非对称加密,探讨了在加密过程中遇到的字符串长度限制问题,并提供了超出117字节加密及126字节解密的解决方案。
最低0.47元/天 解锁文章
2198

被折叠的 条评论
为什么被折叠?



