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

2025-05-17 04:11:42
推荐回答(1个)
回答(1):

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;

}收起