Advertisement
Guest User

prueba

a guest
Oct 6th, 2012
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.20 KB | None | 0 0
  1. package cifrados;
  2. import java.security.MessageDigest;
  3. import java.security.NoSuchAlgorithmException;
  4.  
  5. public class prueba {
  6.     public static String md2 = "MD2";
  7.     public static String md5 = "MD5";
  8.     public static String sha1 = "SHA-1";
  9.     public static String sha256 = "SHA-256";
  10.     public static String sha384 = "SHA-384";
  11.     public static String sha512 = "SHA-512";
  12.  
  13.     private static String toHexadecimal(byte[] digest){ //array digest == digerir
  14.         String hash = "";
  15.         /*":", no es usado como operador,
  16.         que se utilizará para iteración a través de la matriz de la matriz denominada "digest"
  17.         #se conserva la variable aux e itera el array digest*/
  18.         /***
  19.          * Convierte un arreglo de bytes a String usando valores hexadecimales
  20.          * @param digest arreglo de bytes a convertir
  21.          * @return String creado a partir de digest
  22.          */
  23.         for(byte aux : digest){
  24.             int b = aux & 0xff;
  25.             if(Integer.toHexString(b).length() == 1) hash += "0";
  26.             hash += Integer.toHexString(b);
  27.         }
  28.         return hash;
  29.     }
  30.     /***
  31.          * Encripta un mensaje de texto mediante algoritmo de resumen de mensaje.
  32.          * @param message texto a encriptar
  33.          * @param algorithm algoritmo de encriptacion, puede ser: MD2, MD5, SHA-1, SHA-256, SHA-384, SHA-512
  34.          * @return mensaje encriptado
  35.          */
  36.     public static String getStringMessageDigest(String message, String algorithm){
  37.         byte[] digest = null;
  38.         byte[] buffer = message.getBytes();
  39.         try{
  40.             MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
  41.             messageDigest.reset();
  42.             messageDigest.update(buffer);
  43.             digest = messageDigest.digest();
  44.         }catch(NoSuchAlgorithmException ex){
  45.             System.out.println("Error creando Digest");
  46.         }
  47.         return toHexadecimal(digest);
  48.     }
  49.    
  50.     public static void main(String[] args) {
  51.         //ejemplo de como hacerlo en esta clase
  52.         String mensaje = "";
  53.         System.out.println("Mensaje = " + mensaje);
  54.         System.out.println("MD5 = " + prueba.getStringMessageDigest(mensaje, prueba.md5));
  55.  
  56.     }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement