当前位置:首页 » 编程语言 » 公钥加密java

公钥加密java

发布时间: 2022-06-22 02:47:23

java公钥加密,私钥解密,该怎么解决

一个比较简单的实现:一个三个类KeyGenerater生成公钥私钥对,Signaturer类使用私钥签名,SignProvider用公钥验证。公钥和私钥使用Base64加密Base64这个类也在博客里面
public class KeyGenerater {
private byte[] priKey;
private byte[] pubKey;
public void generater() {
try {
Java.security.KeyPairGenerator keygen = java.security.KeyPairGenerator
.getInstance("RSA");
SecureRandom secrand = new SecureRandom();
secrand.setSeed("syj".getBytes()); // 初始化随机产生器
keygen.initialize(1024, secrand);
KeyPair keys = keygen.genKeyPair();
PublicKey pubkey = keys.getPublic();
PrivateKey prikey = keys.getPrivate();
pubKey = Base64.encodeToByte(pubkey.getEncoded());
priKey = Base64.encodeToByte(prikey.getEncoded());
System.out.println("pubKey = " + new String(pubKey));
System.out.println("priKey = " + new String(priKey));
} catch (java.lang.Exception e) {
System.out.println("生成密钥对失败");
e.printStackTrace();
}
}
public byte[] getPriKey() {
return priKey;
}
public byte[] getPubKey() {
return pubKey;
}
}

public class Signaturer {
/**
*
* Description:数字签名
*
* @param priKeyText
* @param plainText
* @return
* @author 孙钰佳
* @since:2007-12-27 上午10:51:48
*/
public static byte[] sign(byte[] priKeyText, String plainText) {
try {
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64
.decode(priKeyText));
KeyFactory keyf = KeyFactory.getInstance("RSA");
PrivateKey prikey = keyf.generatePrivate(priPKCS8);
// 用私钥对信息生成数字签名
java.security.Signature signet = java.security.Signature
.getInstance("MD5withRSA");
signet.initSign(prikey);
signet.update(plainText.getBytes());
byte[] signed = Base64.encodeToByte(signet.sign());
return signed;
} catch (java.lang.Exception e) {
System.out.println("签名失败");
e.printStackTrace();
}
return null;
}
}
public class SignProvider {
private SignProvider() {
}
/**
*
* Description:校验数字签名,此方法不会抛出任务异常,成功返回true,失败返回false,要求全部参数不能为空
*
* @param pubKeyText
* 公钥,base64编码
* @param plainText
* 明文
* @param signTest
* 数字签名的密文,base64编码
* @return 校验成功返回true 失败返回false
* @author 孙钰佳
* @since:2007-12-27 上午09:33:55
*/
public static boolean verify(byte[] pubKeyText, String plainText,
byte[] signText) {
try {
// 解密由base64编码的公钥,并构造X509EncodedKeySpec对象
java.security.spec.X509EncodedKeySpec bobPubKeySpec = new java.security.spec.X509EncodedKeySpec(
Base64.decode(pubKeyText));
// RSA对称加密算法
java.security.KeyFactory keyFactory = java.security.KeyFactory
.getInstance("RSA");
// 取公钥匙对象
java.security.PublicKey pubKey = keyFactory
.generatePublic(bobPubKeySpec);
// 解密由base64编码的数字签名
byte[] signed = Base64.decode(signText);
java.security.Signature signatureChecker = java.security.Signature
.getInstance("MD5withRSA");
signatureChecker.initVerify(pubKey);
signatureChecker.update(plainText.getBytes());
// 验证签名是否正常
if (signatureChecker.verify(signed))
return true;
else
return false;
} catch (Throwable e) {
System.out.println("校验签名失败");
e.printStackTrace();
return false;
}
}
}

望采纳,谢谢。

② JAVA公钥加密,私钥解密,该怎么解决

public abstract class RSACoder extends Coder {public static final String KEY_ALGORITHM = "RSA";public static final String SIGNATURE_ALGORITHM = "MD5withRSA";private static final String PUBLIC_KEY = "RSAPublicKey";private static final String PRIVATE_KEY = "RSAPrivateKey";/*** 用私钥对信息生成数字签名* * @param data 加密数据* @param privateKey* 私钥* * @return* @throws Exception*/public static String sign(byte[] data, String privateKey) throws Exception {// 解密由base64编码的私钥byte[] keyBytes = decryptBASE64(privateKey);// 构造PKCS8EncodedKeySpec对象PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);// KEY_ALGORITHM 指定的加密算法KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);// 取私钥匙对象PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec);// 用私钥对信息生成数字签名Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);signature.initSign(priKey);signature.update(data);return encryptBASE64(signature.sign());}/*** 校验数字签名* * @param data* 加密数据* @param publicKey* 公钥* @param sign* 数字签名* * @return 校验成功返回true 失败返回false* @throws Exception* */public static boolean verify(byte[] data, String publicKey, String sign)throws Exception {// 解密由base64编码的公钥byte[] keyBytes = decryptBASE64(publicKey);// 构造X509EncodedKeySpec对象X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);// KEY_ALGORITHM 指定的加密算法KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);// 取公钥匙对象PublicKey pubKey = keyFactory.generatePublic(keySpec);Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);signature.initVerify(pubKey);signature.update(data);// 验证签名是否正常return signature.verify(decryptBASE64(sign));}/*** 解密<br>* 用私钥解密* * @param data* @param key* @return* @throws Exception*/public static byte[] decryptByPrivateKey(byte[] data, String key)throws Exception {// 对密钥解密byte[] keyBytes = decryptBASE64(key);// 取得私钥PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);// 对数据解密Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());cipher.init(Cipher.DECRYPT_MODE, privateKey);return cipher.doFinal(data);}/*** 解密<br>* 用公钥解密* * @param data* @param key* @return* @throws Exception*/public static byte[] decryptByPublicKey(byte[] data, String key)throws Exception {// 对密钥解密byte[] keyBytes = decryptBASE64(key);// 取得公钥X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);Key publicKey = keyFactory.generatePublic(x509KeySpec);// 对数据解密Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());cipher.init(Cipher.DECRYPT_MODE, publicKey);return cipher.doFinal(data);}/*** 加密<br>* 用公钥加密* * @param data* @param key* @return* @throws Exception*/public static byte[] encryptByPublicKey(byte[] data, String key)throws Exception {// 对公钥解密byte[] keyBytes = decryptBASE64(key);// 取得公钥X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);Key publicKey = keyFactory.generatePublic(x509KeySpec);// 对数据加密Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());cipher.init(Cipher.ENCRYPT_MODE, publicKey);return cipher.doFinal(data);}/*** 加密<br>* 用私钥加密* * @param data* @param key* @return* @throws Exception*/public static byte[] encryptByPrivateKey(byte[] data, String key)throws Exception {// 对密钥解密byte[] keyBytes = decryptBASE64(key);// 取得私钥PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);// 对数据加密Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());cipher.init(Cipher.ENCRYPT_MODE, privateKey);return cipher.doFinal(data);}/*** 取得私钥* * @param keyMap* @return* @throws Exception*/public static String getPrivateKey(Map<String, Object> keyMap)throws Exception {Key key = (Key) keyMap.get(PRIVATE_KEY);return encryptBASE64(key.getEncoded());}/*** 取得公钥* * @param keyMap* @return* @throws Exception*/public static String getPublicKey(Map<String, Object> keyMap)throws Exception {Key key = (Key) keyMap.get(PUBLIC_KEY);return encryptBASE64(key.getEncoded());}/*** 初始化密钥* * @return* @throws Exception*/public static Map<String, Object> initKey() throws Exception {KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);keyPairGen.initialize(1024);KeyPair keyPair = keyPairGen.generateKeyPair();// 公钥RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();// 私钥RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();Map<String, Object> keyMap = new HashMap<String, Object>(2);keyMap.put(PUBLIC_KEY, publicKey);keyMap.put(PRIVATE_KEY, privateKey);return keyMap;}}

③ JAVA公钥加密,私钥解密,该怎么解决

RSA加密算法,是世界上第一个非对称加密算法,也是数论的第一个实际应用。它的算法如下:
1.找两个非常大的质数p和q(通常p和q都有155十进制位或都有512十进制位)并计算n=pq,k=(p-1)(q-1)。
2.将明文编码成整数M,保证M不小于0但是小于n。
3.任取一个整数e,保证e和k互质,而且e不小于0但是小于k。加密钥匙(称作公钥)是(e, n)。
4.找到一个整数d,使得ed除以k的余数是1(只要e和n满足上面条件,d肯定存在)。解密钥匙(称作密钥)是(d, n)。
加密过程: 加密后的编码C等于M的e次方除以n所得的余数。
解密过程: 解密后的编码N等于C的d次方除以n所得的余数。
只要e、d和n满足上面给定的条件。M等于N。

④ Java 第三方公钥 RSA加密求助

下面是RSA加密代码。

/**
* RSA算法,实现数据的加密解密。
* @author ShaoJiang
*
*/
public class RSAUtil {

private static Cipher cipher;

static{
try {
cipher = Cipher.getInstance("RSA");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
}
}

/**
* 生成密钥对
* @param filePath 生成密钥的路径
* @return
*/
public static Map<String,String> generateKeyPair(String filePath){
try {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
// 密钥位数
keyPairGen.initialize(1024);
// 密钥对
KeyPair keyPair = keyPairGen.generateKeyPair();
// 公钥
PublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
// 私钥
PrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
//得到公钥字符串
String publicKeyString = getKeyString(publicKey);
//得到私钥字符串
String privateKeyString = getKeyString(privateKey);

FileWriter pubfw = new FileWriter(filePath+"/publicKey.keystore");
FileWriter prifw = new FileWriter(filePath+"/privateKey.keystore");
BufferedWriter pubbw = new BufferedWriter(pubfw);
BufferedWriter pribw = new BufferedWriter(prifw);
pubbw.write(publicKeyString);
pribw.write(privateKeyString);
pubbw.flush();
pubbw.close();
pubfw.close();
pribw.flush();
pribw.close();
prifw.close();
//将生成的密钥对返回
Map<String,String> map = new HashMap<String,String>();
map.put("publicKey",publicKeyString);
map.put("privateKey",privateKeyString);
return map;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

/**
* 得到公钥
*
* @param key
* 密钥字符串(经过base64编码)
* @throws Exception
*/
public static PublicKey getPublicKey(String key) throws Exception {
byte[] keyBytes;
keyBytes = (new BASE64Decoder()).decodeBuffer(key);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(keySpec);
return publicKey;
}

/**
* 得到私钥
*
* @param key
* 密钥字符串(经过base64编码)
* @throws Exception
*/
public static PrivateKey getPrivateKey(String key) throws Exception {
byte[] keyBytes;
keyBytes = (new BASE64Decoder()).decodeBuffer(key);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
return privateKey;
}

/**
* 得到密钥字符串(经过base64编码)
*
* @return
*/
public static String getKeyString(Key key) throws Exception {
byte[] keyBytes = key.getEncoded();
String s = (new BASE64Encoder()).encode(keyBytes);
return s;
}

/**
* 使用公钥对明文进行加密,返回BASE64编码的字符串
* @param publicKey
* @param plainText
* @return
*/
public static String encrypt(PublicKey publicKey,String plainText){
try {
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] enBytes = cipher.doFinal(plainText.getBytes());
return (new BASE64Encoder()).encode(enBytes);
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}

/**
* 使用keystore对明文进行加密
* @param publicKeystore 公钥文件路径
* @param plainText 明文
* @return
*/
public static String encrypt(String publicKeystore,String plainText){
try {
FileReader fr = new FileReader(publicKeystore);
BufferedReader br = new BufferedReader(fr);
String publicKeyString="";
String str;
while((str=br.readLine())!=null){
publicKeyString+=str;
}
br.close();
fr.close();
cipher.init(Cipher.ENCRYPT_MODE,getPublicKey(publicKeyString));
byte[] enBytes = cipher.doFinal(plainText.getBytes());
return (new BASE64Encoder()).encode(enBytes);
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

/**
* 使用私钥对明文密文进行解密
* @param privateKey
* @param enStr
* @return
*/
public static String decrypt(PrivateKey privateKey,String enStr){
try {
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] deBytes = cipher.doFinal((new BASE64Decoder()).decodeBuffer(enStr));
return new String(deBytes);
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}

/**
* 使用keystore对密文进行解密
* @param privateKeystore 私钥路径
* @param enStr 密文
* @return
*/
public static String decrypt(String privateKeystore,String enStr){
try {
FileReader fr = new FileReader(privateKeystore);
BufferedReader br = new BufferedReader(fr);
String privateKeyString="";
String str;
while((str=br.readLine())!=null){
privateKeyString+=str;
}
br.close();
fr.close();
cipher.init(Cipher.DECRYPT_MODE, getPrivateKey(privateKeyString));
byte[] deBytes = cipher.doFinal((new BASE64Decoder()).decodeBuffer(enStr));
return new String(deBytes);
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}

⑤ JAVA公钥加密,私钥解密,该怎么解决

public abstract class RSACoder extends Coder {public static final String KEY_ALGORITHM = "RSA";public static final String SIGNATURE_ALGORITHM = "MD5withRSA";private static final String PUBLIC_KEY = "RSAPublicKey";private static final String PRIVATE_KEY = "RSAPrivateKey";/*** 用私钥对信息生成数字签名* * @param data* 加密数据* @param privateKey* 私钥* * @return* @throws Exception*/public static String sign(byte[] data, String privateKey) throws Exception {// 解密由base64编码的私钥byte[] keyBytes = decryptBASE64(privateKey);// 构造PKCS8EncodedKeySpec对象PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);// KEY_ALGORITHM 指定的加密算法KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);// 取私钥匙对象PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec);// 用私钥对信息生成数字签名Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);signature.initSign(priKey);signature.update(data);return encryptBASE64(signature.sign());}/*** 校验数字签名* * @param data* 加密数据* @param publicKey* 公钥* @param sign* 数字签名* * @return 校验成功返回true 失败返回false* @throws Exception* */public static boolean verify(byte[] data, String publicKey, String sign)throws Exception {// 解密由base64编码的公钥byte[] keyBytes = decryptBASE64(publicKey);// 构造X509EncodedKeySpec对象X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);// KEY_ALGORITHM 指定的加密算法KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);// 取公钥匙对象PublicKey pubKey = keyFactory.generatePublic(keySpec);Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);signature.initVerify(pubKey);signature.update(data);// 验证签名是否正常return signature.verify(decryptBASE64(sign));}/*** 解密<br>* 用私钥解密* * @param data* @param key* @return* @throws Exception*/public static byte[] decryptByPrivateKey(byte[] data, String key)throws Exception {// 对密钥解密byte[] keyBytes = decryptBASE64(key);// 取得私钥PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);// 对数据解密Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());cipher.init(Cipher.DECRYPT_MODE, privateKey);return cipher.doFinal(data);}/*** 解密<br>* 用公钥解密* * @param data* @param key* @return* @throws Exception*/public static byte[] decryptByPublicKey(byte[] data, String key)throws Exception {// 对密钥解密byte[] keyBytes = decryptBASE64(key);// 取得公钥X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);Key publicKey = keyFactory.generatePublic(x509KeySpec);// 对数据解密Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());cipher.init(Cipher.DECRYPT_MODE, publicKey);return cipher.doFinal(data);}/*** 加密<br>* 用公钥加密* * @param data* @param key* @return* @throws Exception*/public static byte[] encryptByPublicKey(byte[] data, String key)throws Exception {// 对公钥解密byte[] keyBytes = decryptBASE64(key);// 取得公钥X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);Key publicKey = keyFactory.generatePublic(x509KeySpec);// 对数据加密Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());cipher.init(Cipher.ENCRYPT_MODE, publicKey);return cipher.doFinal(data);}/*** 加密<br>* 用私钥加密* * @param data* @param key* @return* @throws Exception*/public static byte[] encryptByPrivateKey(byte[] data, String key)throws Exception {// 对密钥解密byte[] keyBytes = decryptBASE64(key);// 取得私钥PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);// 对数据加密Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());cipher.init(Cipher.ENCRYPT_MODE, privateKey);return cipher.doFinal(data);}/*** 取得私钥* * @param keyMap* @return* @throws Exception*/public static String getPrivateKey(Map<String, Object> keyMap)throws Exception {Key key = (Key) keyMap.get(PRIVATE_KEY);return encryptBASE64(key.getEncoded());}/*** 取得公钥* * @param keyMap* @return* @throws Exception*/public static String getPublicKey(Map<String, Object> keyMap)throws Exception {Key key = (Key) keyMap.get(PUBLIC_KEY);return encryptBASE64(key.getEncoded());}/*** 初始化密钥* * @return* @throws Exception*/public static Map<String, Object> initKey() throws Exception {KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);keyPairGen.initialize(1024);KeyPair keyPair = keyPairGen.generateKeyPair();// 公钥RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();// 私钥RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();Map<String, Object> keyMap = new HashMap<String, Object>(2);keyMap.put(PUBLIC_KEY, publicKey);keyMap.put(PRIVATE_KEY, privateKey);return keyMap;}}

⑥ JAVA公钥加密,私钥解密,该怎么解决

可以使用Java中的RSA加解密,公私钥就是非对称的,公钥加密,私钥解密。也可以使用硬件加密锁,一般都支持RSA等加密算法,比如ROCKEY。

⑦ 新的java程序公钥加密算法有哪些

AES和RSA都是加密算法 AES属于对称加密算法 RSA属于非对称加密算法,公钥和私钥不一致 MD5是一种校验方式,用于保证文件的正确性,防止被植入木马或病毒

⑧ JAVA公钥加密,私钥解密,该怎么解决

1、默认 Java 中仅支持 128 位密钥,当使用 256 位密钥的时候,会报告密钥长度错误 Invalid AES key length 你需要下载一个支持更长密钥的包。这个包叫做 Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files 6 看一下你的 JRE 环境,将 JRE 环境中 lib\lib\security 中的同名包替换掉。
2、Base64 问题 // 编码 String asB64 = new Base64().encodeToString("some string".getBytes("utf-8")); System.out.println(asB64); // 输出为: c29tZSBzdHJpbmc= 解码 // 解码 byte[] asBytes = new Base64().getDecoder().decode("c29tZSBzdHJpbmc="); System.out.println(new String(asBytes, "utf-8")); // 输出为: some string ...

⑨ JAVA公钥加密,私钥解密,该怎么解决

RSA算法,选取两个互质数
如p:6和q:5(最大公约数为1)
求出乘积n=30,欧拉函数值((p - 1) * (q - 1)) eul =20
选出一个和eul互质且小于eul大于1的数,如 e = 19
通过扩展欧几里得算法求逆元 此处求出一个逆元 d = 39
逆元就是满足公式 (e*d) % eul = 1的值(该公式可能有多个解,求出一个就行)
(n,e)组成公钥,(n,d)组成私钥
假定明文是一个数字m
计算 m的e次方模n 得到的余数就是密文 em
计算 em的d次方模n 得到的余数就是明文 m
因此可以使用公钥加密byte数组,使用私钥解密还原byte数组
byte数组组成了字符串、文件等
最后注意,要加密的明文二进制位数不能超过密钥的二进制位数

⑩ JAVA公钥加密,私钥解密,该怎么解决

public String encryptStringWithRSA(RSAPublicKey publicKey,
String str)
{
String key;
try
{
key =
encode(publicKey.getEncoded());
byte[] keyBytes =
decode(key);
X509EncodedKeySpec x509KeySpec = new
X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory =
KeyFactory.getInstance(RSA);
Key publicK =
keyFactory.generatePublic(x509KeySpec);
// 对数据加密
Cipher cipher =
Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE,
publicK);
byte[] data = str.getBytes();
int inputLen =
data.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int
offSet = 0;
byte[] cache;
int i = 0;
// 对数据分段加密
while (inputLen -
offSet > 0)
{
if (inputLen - offSet >
MAX_ENCRYPT_BLOCK)
{
cache = cipher.doFinal(data, offSet,
MAX_ENCRYPT_BLOCK);
} else
{
cache = cipher.doFinal(data, offSet,
inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet
= i * MAX_ENCRYPT_BLOCK;
}
byte[] encryptedData =
out.toByteArray();
out.close();
return
parseByte2HexStr(encryptedData);
} catch (Exception
e)
{
e.printStackTrace();
}
return ERROR;

}

public
String decryptStringWithRSA(RSAPrivateKey privateKey, String str)
{
if
(!str.equals(""))
{
String key;
try
{
key =
encode(privateKey.getEncoded());
byte[] keyBytes =
decode(key);
PKCS8EncodedKeySpec pkcs8KeySpec = new
PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory =
KeyFactory.getInstance(RSA);
Key privateK =
keyFactory.generatePrivate(pkcs8KeySpec);
Cipher cipher =
Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE,
privateK);
byte[] encryptedData = parseHexStr2Byte(str);
int inputLen =
encryptedData.length;
ByteArrayOutputStream out = new
ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
//
对数据分段解密
while (inputLen - offSet > 0)
{
if (inputLen - offSet >
MAX_DECRYPT_BLOCK)
{
cache = cipher.doFinal(encryptedData, offSet,
MAX_DECRYPT_BLOCK);
} else
{
cache = cipher.doFinal(encryptedData,
offSet, inputLen - offSet);
}
out.write(cache, 0,
cache.length);
i++;
offSet = i * MAX_DECRYPT_BLOCK;
}
byte[]
decryptedData = out.toByteArray();
out.close();
return new
String(decryptedData);
} catch (Exception
e)
{
e.printStackTrace();
}

} else
{
return
str;
}
return ERROR;

}收起

热点内容
x2哪个配置性价比高 发布:2025-02-06 00:40:12 浏览:109
猪哥亮访问张菲 发布:2025-02-06 00:37:52 浏览:570
期货账户怎么改密码 发布:2025-02-06 00:32:35 浏览:279
qq自动上传群文件 发布:2025-02-06 00:26:25 浏览:110
安卓照片放在什么地方 发布:2025-02-06 00:26:24 浏览:988
linux系统镜像iso 发布:2025-02-06 00:15:39 浏览:188
存储上料模块的意义 发布:2025-02-06 00:14:14 浏览:125
unix时间戳转换php 发布:2025-02-06 00:13:27 浏览:404
我的世界网易电脑板好玩的枪械rpg服务器 发布:2025-02-06 00:08:04 浏览:346
非挥发性记忆体永久性存储器 发布:2025-02-06 00:07:17 浏览:267