java加解密算法的简单运用

互联网虽然用起来方便,但是很容易信息泄露,被些别有用心的人攻击,为了保护网络的安全,双向加密算法例如DES,AES,信息摘要MD5,SHA应运而生。
java在jdk的包中也支持相关的加解密算法,底层通过spi扩展机制,加载不同的provider。
其中有几个比较关键的类

  1. KeyGenerator :提供对称密钥生成器的功能,支持各种算法
  2. SecretKey:责保存对称密钥
  3. Cipher:负责完成加密或解密工作
package com.cipher;/*
    @author 
    @time 23:02
*/

import org.junit.Test;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

public class CipherTest {

    @Test
    public void DESTest() throws Exception {
        //对称加密生成器
        KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
        //keyGenerator.
        SecretKey secretKey = keyGenerator.generateKey();
        Cipher cipher = Cipher.getInstance("DES");

        String str="hello DES";
        //加密
        cipher.init(Cipher.ENCRYPT_MODE,secretKey);
        byte[] encryptStr = cipher.doFinal(str.getBytes());

        String hexStr = EncryptUtil.parseByte2HexStr(encryptStr);
        System.out.println(hexStr);

        //解密
        cipher.init(Cipher.DECRYPT_MODE,secretKey);
        byte[] decryptorByte = cipher.doFinal(parseHexStr2Byte(hexStr));
        System.out.println(new String(decryptorByte));
    }

    @Test
    public void AESTest() throws Exception {
        //对称加密生成器
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        //keyGenerator.
        SecretKey secretKey = keyGenerator.generateKey();
        Cipher cipher = Cipher.getInstance("AES");

        String str="hello AES";
        //加密
        cipher.init(Cipher.ENCRYPT_MODE,secretKey);
        byte[] encryptStr = cipher.doFinal(str.getBytes());

        String hexStr = parseByte2HexStr(encryptStr);
        System.out.println(hexStr);

        //解密
        cipher.init(Cipher.DECRYPT_MODE,secretKey);
        byte[] decryptorByte = cipher.doFinal(EncryptUtil.parseHexStr2Byte2(hexStr));
        System.out.println(new String(decryptorByte));
    }
    //指定key加解密
    @Test
    public void AESByIndicateKeyTest() throws Exception {
        //对称加密生成器
        String key = "AESKEY";
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(new SecureRandom(key.getBytes("utf-8")));
        //keyGenerator.
        SecretKey secretKey = keyGenerator.generateKey();
        Cipher cipher = Cipher.getInstance("AES");

        String str="hello AES";
        //加密
        cipher.init(Cipher.ENCRYPT_MODE,secretKey);
        byte[] encryptStr = cipher.doFinal(str.getBytes());

        String hexStr = parseByte2HexStr(encryptStr);
        System.out.println(hexStr);


        //使用特定的key
        KeyGenerator keyGenerator2 = KeyGenerator.getInstance("AES");
        keyGenerator2.init(new SecureRandom(key.getBytes("utf-8")));
        //keyGenerator.
        SecretKey secretKey2 = keyGenerator2.generateKey();

        //解密
        cipher.init(Cipher.DECRYPT_MODE,secretKey2);
        byte[] decryptorByte = cipher.doFinal(EncryptUtil.parseHexStr2Byte2(hexStr));
        System.out.println(new String(decryptorByte));
    }


    @Test
    public void md5Test() throws NoSuchAlgorithmException {
        MessageDigest messageDigest = MessageDigest.getInstance("MD5");
        String str = "hello md5";
        byte[] result = messageDigest.digest(str.getBytes());
        System.out.println(new String(Base64.getEncoder().encode(result)));
    }

    /**将二进制转换成16进制 */
    public static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {

            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }


    /**将16进制转换为二进制*/
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1)
            return null;
        byte[] result = new byte[hexStr.length()/2];
        for (int i = 0;i< hexStr.length()/2; i++) {
            int temp = Integer.parseInt(hexStr.substring(i*2, i*2+2), 16);
            result[i] = (byte) (temp);
        }
        return result;
    }


}

官方文档:
https://docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html#KeyGenerator

文件加密解密算法(Java源码) java,file,算法,加密解密,java源码 package com.crypto.encrypt; import java.security.SecureRandom; import java.io.*; import javax.crypto.spec.DESKeySpec; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.Cipher; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import javax.crypto.NoSuchPaddingException; import javax.crypto.BadPaddingException; import javax.crypto.IllegalBlockSizeException; import java.lang.reflect.Constructor; import java.security.spec.KeySpec; import java.lang.reflect.InvocationTargetException; public class EncryptData { private String keyfile=null; public EncryptData() { } public EncryptData(String keyfile) { this.keyfile=keyfile; } /** * 加密文件 * @param filename String 源路径 * @param filenamekey String 加密后的路径 */ public void createEncryptData(String filename,String filenamekey) throws IllegalStateException, IllegalBlockSizeException, BadPaddingException, NoSuchPaddingException, InvalidKeySpecException, NoSuchAlgorithmException, InvalidKeyException, IOException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, ClassNotFoundException, IllegalStateException, IllegalBlockSizeException, BadPaddingException, NoSuchPaddingException, InvalidKeySpecException, NoSuchAlgorithmException, InvalidKeyException, IOException { //验证keyfile if(keyfile==null || keyfile.equals("")) { throw new NullPointerException("无效的key文件路径"); } encryptData(filename,filenamekey); } /** * 加密类文件 * @param filename String 原始的类文件 * @param encryptfile String 加密后的类文件 * @throws IOException * @throws InvalidKeyException * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException * @throws NoSuchPaddingException * @throws NoSuchAlgorithmException * @throws BadPaddingException * @throws IllegalBlockSizeException * @throws IllegalStateException */ private void encryptData(String filename,String encryptfile) throws IOException, InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, NoSuchAlgorithmException, BadPaddingException, IllegalBlockSizeException, IllegalStateException, ClassNotFoundException, SecurityException, NoSuchMethodException, InvocationTargetException, IllegalArgumentException, IllegalAccessException, InstantiationException { byte data[]=Util.readFile(filename); // 执行加密操作 byte encryptedClassData[] = getencryptData(data); // 保存加密后的文件,覆盖原有的类文件。 Util.writeFile(encryptedClassData,encryptfile); } /** * 直接获得加密数据 * @param bytes byte[] * @throws IllegalStateException * @throws IllegalBlockSizeException * @throws BadPaddingException * @throws InvalidKeyException * @throws NoSuchPaddingException * @throws InvalidKeySpecException * @throws NoSuchAlgorithmException * @throws InstantiationException * @throws IllegalAccessException * @throws IllegalArgumentException * @throws InvocationTargetException * @throws NoSuchMethodException * @throws SecurityException * @throws ClassNotFoundException * @throws IOException * @return byte[] */ public byte[] createEncryptData(byte[] bytes) throws IllegalStateException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException, NoSuchPaddingException, InvalidKeySpecException, NoSuchAlgorithmException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, ClassNotFoundException, IOException { bytes=getencryptData(bytes); return bytes; } private byte[] getencryptData(byte[] bytes) throws IOException, ClassNotFoundException, SecurityException, NoSuchMethodException, InvocationTargetException, IllegalArgumentException, IllegalAccessException, InstantiationException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, IllegalStateException { // 产生一个可信任的随机数源 SecureRandom sr = new SecureRandom(); //从密钥文件key Filename中得到密钥数据 byte[] rawKeyData = Util.readFile(keyfile); // 从原始密钥数据创建DESKeySpec对象 Class classkeyspec=Class.forName(Util.getValue("keyspec")); Constructor constructor = classkeyspec.getConstructor(new Class[]{byte[].class}); KeySpec dks = (KeySpec) constructor.newInstance(new Object[]{rawKeyData}); // 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(Util.getAlgorithm()); SecretKey key = keyFactory.generateSecret(dks); // Cipher对象实际完成加密操作 Cipher cipher = Cipher.getInstance(Util.getAlgorithm()); // 用密钥初始化Cipher对象 cipher.init(Cipher.ENCRYPT_MODE, key, sr); // 执行加密操作 bytes = cipher.doFinal(bytes); // 返回字节数组 return bytes; } /** * 设置key文件路径 * @param keyfile String */ public void setKeyFile(String keyfile) { this.keyfile=keyfile; } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值