我正在爲Android中的RSA加密和解密實施演示。我可以很好地執行加密,但在解密中,我得到一個例外:>>java.security.InvalidKeyException: unknown key type passed to RSA
。Android中的RSA加密解密
KeyPairGenerator kpg;
KeyPair kp;
PublicKey publicKey;
PrivateKey privateKey;
byte [] encryptedBytes,decryptedBytes;
Cipher cipher,cipher1;
String encrypted,decrypted;
public String RSAEncrypt (final String plain) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException
{
kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(1024);
kp = kpg.genKeyPair();
publicKey = kp.getPublic();
privateKey = kp.getPrivate();
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
encryptedBytes = cipher.doFinal(plain.getBytes());
encrypted = new String(encryptedBytes);
System.out.println("EEncrypted?????"+encrypted);
return encrypted;
}
public String RSADecrypt (final String result) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException
{
cipher1=Cipher.getInstance("RSA");
cipher1.init(Cipher.DECRYPT_MODE, privateKey);
decryptedBytes = cipher1.doFinal(result.getBytes());
decrypted = new String(decryptedBytes);
System.out.println("DDecrypted?????"+decrypted);
return decrypted;
}
而且我從這裏調用該函數:
encrypt.setOnClickListener(new OnClickListener()
{
public void onClick(View arg0)
{
try
{
RSAEncrypt rsaencrypt=new RSAEncrypt();
rsaencrypt.RSAEncrypt(name);
result=rsaencrypt.RSAEncrypt(name);
Toast.makeText(getBaseContext(), result.toString(),Toast.LENGTH_SHORT).show();
System.out.println("Result:"+result);
}
catch(Exception e)
{
e.printStackTrace();
Toast.makeText(getBaseContext(), e.toString(),Toast.LENGTH_LONG).show();
}
}
});
decrypt.setOnClickListener(new OnClickListener()
{
public void onClick(View arg0)
{
{
try
{
RSAEncrypt rsadecrypt=new RSAEncrypt();
rsadecrypt.RSADecrypt(result);
ans=rsadecrypt.RSADecrypt(result);
System.out.println("Result is"+ans);
Toast.makeText(getBaseContext(), ans.toString(),Toast.LENGTH_LONG).show();
}
catch(Exception e)
{
e.printStackTrace();
Toast.makeText(getBaseContext(), e.toString(),Toast.LENGTH_LONG).show();
System.out.println("Exception is>>"+e);
}
}
});
非常感謝。你是對的..我做了錯誤在那..但現在我得到異常>> System.err(416):java.security.InvalidKeyException:未知的關鍵類型傳遞給RSA 請幫助我..謝謝提前.. –
查看我的更新回答 – Robert
感謝您的。只是一個評論:鍵是對稱的。因此,您可以使用public進行編碼,然後使用private進行解碼(確保向誰發送加密數據),或者使用private進行編碼,然後使用public進行解碼(以確保誰向您發送了加密數據)。做2(用2個不同的密鑰集),允許你執行'從誰'和'誰'安全方面。 – Pascal