java实现DES加密和解密

import javax.crypto.Cipher;

import javax.crypto.KeyGenerator;

import javax.crypto.SecretKey;

import java.security.Key;

import java.security.SecureRandom;

import java.util.Scanner;

import sun.misc.BASE64Encoder;

 

 

 

public class DES {

 

    public static final String ALGORITHM="DES";

 

 

    public static void main(String[] args) {

 

        String str = null;

 

        Scanner scanner = new Scanner(System.in);

        str = scanner.next();

        System.out.println("原文:"+str);

 

 

 

 

 

//       加密和解密

        try {

 

 

            Key key = toKey();

 

            System.out.println("密钥:"+key);

 

            byte[] encrytoResult = encrypt(str.getBytes(), key);

            BASE64Encoder base64Encoder = new BASE64Encoder();  //将字节转换为字符串输出

            System.out.println("加密后:"+base64Encoder.encode(encrytoResult));

 

            byte[] decrytoResult = decrypt(encrytoResult,key);

            System.out.println("解密后:"+new String(decrytoResult));

 

        }catch (Exception e){

            e.printStackTrace();

        }

    }

 

    //    生成密钥

    public static Key toKey() throws Exception{

 

 

 

 

//            DESKeySpec desKeySpec = new DESKeySpec(key);

//            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);

//            secretKey = keyFactory.generateSecret(desKeySpec);

 

        KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);

        keyGenerator.init(56);//密钥长度为64位

        SecretKey  secretKey = keyGenerator.generateKey();

 

 

        return secretKey;

 

    }

 

    //加密

    public static byte[] encrypt(byte[] data,Key key) throws Exception{

 

        SecureRandom random = new SecureRandom();

        Cipher cipher = Cipher.getInstance("DES");

        cipher.init(Cipher.ENCRYPT_MODE, key, random);

 

 

        return  cipher.doFinal(data);

    }

 

    //    解密

    public static byte[] decrypt(byte[] data,Key key) throws  Exception{

 

 

        SecureRandom random = new SecureRandom();

        Cipher cipher = Cipher.getInstance("DES");

        cipher.init(Cipher.DECRYPT_MODE,key,random);

 

        return cipher.doFinal(data);

 

    }

 

}



遇到的问题:sun.misc.BASE64Encoder找不到jar包?

解决方法:右击项目->properties->java build path,将JRE System Library先移除,再将JRE System Library加进来,重新编译一下就行了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值