I am using the below code
public byte[] encrypt(byte[] unencryptedString,String k)throws Exception {
String encryptedString = null;
String k1 = String.format("%024d", Integer.parseInt(k));
myEncryptionKey = k1;
myEncryptionScheme = DESEDE_ENCRYPTION_SCHEME;
arrayBytes = myEncryptionKey.getBytes(UNICODE_FORMAT);
ks = new DESedeKeySpec(arrayBytes);
skf = SecretKeyFactory.getInstance(myEncryptionScheme);
cipher = Cipher.getInstance(myEncryptionScheme);
key = skf.generateSecret(ks);
try {
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] plainText =
unencryptedString/*.getBytes(UNICODE_FORMAT)*/;
byte[] encryptedText = cipher.doFinal(plainText);
// encryptedString = new String(Base64.encodeBase64(encryptedText));
} catch (Exception e) {
e.printStackTrace();
}
return encryptedText;
}
The return statement gives the following error:
encryptedText cannot be resolved to a variable
Contrary to the other answers, I wouldn't change your code to return null
if you fail to encrypt the text - I would let that failure bubble up as an exception. I wouldn't declare that your method can throw Exception
either - I'd specify which exceptions it can throw. You could do this at a very fine-grained level, or in this case use GeneralSecurityException
which covers all the crypto-specific exceptions you're interested in.
I'd further stop using fields unnecessarily - you don't need to change any state here.
After all this refactoring, your method would become:
public static byte[] encrypt(String unencryptedString, String k)
throws GeneralSecurityException {
String keySpecText = String.format("%024d", Integer.parseInt(k));
byte[] keySpecBytes = keySpecText.getBytes(StandardCharsets.UTF_16);
KeySpec ks = new DESedeKeySpec(keySpecBytes);
SecretKeyFactory skf = SecretKeyFactory.getInstance(DESEDE_ENCRYPTION_SCHEME);
Key key = skf.generateSecret(ks);
Cipher cipher = Cipher.getInstance(DESEDE_ENCRYPTION_SCHEME);
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] plainText = unencryptedString.getBytes(StandardCharsets.UTF_16);
return cipher.doFinal(plainText);
}
I'm not at all sure that this is a good way of providing a key - you're limited to 232 keys here, which isn't great, and even if you're happy with that, why take a string for the key instead of an int
? But at least the code compiles, and when it fails it will properly fail.
See more on this question at Stackoverflow