阅读背景:

java加解密算法--DES

来源:互联网 
  • ECB
import sun.misc.BASE64Decoder;

import javax.crypto.*;
import javax.crypto.spec.DESKeySpec;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;

public class encrypt {

    public static byte[] initSecretKey() throws NoSuchAlgorithmException {
        //指定算法秘钥生成器
        KeyGenerator kg = KeyGenerator.getInstance("des");
        //初始化秘钥生成器,使其具有确定到秘钥大小
        kg.init(56);
        //生成秘钥
        SecretKey secretkey = kg.generateKey();
        return secretkey.getEncoded();
    }

    public static byte[] encrypt(byte[] key, String src) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, BadPaddingException, IllegalBlockSizeException {
        //jdk初始化秘钥转化des秘钥
        DESKeySpec desKeySpec = new DESKeySpec(key);
        //创建秘钥工厂实例
        SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("des");
        //生成秘钥
        SecretKey secretKey = secretKeyFactory.generateSecret(desKeySpec);

        /**
         * 加密实际操作Cipher
         */
        //创建Cipher对象
        Cipher cipher = Cipher.getInstance("des/ecb/PKCS5Padding");
        //初始化Cipher
        cipher.init(Cipher.ENCRYPT_MODE,secretKey);
        byte[] data = src.getBytes();
        //加密
        byte[] encryptedData = cipher.doFinal(data);

    }

    public static void main(String[] args) throws NoSuchAlgorithmException, IllegalBlockSizeException, NoSuchPaddingException, BadPaddingException, InvalidKeySpecException, InvalidKeyException, IOException {
        //byte[] secretKey = initSecretKey();
        //或者代码中约定key
        String key = "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4";
        byte[] secretKey = new BASE64Decoder().decodeBuffer(key);
        String str = "abc";
        byte[] encryptedData = encrypt(secretKey, str);
        String decrypteData = decrypt(secretKey, encryptedData);
    }

    public static String decrypt(byte[] key,byte[] encryptedData) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, BadPaddingException, IllegalBlockSizeException {
        //jdk初始化秘钥转化des秘钥
        DESKeySpec desKeySpec = new DESKeySpec(key);
        //创建秘钥工厂实例
        SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("des");
        //生成秘钥
        SecretKey secretKey = secretKeyFactory.generateSecret(desKeySpec);

        /**
         * 解密实际操作Cipher
         */
        //创建Cipher对象
        Cipher cipher = Cipher.getInstance("des/ecb/PKCS5Padding");
        //初始化Cipher
        cipher.init(Cipher.DECRYPT_MODE,secretKey);
        //加密
        byte[] dencryptedData = cipher.doFinal(encryptedData);
        return new String(dencryptedData);
    }
}
import sun.misc.BASE64Decoder;



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: