java 常见的加密算法

加密算法分类:

v 只能加密:SHA  SHA1  MD5  CRC-32

v 既能加密也能解密:

DES  3DES  AES  Blowfish

RSA(加密、签名)   DSA(只能签名)

非对称加密技术开销比较大,不适合大文本的加密。


Java代码实现SHA算法


/*

SHA(Secure Hash Algorithm,安全散列算法),数字签名等密码学应用中重要的工具,

被广泛地应用于电子商务等信息安全领域。虽然,SHA与MD5通过碰撞法都被破解了, 

但是SHA仍然是公认的安全加密算法,较之MD5更为安全*/

public class SHAEncode {
    public static final String KEY_SHA = "SHA1";   
    
    public static String shaDigest(byte[] source) throws NoSuchAlgorithmException {

String encrpt = null;
MessageDigest md = MessageDigest.getInstance(KEY_SHA);
md.update(source);
//得到数据摘要
byte[] digest = md.digest();
//把二进制数组转换成十六进制字符串
encrpt = Byte2HexStrUtil.byte2HexStr(digest);
return encrpt;
}
}


Java代码实现MD5算法

/**
  * 获取加密后的字符串
  * @param input
  * @return
  */
 public static String md5Digest(String data) {
  try {  
     
        // 拿到一个MD5转换器(如果想要SHA1参数换成”SHA1”)  
        MessageDigest messageDigest =MessageDigest.getInstance("MD5");  
        // 输入的字符串转换成字节数组  
        byte[] inputByteArray = data.getBytes();  
        // inputByteArray是输入字符串转换得到的字节数组  
        messageDigest.update(inputByteArray);  
        // 转换并返回结果,也是字节数组,包含16个元素  
        byte[] resultByteArray = messageDigest.digest();  
        // 字符数组转换成字符串返回  
        return byteArrayToHex(resultByteArray);  
     } catch (NoSuchAlgorithmException e) {  
        return null;  
     }  
 }
 
    public static String byteArrayToHex(byte[] byteArray) {  
        
        // 首先初始化一个字符数组,用来存放每个16进制字符  
        char[] hexDigits = {'0','1','2','3','4','5','6','7','8','9', 'A','B','C','D','E','F' };  
        // new一个字符数组,这个就是用来组成结果字符串的(解释一下:一个byte是八位二进制,也就是2位十六进制字符(2的8次方等于16的2次方))  
        char[] resultCharArray =new char[byteArray.length * 2];  
        // 遍历字节数组,通过位运算(位运算效率高),转换成字符放到字符数组中去  
        int index = 0; 
        for (byte b : byteArray) {  
           resultCharArray[index++] = hexDigits[b>>> 4 & 0xf];  
           resultCharArray[index++] = hexDigits[b& 0xf];  
        }
        // 字符数组组合成字符串返回  
        return new String(resultCharArray);  
    }


java实现DES加密算法

/**
 * DES加密
 * @param source
 * @return
 */
public static String desEncrypt(String source){
if(source == null || source.length() ==0){
return null;
}
try {
     //DES算法要求有一个可信任的随机数源
     SecureRandom sr = new SecureRandom();
     //从原始密钥数据创建一个DESKeySpec对象
     DESKeySpec dks = new DESKeySpec(DES_KEY.getBytes());
     SecretKeyFactory keyFactory = 
                                   SecretKeyFactory.getInstance("DES");
     //生产密钥
     SecretKey key = keyFactory.generateSecret(dks);
     //Cipher对象实际完成加密操作
     Cipher cipher = Cipher.getInstance("DES");
     //使用密钥初始化Cipher对象
     cipher.init(Cipher.ENCRYPT_MODE,key,sr);
     byte [] data =source.getBytes();
     //加密
     byte [] encryptedData = cipher.doFinal(data);
     //转成16进制串
     String hexString = HexUtil.byte2HexStr(encryptedData);
return hexString;
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}


/**
 * DES解密
 * @param source
 * @return
 */
public static String desDecrypt(String source){
if(source == null || source.length() ==0){
return null;
}
try {
//DES算法要求有一个可信任的随机数源
SecureRandom sr = new SecureRandom();
//从原始密钥数据创建一个DESKeySpec对象
DESKeySpec dks = new DESKeySpec(DES_KEY.getBytes());
SecretKeyFactory keyFactory =   
                                SecretKeyFactory.getInstance("DES");
SecretKey key = keyFactory.generateSecret(dks);
//Cipher对象实际完成解密操作
Cipher cipher = Cipher.getInstance("DES");
//使用密钥初始化Cipher对象
cipher.init(Cipher.DECRYPT_MODE,key,sr);
//将十六进制串转成字节数组
byte [] data =HexUtil.hex2Byte(source);
//解密
byte [] decryptedData = cipher.doFinal(data);
return new String(decryptedData);
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}



3DES加密算法

实现3DES加密算法

、加入bcprov-jdk16-145.jar包支持
       public class ThreeDESUtil {
    // 算法名称 
    public static final String KEY_ALGORITHM = "desede";
    // 算法名称/加密模式/填充方式 
    public static final String CIPHER_ALGORITHM = "desede/CBC/NoPadding";

    /** *//** 
     * CBC加密 
     * @param key 密钥 
     * @param keyiv IV 
     * @param data 明文 
     * @return Base64编码的密文 
     * @throws Exception 
     */
    public static byte[] des3EncodeCBC(byte[] key, byte[] keyiv, byte[] data) throws Exception {
        Security.addProvider(new BouncyCastleProvider()); 
        Key deskey = keyGenerator(new String(key));
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        IvParameterSpec ips = new IvParameterSpec(keyiv);
        cipher.init(Cipher.ENCRYPT_MODE, deskey, ips);
        byte[] bOut = cipher.doFinal(data);
        for (int k = 0; k < bOut.length; k++) {
            System.out.print(bOut[k] + " ");
        }
        System.out.println("");
        return bOut;
    }

    /** *//** 
     *   
     * 生成密钥key对象 
     * @param KeyStr 密钥字符串 
     * @return 密钥对象 
     * @throws InvalidKeyException   
     * @throws NoSuchAlgorithmException   
     * @throws InvalidKeySpecException   
     * @throws Exception 
     */
    private static Key keyGenerator(String keyStr) throws Exception {
        byte input[] = HexString2Bytes(keyStr);
        DESedeKeySpec KeySpec = new DESedeKeySpec(input);
        SecretKeyFactory KeyFactory = SecretKeyFactory.getInstance(KEY_ALGORITHM);
        return ((Key) (KeyFactory.generateSecret(((java.security.spec.KeySpec) (KeySpec)))));
    }

    private static int parse(char c) {
        if (c >= 'a') return (c - 'a' + 10) & 0x0f;
        if (c >= 'A') return (c - 'A' + 10) & 0x0f;
        return (c - '0') & 0x0f;
    }
 
    // 从十六进制字符串到字节数组转换 
    public static byte[] HexString2Bytes(String hexstr) {
        byte[] b = new byte[hexstr.length() / 2];
        int j = 0;
        for (int i = 0; i < b.length; i++) {
            char c0 = hexstr.charAt(j++);
            char c1 = hexstr.charAt(j++);
            b[i] = (byte) ((parse(c0) << 4) | parse(c1));
        }
        return b;
    }

    /** *//** 
     * CBC解密 
     * @param key 密钥 
     * @param keyiv IV 
     * @param data Base64编码的密文 
     * @return 明文 
     * @throws Exception 
     */
    public static byte[] des3DecodeCBC(byte[] key, byte[] keyiv, byte[] data) throws Exception {
        Key deskey = keyGenerator(new String(key));
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        IvParameterSpec ips = new IvParameterSpec(keyiv);
        cipher.init(Cipher.DECRYPT_MODE, deskey, ips);
        byte[] bOut = cipher.doFinal(data);
        return bOut;
    }

    public static void main(String[] args) throws Exception {
        byte[] key = "6C4E60E55552386C759569836DC0F83869836DC0F838C0F7".getBytes();
        byte[] keyiv = { 1, 2, 3, 4, 5, 6, 7, 8 };
        byte[] data = "amigoxie".getBytes("UTF-8");
        System.out.println("data.length=" + data.length);
        System.out.println("CBC加密解密");
        byte[] str5 = des3EncodeCBC(key, keyiv, data);
        System.out.println(new sun.misc.BASE64Encoder().encode(str5));

        byte[] str6 = des3DecodeCBC(key, keyiv, str5);
        System.out.println(new String(str6, "UTF-8"));
    }
}

       



转载于:https://blog.51cto.com/dezewuyou/1833825