com.java.demo.DesDemo.java Source code

Java tutorial

Introduction

Here is the source code for com.java.demo.DesDemo.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.java.demo;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.*;
import javax.crypto.Cipher;
import org.apache.commons.codec.binary.Hex;

/**
 *
 * @author Administrator
 */
public class DesDemo {

    public static void main(String[] args) {
        //des(data crpt)
        Init();
        byte[] strBytes = Encrypt("abc");
        System.out.println(Hex.encodeHexString(strBytes));
        byte[] str = Decrypt(strBytes);
        System.out.println(new String(str));
    }

    static Key convertSecretKey;

    public static void Init() {
        try {
            KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
            keyGenerator.init(56);
            SecretKey secretKey = keyGenerator.generateKey();
            byte[] bytesKey = secretKey.getEncoded();

            DESKeySpec dESKeySpec = new DESKeySpec(bytesKey);
            SecretKeyFactory factory = SecretKeyFactory.getInstance("DES");
            convertSecretKey = factory.generateSecret(dESKeySpec);

        } catch (Exception e) {
        }
    }

    public static byte[] Encrypt(String str) {
        try {
            Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, convertSecretKey);
            byte[] result = cipher.doFinal(str.getBytes());
            return result;

        } catch (Exception e) {
            return null;
        }
    }

    public static byte[] Decrypt(byte[] strBytes) {
        try {
            Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, convertSecretKey);
            byte[] result = cipher.doFinal(strBytes);
            return result;
        } catch (Exception e) {
            return null;
        }
    }
}