Ci sono un sacco di domande su questo argomento, la stessa soluzione, ma questo non funziona per me. Ho un semplice test con una crittografia. La crittografia/decodifica stessa funziona (finché gestisco questo test con l'array di byte stesso e non come Strings). Il problema è che non voglio gestirlo come array di byte ma come String, ma quando codifico l'array di byte in stringa e back, l'array di byte risultante differisce dall'array di byte originale, quindi la decrittografia non funziona più. Ho provato i seguenti parametri nei metodi stringa corrispondenti: UTF-8, UTF8, UTF-16, UTF8. Nessuno di loro funziona. La matrice di byte risultante differisce dall'originale. Qualche idea per cui è così?Problemi di conversione dell'array di byte in stringa e ritorno all'array di byte
Encrypter:
public class NewEncrypter
{
private String algorithm = "DESede";
private Key key = null;
private Cipher cipher = null;
public NewEncrypter() throws NoSuchAlgorithmException, NoSuchPaddingException
{
key = KeyGenerator.getInstance(algorithm).generateKey();
cipher = Cipher.getInstance(algorithm);
}
public byte[] encrypt(String input) throws Exception
{
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] inputBytes = input.getBytes("UTF-16");
return cipher.doFinal(inputBytes);
}
public String decrypt(byte[] encryptionBytes) throws Exception
{
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] recoveredBytes = cipher.doFinal(encryptionBytes);
String recovered = new String(recoveredBytes, "UTF-16");
return recovered;
}
}
Questa è la prova in cui ho provato:
public class NewEncrypterTest
{
@Test
public void canEncryptAndDecrypt() throws Exception
{
String toEncrypt = "FOOBAR";
NewEncrypter encrypter = new NewEncrypter();
byte[] encryptedByteArray = encrypter.encrypt(toEncrypt);
System.out.println("encryptedByteArray:" + encryptedByteArray);
String decoded = new String(encryptedByteArray, "UTF-16");
System.out.println("decoded:" + decoded);
byte[] encoded = decoded.getBytes("UTF-16");
System.out.println("encoded:" + encoded);
String decryptedText = encrypter.decrypt(encoded); //Exception here
System.out.println("decryptedText:" + decryptedText);
assertEquals(toEncrypt, decryptedText);
}
}
Prima è necessario convertire i byte in qualcosa che può essere presentato come una stringa. Di solito convertendo in hex o base64. –
Qual è la differenza effettiva che si vede negli array di byte prima e dopo la conversione in una stringa? – Herms
@Roger Lindsjö: grazie per il tipp. Lo proverò immediatamente. – Bevor