Sorry for my bad english
I'm having problems when decrypting a String
the result of decryption process is something like corrupt, even if I pass the string Base64 encoded: this is the code i used:
public class StringCipher {
private byte[] input;
private byte[] keyBytes = new byte[] { 0x01, 0x23, 0x45, 0x67, (byte) 0x89, (byte) 0xab, (byte) 0xcd,
(byte) 0xef };
private byte[] ivBytes = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x00, 0x00, 0x00, 0x01 };
private SecretKeySpec key = new SecretKeySpec(keyBytes, "DES");
private IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
private Cipher cipher;
public StringCipher(){
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
try {
cipher = Cipher.getInstance("DES/CTR/NoPadding", "BC");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
}
}
public String getEncryptedString(String inputString) throws ShortBufferException, IllegalBlockSizeException, BadPaddingException{
try {
cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
e.printStackTrace();
}
this.input = inputString.getBytes();
byte[] cipherText = new byte[cipher.getOutputSize(input.length)];
int ctLength = cipher.update(input, 0, input.length, cipherText, 0);
ctLength += cipher.doFinal(cipherText, ctLength);
return (new String(Base64.encodeBytes(cipherText,Base64.ENCODE)));
}
public String getDecrypedString(String inputString) throws Exception{
this.input = Base64.decode(inputString,Base64.DECODE);
cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
byte[] plainText = new byte[cipher.getOutputSize(input.length)];
int ptLength = cipher.update(input, 0, input.length, plainText, 0);
ptLength += cipher.doFinal(plainText, ptLength);
String aux = Base64.encodeBytes(plainText,Base64.ENCODE);
System.out.println(aux);
return (new String (plainText));
}
}
when I call getEncryptedString("helloWorld") I get "CcWW6ZTJrny5WgAAAAAAAA=="
So, if I ship "CcWW6ZTJrny5WgAAAAAAAA==" in base64 an encrypted to getDecrypedString, I obtain "helloWorld���7�`"
Does anybody Can help me?