Ciao a tutti e spero tanto che mi possiate aiutare.
Sto realizzando una classe che faccia l'encrypt e la decrypt di una stringa passata in input con una chiave anche esse passata in input già in mio possesso (quindi non devo crearla o autogenerarla), con algoritmo TRIPLE-DES.
Ma sto avendo un pò di problemi.
Quando chiamo il metodo encrypt passandogli la stringa "ad esempio" mi codifica tale stringa, se faccio il passaggio inverso invece non ottengo lo stesso risultato di partenza.
Questa è la classe che fa l'encrypt/decrypt:
Il main che lancia ciò è fatto così:codice:import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; import javax.crypto.SecretKey; public class Decrypt{ static final int BLOCKSIZE = 8; static final char PADDINGCHAR = ' '; static final String TRIPLE_DES = "DESede/ECB/NoPadding"; protected SecretKey key; public Decrypt(String keycode) { try { byte[] keyBytes = keycode.getBytes(); key = new SecretKeySpec(keyBytes, "DESede"); } catch (Exception e) { e.printStackTrace(); System.exit(0); } } public String decrypt(String encryptText) throws Exception { String codec = ""; String b64cipher; char dateControllor; int i=0; try { b64cipher = encryptText; codec = new String(cipher(b64cipher.getBytes(), Cipher.DECRYPT_MODE),"ISO-8859-1").trim(); return codec; } catch (Exception e) { e.printStackTrace(); throw e; } } public String encrypt(String plainText) throws Exception { int remainder = plainText.length() % BLOCKSIZE; if (remainder != 0) { int count = BLOCKSIZE - remainder; for (int i = 0; i < count; i++) { plainText += PADDINGCHAR; } } byte[] text = plainText.getBytes(); String ritorno = new String(cipher(text, Cipher.ENCRYPT_MODE),"ISO-8859-1"); return ritorno; } private byte[] cipher(byte[] text, int mode) throws Exception { try { byte[] cipherText; Cipher aCipher = Cipher.getInstance(TRIPLE_DES); aCipher.init(mode, key); cipherText = aCipher.update(text); return cipherText; } catch (Exception e) { e.printStackTrace(); throw e; } } }
E' corretto come sono state implementate le cose? In cosa sbaglio?codice:Decrypt dec = new Decrypt("CHIAVE DI 24 CARATTERI"); String daCod = "Prova Prova Prova"; String encr = dec.encrypt(daCod); System.out.println("\nCodifica = " + encr); String dd = dec.decrypt(encr); System.out.println("\nDecodifica = " + dd);
Grazie e spero tanto in una vostra risposta.

Rispondi quotando
