import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.*;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.security.*;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Enumeration;
public class RSAUtil {
public static final String SIGN_ALGORITHMS = "SHA1WithRSA";
/**
* RSA最大加密明文大小
*/
private static final int MAX_ENCRYPT_BLOCK = 117;
/**
* RSA最大解密密文大小
*/
private static final int MAX_DECRYPT_BLOCK = 128;
public static String sign(String content, String input_charset, Key key)
throws UnsupportedEncodingException, Exception {
Cipher cipher;
try {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] output = cipher.doFinal(content.getBytes(input_charset));
return Base64.encode(output);
} catch (NoSuchAlgorithmException e) {
throw new Exception("无此加密算法");
} catch (NoSuchPaddingException e) {
e.printStackTrace();
return null;
} catch (InvalidKeyException e) {
throw new Exception("加密公钥非法,请检查");
} catch (IllegalBlockSizeException e) {
throw new Exception("明文长度非法");
} catch (BadPaddingException e) {
throw new Exception("明文数据已损坏");
}
}
public static String readFile(String filePath, String charSet) throws Exception {
FileInputStream fileInputStream = new FileInputStream(filePath);
try {
FileChannel fileChannel = fileInputStream.getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate((int) fileChannel.size());
fileChannel.read(byteBuffer);
byteBuffer.flip();
return new String(byteBuffer.array(), charSet);
} finally {
fileInputStream.close();
}
}
public static String getKey(String string) throws Exception {
String content = readFile(string, "UTF8");
return content.replaceAll("\\-{5}[\\w\\s]+\\-{5}[\\r\\n|\\n]", "");
}
public static boolean verifyByKeyPath(String content, String sign, String publicKeyPath, String input_charset) {
try {
return verifyByPublicKey(content, sign, getKey(publicKeyPath), input_charset);
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public static KeyInfo getPFXPrivateKey(String pfxPath, String password)
throws KeyStoreException, NoSuchAlgorithmException,
CertificateException, IOException, UnrecoverableKeyException {
FileInputStream fis = new FileInputStream(pfxPath);
KeyStore ks = KeyStore.getInstance("PKCS12");
ks.load(fis, password.toCharArray());
fis.close();
Enumeration<String> enumas = ks.aliases();
String keyAlias = null;
if (enumas.hasMoreElements())// we are readin just one certificate.
{
keyAlias = enumas.nextElement();
}
KeyInfo keyInfo = new
RAS 加密工具类
最新推荐文章于 2024-07-01 15:19:51 发布
本文详细介绍了如何在Java中使用RSA算法进行加密操作,包括密钥对的生成、加密过程和解密步骤,适合需要在Java项目中应用RSA加密的开发者参考。
摘要由CSDN通过智能技术生成