get Secret Key Spec - Android java.security

Android examples for java.security:Key

Description

get Secret Key Spec

Demo Code


//package com.java2s;
import android.provider.Settings;
import java.security.MessageDigest;
import java.security.spec.KeySpec;

import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;

public class Main {
    private static SecretKeySpec getSecretKeySpec(String passphrase,
            String algorithm, int kgenbit) throws Exception {
        // 8-byte Salt - SHOULD NOT BE DISCLOSED
        // alternative approach is to have the salt passed from the
        // calling class (pass-the-salt)?
        byte[] salt = Settings.Secure.ANDROID_ID.getBytes();

        // Iteration count
        int iterationCount = 1024;

        KeySpec keySpec = new PBEKeySpec(passphrase.toCharArray(), salt,
                iterationCount);/*from w  ww.jav  a  2  s  .c om*/

        SecretKey secretKey = SecretKeyFactory.getInstance(
                "PBEWithMD5AndDES").generateSecret(keySpec);

        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(secretKey.getEncoded());
        md.update(salt);
        for (int i = 1; i < iterationCount; i++) {
            md.update(md.digest());
        }

        byte[] keyBytes = md.digest();
        SecretKeySpec skeyspec = new SecretKeySpec(keyBytes, algorithm);

        return skeyspec;
    }
}

Related Tutorials