Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.juicioenlinea.application.secutiry; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.logging.Level; import java.util.logging.Logger; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import org.apache.commons.codec.binary.Base64; /** * * @author eddy_ */ public class Security { public static String encriptar(String texto) { final String secretKey = "hunter"; //llave para encriptar datos String encryptedString = null; try { MessageDigest md = MessageDigest.getInstance("SHA"); byte[] digestOfPassword = md.digest(secretKey.getBytes("UTF-8")); byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24); SecretKey key = new SecretKeySpec(keyBytes, "DESede"); Cipher cipher = Cipher.getInstance("DESede"); cipher.init(Cipher.ENCRYPT_MODE, key); byte[] plainTextBytes = texto.getBytes("UTF-8"); byte[] buf = cipher.doFinal(plainTextBytes); byte[] base64Bytes = Base64.encodeBase64(buf); encryptedString = new String(base64Bytes); } catch (NoSuchAlgorithmException | UnsupportedEncodingException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException ex) { Logger.getLogger(Security.class.getName()).log(Level.SEVERE, null, ex); } return encryptedString; } public static String desencriptar(String textoEncriptado) { final String secretKey = "hunter"; //llave para encriptar datos String encryptedString = null; try { byte[] message = Base64.decodeBase64(textoEncriptado.getBytes("UTF-8")); MessageDigest md = MessageDigest.getInstance("SHA"); byte[] digestOfPassword = md.digest(secretKey.getBytes("UTF-8")); byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24); SecretKey key = new SecretKeySpec(keyBytes, "DESede"); Cipher decipher = Cipher.getInstance("DESede"); decipher.init(Cipher.DECRYPT_MODE, key); byte[] plainText = decipher.doFinal(message); encryptedString = new String(plainText, "UTF-8"); } catch (UnsupportedEncodingException | InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException ex) { Logger.getLogger(Security.class.getName()).log(Level.SEVERE, null, ex); } return encryptedString; } }