Java DES desEncrypt(byte[] input, String password)

Here you can find the source of desEncrypt(byte[] input, String password)

Description

des Encrypt

License

Apache License

Declaration

public static byte[] desEncrypt(byte[] input, String password) 

Method Source Code


//package com.java2s;
/*/*from   w  w w .  j a  va2  s .c  o m*/
 * Copyright 2002-2015 by bafeimao.net
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import javax.crypto.*;
import javax.crypto.spec.DESKeySpec;

import java.security.SecureRandom;

public class Main {
    public static byte[] desEncrypt(byte[] input, String password) {
        return doDes(Cipher.ENCRYPT_MODE, input, password);
    }

    public static byte[] desEncrypt(String message, String password) {
        return desEncrypt(message.getBytes(), password);
    }

    private static byte[] doDes(int mode, byte[] input, String password) {
        try {
            SecureRandom random = new SecureRandom();
            DESKeySpec desKey = new DESKeySpec(password.getBytes());
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey securekey = keyFactory.generateSecret(desKey);
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(mode, securekey, random);
            return cipher.doFinal(input);
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;
    }
}

Related

  1. des3EncodeECB(byte[] key, byte[] data)
  2. desEncrypt(byte[] data, String encryptKey)
  3. desEncrypt(String content, String key)