DES encode String value - Android java.security

Android examples for java.security:DES

Description

DES encode String value

Demo Code


//package com.java2s;
import android.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.security.Key;
import java.security.spec.AlgorithmParameterSpec;

public class Main {
    public static final String ALGORITHM_DES = "DES/CBC/PKCS5Padding";

    public static String encode(String key, String data) throws Exception {
        return encode(key, data.getBytes());
    }/*from   w  w  w . ja  v a  2 s. co  m*/

    public static String encode(String key, byte[] data) throws Exception {
        try {
            DESKeySpec dks = new DESKeySpec(key.getBytes());

            SecretKeyFactory keyFactory = SecretKeyFactory
                    .getInstance("DES");
            //key8
            Key secretKey = keyFactory.generateSecret(dks);
            Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
            IvParameterSpec iv = new IvParameterSpec(key.getBytes());
            AlgorithmParameterSpec paramSpec = iv;
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec);

            byte[] bytes = cipher.doFinal(data);

            return new String(Base64.encode(bytes, Base64.DEFAULT));
        } catch (Exception e) {
            throw new Exception(e);
        }
    }
}

Related Tutorials