des3 Encrypt plain text with key and charset, return byte array - Java Security

Java examples for Security:DES

Description

des3 Encrypt plain text with key and charset, return byte array

Demo Code


//package com.java2s;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class Main {
    public static void main(String[] argv) throws Exception {
        String plainText = "java2s.com";
        String key = "java2s.com";
        String charset = "java2s.com";
        System.out.println(java.util.Arrays.toString(des3Encrypt(plainText,
                key, charset)));/*from  w  ww.j  av  a  2  s .  c o  m*/
    }

    public static byte[] des3Encrypt(String plainText, String key,
            String charset) {

        try {
            SecretKey secretKey = new SecretKeySpec(key.getBytes(charset),
                    "DESede");
            /*
             KeyGenerator kg = KeyGenerator.getInstance("DESede");
             kg.init(new SecureRandom(key.getBytes(charset)));
             SecretKey secretKey = kg.generateKey();
             */
            Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);

            return cipher.doFinal(plainText.getBytes(charset));

        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }
}

Related Tutorials