java Des加解密算法

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.SecureRandom;
import java.util.Base64;



public class A {


    public static void main(String[] args) {
        String content = args[0];
        // 密码长度必须是8的倍数
        String password = args[1];

        String mode = args[2];

        if(mode.equals("decode")){
            String decryResult = decrypt(Base64.getDecoder().decode(content), password);
            System.out.println("解密后:" + decryResult);
        } else {
            System.out.println("密 钥:" + password);
            System.out.println("加密前:" + content);
            byte[] result = encrypt(content, password);
            String medid = Base64.getEncoder().encodeToString(result);
            System.out.println("加密后:" + Base64.getEncoder().encodeToString(result));
        }
    }


    private static byte[] encrypt(String content, String key) {
        try {
            SecureRandom random = new SecureRandom();
            DESKeySpec desKey = new DESKeySpec(key.getBytes());
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey securekey = keyFactory.generateSecret(desKey);
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.ENCRYPT_MODE, securekey, random);
            byte[] result = cipher.doFinal(content.getBytes());
            return result;
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;
    }

    private static String decrypt(byte[] content, String key) {
        try {
            SecureRandom random = new SecureRandom();
            DESKeySpec desKey = new DESKeySpec(key.getBytes());
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey securekey = keyFactory.generateSecret(desKey);
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.DECRYPT_MODE, securekey, random);
            byte[] result = cipher.doFinal(content);
            return new String(result);
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;
    }
}

 

你可能感兴趣的:(java)