Questo sito utilizza cookies solo per scopi di autenticazione sul sito e nient'altro. Nessuna informazione personale viene tracciata. Leggi l'informativa sui cookies.
Username: Password: oppure
Java - cifratura PBE
Forum - Java - cifratura PBE

Avatar
anerol82 (Normal User)
Newbie


Messaggi: 4
Iscritto: 16/04/2007

Segnala al moderatore
Postato alle 16:41
Venerdì, 27/04/2007
Sto scrivendo un'applicazione client server dove un client invia il suo nome, il server lo riceve poi estrae una informazione legata al client utilizza una password la invia al client il client la decifra e poi dovrebbe visualizzare la stringa corretta...ho usato PBE...ma mi da l'errore " PARAMETRO NON CORRETTO" lato client...quindi suppongo che lato server la cifratura avvenga correttamente...qualcuno può aiutarmi?? Devo usare qualche codifica??

La password che uso sia per decifrare che codificare è una stringa del tipo "240982"
mentre la stringa da codificare è del tipo "negativo"(in realtà sarebbe una stringa "12.4" quale potrebbe essere l'errore? La classe dove ho implementato le operazioni è questa:

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.security.spec.*;

import javax.crypto.*;
import javax.crypto.spec.*;
import java.util.*;

public class Cryptex{
    

    private static final int ITERATIONS = 1000;


    public static String encrypt(char[] password, String plaintext) {

        Random random = new Random();
        byte[] salt = new byte[8];
        random.nextBytes(salt);
      
        PBEKeySpec keySpec = new PBEKeySpec(password);
        try{
        SecretKeyFactory keyFactory =SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        SecretKey key = keyFactory.generateSecret(keySpec);
        PBEParameterSpec paramSpec =new PBEParameterSpec(salt, ITERATIONS);
        Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");
        cipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
        byte[] ciphertext = cipher.doFinal(plaintext.getBytes("UTF8"));
        return new String(salt) + new String(ciphertext);
        }
        catch (NoSuchAlgorithmException e1) {        
            System.out.println("Algoritmo non supportato");    
        }
        
  
        catch (NoSuchPaddingException e2) {        
            System.out.println("Padding non supportato");    
        }
        
        catch (InvalidKeySpecException e3) {
            System.out.println("Specificazione della chiave non valida");    
        }
        
        catch (InvalidKeyException e4) {
            System.out.println("Chiave non valida");
        }
        
        catch (InvalidAlgorithmParameterException e5) {
            System.out.println("Parametro non valido");
        }
        
        catch (IllegalBlockSizeException e6) {
            System.out.println("Dimensione blocco illegale");
        }
        
        catch (BadPaddingException e7) {
            System.out.println("Bad Padding");
        }
        catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }     
        return "Error";
    }
    
    public static String decrypt(char[] password, String input) {
        
        try{
    
        byte[] salt = input.substring(0,8).getBytes("UTF8");
        byte[] ciphertext = input.substring( 8 ).getBytes("UTF8");
        PBEKeySpec keySpec = new PBEKeySpec(password);
        SecretKeyFactory keyFactory =
        SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        SecretKey key = keyFactory.generateSecret(keySpec);
        PBEParameterSpec paramSpec =
        new PBEParameterSpec(salt, ITERATIONS);
        Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");
        cipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
        byte[] plaintextArray = cipher.doFinal(ciphertext);
        return new String(plaintextArray );
        }    catch (NoSuchAlgorithmException e1) {        
            System.out.println("Algoritmo non supportato");
        }
        
        catch (NoSuchPaddingException e2) {        
            System.out.println("Padding non supportato");    
        }
        
        catch (InvalidKeySpecException e3) {
            System.out.println("Specificazione della chiave non valida");
        }
        
        catch (InvalidKeyException e4) {
            System.out.println("Chiave non valida");
        }
        
        catch (InvalidAlgorithmParameterException e5) {
            System.out.println("Parametro non valido");
        }
        
        catch (IllegalBlockSizeException e6) {
            System.out.println("Dimensione blocco illegale");
        }
        
        catch (BadPaddingException e7) {
            System.out.println("Bad Padding");
        }
        
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "Decifratura Fallita";
    }
    
    }

mentre quando utilizzo lato client il metodo per la decifratura uso:

....
     // ricezione esito
        String esito,risultato;
        String pwd= null;
        System.out.println("INSERIRE PASSWORD = "+"/n");
        
        try{
          
            while ( (pwd=stdIn.readLine()) != null){              
                
                try{
            
        
          esito = inSock.readUTF();
          risultato=Cryptex.decrypt(pwd.toCharArray(),esito);
          System.out.println("Esito esame: " + risultato);
          // chiudo la socket in downstream
          socket.shutdownInput();
          System.out.println("Terminata la chiusura della socket: " + socket);
        }
....
...

Qual è l'errore???? grazie in anticipo

PM Quote
Avatar
netarrow (Admin)
Guru^2


Messaggi: 2502
Iscritto: 12/05/2004

Segnala al moderatore
Postato alle 11:51
Domenica, 29/04/2007
Devi convertire a base64 per evitare di perdere bit per strada ;-)

Ah, usando base64 8 bytes diventano 12 caratteri

Questo è il mio output:

J+yyP0CmYGs=ahYDYJ2DI66ngmGuCPfmnLR7apaf/xnpxNP8r+8lk+RnmCPCTCE/Oeu4qLnrpG/P
quelsiasi testo quelsiasi testo qualsiasi testo

Versione corretta:

Codice sorgente - presumibilmente Java

  1. import java.io.IOException;
  2. import java.io.UnsupportedEncodingException;
  3. import java.security.*;
  4. import java.security.spec.*;
  5.  
  6. import javax.crypto.*;
  7. import javax.crypto.spec.*;
  8. import java.util.*;
  9.  
  10. import sun.misc.*;
  11.  
  12. public class Cryptex {
  13.  
  14.  
  15. private static final int ITERATIONS = 1000;
  16.  
  17. public static void main(String args[]) {
  18. String test = encrypt("password".toCharArray(), "quelsiasi testo quelsiasi testo qualsiasi testo");
  19. System.out.println(test);
  20. System.out.println(decrypt("password".toCharArray(), test));
  21. }
  22.  
  23. public static String encrypt(char[] password, String plaintext) {
  24.  
  25. Random random = new Random();
  26. byte[] salt = new byte[8];
  27. random.nextBytes(salt);
  28.  
  29. PBEKeySpec keySpec = new PBEKeySpec(password);
  30. try{
  31. BASE64Encoder encoder = new BASE64Encoder();
  32. SecretKeyFactory keyFactory =SecretKeyFactory.getInstance("PBEWithMD5AndDES");
  33. SecretKey key = keyFactory.generateSecret(keySpec);
  34. PBEParameterSpec paramSpec =new PBEParameterSpec(salt, ITERATIONS);
  35. Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");
  36. cipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
  37. byte[] ciphertext = cipher.doFinal(plaintext.getBytes("UTF8"));
  38. return encoder.encode(salt) + encoder.encode(ciphertext);
  39. }
  40. System.out.println("Algoritmo non supportato");
  41. }
  42.  
  43.  
  44. catch (NoSuchPaddingException e2) {
  45. System.out.println("Padding non supportato");
  46. }
  47.  
  48. System.out.println("Specificazione della chiave non valida");
  49. }
  50.  
  51. catch (InvalidKeyException e4) {
  52. System.out.println("Chiave non valida");
  53. }
  54.  
  55. System.out.println("Parametro non valido");
  56. }
  57.  
  58. catch (IllegalBlockSizeException e6) {
  59. System.out.println("Dimensione blocco illegale");
  60. }
  61.  
  62. catch (BadPaddingException e7) {
  63. System.out.println("Bad Padding");
  64. }
  65. // TODO Auto-generated catch block
  66. e.printStackTrace();
  67. }
  68. return "Error";
  69. }
  70.  
  71. public static String decrypt(char[] password, String input) {
  72.  
  73. try{
  74. BASE64Decoder decoder = new BASE64Decoder();
  75. String salt64 = input.substring(0, 12);
  76. String ciphertext64 = input.substring( 12 );
  77. byte[] salt = decoder.decodeBuffer(salt64);
  78. byte[] ciphertext = decoder.decodeBuffer(ciphertext64);
  79. PBEKeySpec keySpec = new PBEKeySpec(password);
  80. SecretKeyFactory keyFactory =
  81. SecretKeyFactory.getInstance("PBEWithMD5AndDES");
  82. SecretKey key = keyFactory.generateSecret(keySpec);
  83. PBEParameterSpec paramSpec =
  84. new PBEParameterSpec(salt, ITERATIONS);
  85. Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");
  86. cipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
  87. byte[] plaintextArray = cipher.doFinal(ciphertext);
  88. return new String(plaintextArray );
  89. System.out.println("Algoritmo non supportato");
  90. }
  91.  
  92. catch (NoSuchPaddingException e2) {
  93. System.out.println("Padding non supportato");
  94. }
  95.  
  96. System.out.println("Specificazione della chiave non valida");
  97. }
  98.  
  99. catch (InvalidKeyException e4) {
  100. System.out.println("Chiave non valida");
  101. }
  102.  
  103. System.out.println("Parametro non valido");
  104. }
  105.  
  106. catch (IllegalBlockSizeException e6) {
  107. System.out.println("Dimensione blocco illegale");
  108. }
  109.  
  110. catch (BadPaddingException e7) {
  111. System.out.println("Bad Padding");
  112. }
  113.  
  114. catch (IOException e) {
  115. e.printStackTrace();
  116. }
  117.  
  118. return "Decifratura Fallita";
  119. }
  120.  
  121. }
  122. /*
  123. String esito,risultato;
  124. String pwd= null;
  125. System.out.println("INSERIRE PASSWORD = "+"/n");
  126.  
  127. try{
  128.  
  129. while ( (pwd=stdIn.readLine()) != null){
  130.  
  131. try{
  132.  
  133.  
  134. esito = inSock.readUTF();
  135. risultato=Cryptex.decrypt(pwd.toCharArray(),esito);
  136. System.out.println("Esito esame: " + risultato);
  137. // chiudo la socket in downstream
  138. socket.shutdownInput();
  139. System.out.println("Terminata la chiusura della socket: " + socket);
  140. */


Ultima modifica effettuata da netarrow il 29/04/2007 alle 12:11
PM Quote
Avatar
Shutdown (Founder Member)
Guru


Messaggi: 1212
Iscritto: 10/09/2005

Segnala al moderatore
Postato alle 18:09
Domenica, 29/04/2007
Bravo Matteo,
sempre pronto per quanto
riguarda questi campi.

PM Quote