Encrypt DES String message - Android java.security

Android examples for java.security:DES

Description

Encrypt DES String message

Demo Code


//package com.java2s;
import android.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

public class Main {
    private final static String key = "zhba1111";
    private final static String iv = "12345678";

    public static String EncryptDES(String message) throws Exception {
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");

        DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));

        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
        IvParameterSpec secretIv = new IvParameterSpec(iv.getBytes("UTF-8"));
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, secretIv);

        return Base64.encodeToString(
                cipher.doFinal(message.getBytes("UTF-8")), Base64.DEFAULT);
    }/* w  w  w.  j  ava2 s.  com*/
}

Related Tutorials