我正在尝试使用 RSA 算法加密和解密字符串。这里加密工作良好,但问题在于解密。代码在 DECRYPT 方法中到达 doFinal 时终止。我输入错误还是公钥和私钥有问题?请给我有关此的建议。感谢你。
public class rsa
{
private KeyPair keypair;
public rsa() throws NoSuchAlgorithmException, NoSuchProviderException
{
KeyPairGenerator keygenerator = KeyPairGenerator.getInstance("RSA");
SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
keygenerator.initialize(1024, random);
keypair = keygenerator.generateKeyPair();
}
public String ENCRYPT(String Algorithm, String Data ) throws Exception
{
String alg = Algorithm;
String data=Data;
byte[] encrypted=new byte[2048];
if(alg.equals("RSA"))
{
PublicKey publicKey = keypair.getPublic();
Cipher cipher;
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
encrypted = cipher.doFinal(data.getBytes());
System.out.println("Encrypted String[RSA] -> " + encrypted);
}
return encrypted.toString();
}
public String DECRYPT(String Algorithm, String Data ) throws Exception
{
String alg = Algorithm;
byte[] Decrypted=Data.getBytes();
if(alg.equals("RSA"))
{
PrivateKey privateKey = keypair.getPrivate();
Cipher cipher;
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] dec = cipher.doFinal(Decrypted);
System.out.println("Decrypted String[RSA] -> " + dec.toString());
}
return Decrypted.toString();
}
public static void main(String[] args) throws Exception
{
rsa RSA=new rsa();
RSA.ENCRYPT("RSA", "avinash");
RSA.DECRYPT("RSA","[B@cb7e2c");
}
}
got exception as
Exception in thread "main" javax.crypto.BadPaddingException: Data must start with zero
at sun.security.rsa.RSAPadding.unpadV15(Unknown Source)
at sun.security.rsa.RSAPadding.unpad(Unknown Source)
at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:356)
at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:382)
at javax.crypto.Cipher.doFinal(Cipher.java:2086)
at EncryptionProvider.rsa.DECRYPT(rsa.java:56)
at EncryptionProvider.rsa.main(rsa.java:68)
加密字符串[RSA] -> [B@4a96a