YellowMoon
Lurker
I'm trying to encrypt a text with DES algorithm using Bouncy Castle library. I have written the following code:
The code is supposed to work as follows: The following part of the code will generate "keySpec" and "Cipher" which is used in both encryption and decryption parts in the switch statement.
Then depending on the user selection, inputText is encrypted or encText is decrypted in the switch statement. Both encryption and decryption blocks share the same "keySpec" and "Cipher" variables generated in the above code snippet. However, the compiler says that keySpec and Cipher cannot be resolved which I understand is that the keySpec and Cipher generated cannot be seen by the statements inside the switch blocks. How can I make it work?
Cheers,
Code:
try{
KeyGenerator kg=KeyGenerator.getInstance("DES");
SecretKey key=kg.generateKey();
SecretKeySpec keySpec = new SecretKeySpec(key.getEncoded(), "DES");
Cipher cipher=Cipher.getInstance("DES");
}catch(Exception e)
{
}
switch(selection){
case enc:
try{
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
String inText=inputText.toString();
byte[] cipherText=cipher.doFinal(inText.getBytes());
encText.setText(new String(cipherText));
}catch(Exception e)
{
encText.setText("Exception occured!");
}
break;
case dec:
try{
cipher.init(Cipher.DECRYPT_MODE, keySpec);
String encT=encText.toString();
byte[] decBytes=cipher.doFinal(encT.getBytes());
decText.setText(new String(decBytes));
}catch(Exception e)
{
decText.setText("Exception occured!");
}
break;
}
}
The code is supposed to work as follows: The following part of the code will generate "keySpec" and "Cipher" which is used in both encryption and decryption parts in the switch statement.
Code:
try{
KeyGenerator kg=KeyGenerator.getInstance("DES");
SecretKey key=kg.generateKey();
SecretKeySpec keySpec = new SecretKeySpec(key.getEncoded(), "DES");
Cipher cipher=Cipher.getInstance("DES");
}catch(Exception e)
{
Then depending on the user selection, inputText is encrypted or encText is decrypted in the switch statement. Both encryption and decryption blocks share the same "keySpec" and "Cipher" variables generated in the above code snippet. However, the compiler says that keySpec and Cipher cannot be resolved which I understand is that the keySpec and Cipher generated cannot be seen by the statements inside the switch blocks. How can I make it work?
Cheers,
