我搜索了很多,但我找不到答案。
这是我的加密类,它包含两个方法Encrypt()和Decrypt():
public class EncryptionClass {
public static SecretKey mainKey=null;
public static SecretKey GenerateKey() throws NoSuchAlgorithmException
{
KeyGenerator keygenerator = KeyGenerator.getInstance("DES");
SecretKey myDesKey = keygenerator.generateKey();
return myDesKey;
}
public static String Encrypt(String plainText) {
String encryptedText = "";
try {
mainKey=GenerateKey();
Cipher desCipher;
// Create the cipher
desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
// Initialize the cipher for encryption
desCipher.init(Cipher.ENCRYPT_MODE,mainKey);
//sensitive information
byte[] plainTextAsBytes =plainText.getBytes();
Log.d("Text [Byte Format] : " , plainTextAsBytes.toString());
Log.d("Text : " ,new String(plainTextAsBytes));
// Encrypt the text
byte[] cipherText = desCipher.doFinal(plainTextAsBytes);
Log.d("Text Encryted : " ,cipherText.toString());
encryptedText=cipherText.toString();
}catch(NoSuchAlgorithmException e){
Log.d("NoSuchAlgorithmException :", e.toString());
}catch(NoSuchPaddingException e){
Log.d("NoSuchPaddingException :", e.toString());
}catch(InvalidKeyException e){
Log.d("InvalidKeyException:", e.toString());
}catch(IllegalBlockSizeException e){
Log.d("IllegalBlockSizeException:", e.toString());
}catch(BadPaddingException e){
Log.d("BadPaddingException:", e.toString());
}
finally{
}
return encryptedText;
}
public static String Decrypt(String cipherText) {
String decryptedText = "";
try {
Log.d("Decrypt MAin Key:",mainKey.getEncoded().toString());
Cipher desCipher;
// Create the cipher
desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
// Initialize the cipher for encryption
desCipher.init(Cipher.DECRYPT_MODE,mainKey);
// Encrypt the text
byte[] cipherTextBytes=cipherText.getBytes();
byte[] plainText= desCipher.doFinal(cipherTextBytes);
Log.d("Text Decryted : " ,plainText.toString());
decryptedText=plainText.toString();
}catch(NoSuchAlgorithmException e){
Log.d("NoSuchAlgorithmException :", e.toString());
}catch(NoSuchPaddingException e){
Log.d("NoSuchPaddingException :", e.toString());
}catch(InvalidKeyException e){
Log.d("InvalidKeyException:", e.toString());
}catch(IllegalBlockSizeException e){
Log.d("IllegalBlockSizeException:", e.toString());
}catch(BadPaddingException e){
Log.d("BadPaddingException:", e.toString());
}
finally{
}
return decryptedText;
}
}
这是我调用方法的主要活动:
public void onClick(View arg0) {
String ct=EncryptionClass.Encrypt("the text to encrypt");
Log.d("Cipher Text", ct);
String pt=EncryptionClass.Decrypt(ct);
Log.d("Plain Text", pt);
}
任何帮助都非常感激。 最诚挚的问候,
答案 0 :(得分:1)
cipherText.toString()
将无法正常工作,因为字节数组可以包含任意字节。其中一些将在转换中丢失或损坏,并且无法解密生成的密文。
保持byte[]
并使用它来提供解密,或将字节转换为Base64。
答案 1 :(得分:0)