2009-10-29 5 views

Répondre

2

D'un ancien code:

public void testSymCypher(SecretKey k, String str) 
     throws BadPaddingException, IllegalBlockSizeException, 
     InvalidAlgorithmParameterException, InvalidKeyException, 
     NoSuchAlgorithmException, NoSuchPaddingException 
{ 
    Cipher cip = Cipher.getInstance("DESede/CBC/PKCS5Padding"); 
    cip.init(Cipher.ENCRYPT_MODE,k); 
    byte[] ciphered = cip.doFinal(str.getBytes()); 
    byte iv[] = cip.getIV(); 

    // printing the ciphered string 
    printHexadecimal(ciphered); 

    IvParameterSpec dps = new IvParameterSpec(iv); 
    cip.init(Cipher.DECRYPT_MODE,k,dps); 
    byte[] deciphered = cip.doFinal(ciphered); 

    // printing the deciphered string 
    printHexadecimal(deciphered); 
} 

avis que d'autres utilisation de DESede sont disponibles en Java JDK 6:

  • DESede/CBC/NoPadding (168)
  • DESede/CBC/PKCS5Padding (168)

Il y a également le mode ECB disponible (mais carreful de ne pas utiliser deux fois !!), vous n'avez pas besoin d'utiliser une partie iv dans ce cas:

  • DESede/BCE/NoPadding (168)
  • DESede/BCE/PKCS5Padding (168)

pour générer la clé pour DESede:

KeyGenerator generatorDes = KeyGenerator.getInstance("DESede"); 
    SecretKey skaes = generatorDes.generateKey(); 

Enfin, je vous recommande la lecture this document de SUN si vous avez besoin de travailler sur Java et Cryptographie

+0

Ce code me donne une java.security.InvalidKeyException: longueur de clé non valide: 8 octets \t à com.sun.crypto.provider.DESedeCipher.engineGetKeySize (DashoA13 * ..) – ScArcher2

+0

Je pense qu'il est parce que je fait une erreur avec KeyGenerator : c'est DESede et non DES. Si vous utilisez votre propre clé, vérifiez la taille de votre clé (elle semble liée au type de clé 3DES que vous utilisez.Parce que je ne sais pas trop à ce sujet, s'il vous plaît se référer à la page wikipedia de 3DES). – Kartoch

1

Nous utilisons cette petite classe d'aide pour le chiffrement DES par mot de passe de chaîne à Hex String et arrière - ne savez pas comment obtenir ce travail avec 3DES si:

import java.security.spec.KeySpec; 

import javax.crypto.Cipher; 
import javax.crypto.SecretKey; 
import javax.crypto.SecretKeyFactory; 
import javax.crypto.spec.PBEKeySpec; 
import javax.crypto.spec.PBEParameterSpec; 

public class DesHelper { 
    private static org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(DesHelper.class); 

    static final byte[] SALT = { (byte) 0x09, /* snip - randomly chosen but static salt*/ }; 
    static final int ITERATIONS = 11; 

    private Cipher _ecipher; 
    private Cipher _dcipher; 

    public DesHelper(final String passphrase) { 
     try { 
      final PBEParameterSpec params = new PBEParameterSpec(SALT, ITERATIONS); 

      final KeySpec keySpec = new PBEKeySpec(passphrase.toCharArray()); 
      final SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES") 
        .generateSecret(keySpec); 

      _ecipher = Cipher.getInstance(key.getAlgorithm()); 
      _dcipher = Cipher.getInstance(key.getAlgorithm()); 
      _ecipher.init(Cipher.ENCRYPT_MODE, key, params); 
      _dcipher.init(Cipher.DECRYPT_MODE, key, params); 

     } catch (final Exception e) { 
      throw new RuntimeException(e); 
     } 
    } 

    public String encrypt(final String string) { 
     try { 
      // Encode the string into bytes using utf-8 
      final byte[] bytes = string.getBytes("UTF-8"); 

      // Encrypt 
      final byte[] enc = _ecipher.doFinal(bytes); 

      // Encode bytes to base64 to get a string 
      return bytesToHex(enc); 
     } catch (final Exception e) { 
      throw new RuntimeException(e); 
     } 
    } 

    public String decrypt(final String str) { 
     try { 
      // Decode base64 to get bytes 
      final byte[] dec = hexToBytes(str); 

      // Decrypt 
      final byte[] utf8 = _dcipher.doFinal(dec); 

      // Decode using utf-8 
      return new String(utf8, "UTF8"); 
     } catch (final Exception e) { 
      log.info("decrypting string failed: " + str + " (" + e.getMessage() + ")"); 
      return null; 
     } 
    } 

    private static String bytesToHex(final byte[] bytes) { 
     final StringBuilder buf = new StringBuilder(bytes.length * 2); 
     for (final byte b : bytes) { 
      final String hex = Integer.toHexString(0xff & b); 
      if (hex.length() == 1) { 
       buf.append("0"); 
      } 
      buf.append(hex); 
     } 
     return buf.toString(); 
    } 

    private static byte[] hexToBytes(final String hex) { 
     final byte[] bytes = new byte[hex.length()/2]; 
     for (int i = 0; i < bytes.length; i++) { 
      bytes[i] = (byte) Integer.parseInt(hex.substring(i * 2, i * 2 + 2), 16); 
     } 
     return bytes; 
    } 
} 

Vous feriez utiliser cette classe comme ceci:

public static void main(final String[] args) { 
    final DesHelper h = new DesHelper("blabla"); 
    System.out.println(h.decrypt(h.encrypt("foobar"))); 
} 
0

J'ai écrit un article sur ce parfois de retour. S'il vous plaît visitez le lien suivant dans mon blog qui a un code de travail, complété avec des explications et un diagramme.

View My Triple DES Encryption Article, Code Here

Nous espérons que vous trouverez utile.

0

Vous pouvez également envisager d'utiliser un chiffrement de flux (par exemple, le mode OFB ou CTR en plus d'un chiffrement de bloc 3DES), de sorte que vous n'avez pas besoin de remplir la chaîne à un multiple de la taille de chiffrement chiffré.

Questions connexes