DES encrypt with hard coded key - Android java.security

Android examples for java.security:DES

Description

DES encrypt with hard coded key

Demo Code


//package com.java2s;
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import android.annotation.SuppressLint;
import android.util.Base64;

public class Main {
    private static final String CHARSET = "UTF-8";
    private static final String ALGORITHM = "DES";
    private static final String TRANSFORMATION = "DES";
    private static final String KEY = "CSIIYZBK";
    private static SecretKey secretkey = null;

    @SuppressLint("TrulyRandom")
    public static String encrypt(String source) {
        String result = null;//from  w ww  .  j a v  a  2  s .c om
        byte[] input = null;
        try {
            byte[] center = source.getBytes(CHARSET);
            Cipher cipher = Cipher.getInstance(TRANSFORMATION);
            cipher.init(Cipher.ENCRYPT_MODE, getKey());
            input = cipher.doFinal(center);
            result = Base64.encodeToString(input, Base64.DEFAULT);
        } catch (Exception e) {
        }
        return result;
    }

    private static Key getKey() {
        if (secretkey == null) {
            byte[] key = null;
            try {
                key = KEY.getBytes(CHARSET);
                secretkey = new SecretKeySpec(key, ALGORITHM);
            } catch (Exception e) {
            }
        }
        return secretkey;
    }
}

Related Tutorials