Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.security.NoSuchAlgorithmException;

import java.util.Locale;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

public class Main {
    public static String enCrypto(String txt, String key) {

        if (txt != null && !"".equals(txt) && !"null".equals(txt)) {

            try {

                StringBuffer sb = new StringBuffer();
                DESKeySpec desKeySpec = new DESKeySpec(key.getBytes());
                SecretKeyFactory skeyFactory = null;
                Cipher cipher = null;
                try {
                    skeyFactory = SecretKeyFactory.getInstance("DES");
                    cipher = Cipher.getInstance("DES");
                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                }
                SecretKey deskey = skeyFactory.generateSecret(desKeySpec);
                cipher.init(Cipher.ENCRYPT_MODE, deskey);
                byte[] cipherText = cipher.doFinal(txt.getBytes());
                for (int n = 0; n < cipherText.length; n++) {
                    String stmp = (java.lang.Integer.toHexString(cipherText[n] & 0XFF));
                    if (stmp.length() == 1) {
                        sb.append("0" + stmp);
                    } else {
                        sb.append(stmp);
                    }
                }
                return sb.toString().toUpperCase(Locale.US);

            } catch (Exception e) {

                e.printStackTrace();
            }
        }
        return null;
    }
}