derive Key From Password - Android java.security

Android examples for java.security:Key

Description

derive Key From Password

Demo Code


//package com.java2s;

import java.security.NoSuchAlgorithmException;

import java.security.spec.InvalidKeySpecException;
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 final String KEY_ALGORITHM = "AES";
    private static final String DER_ALGORITHM = "PBKDF2WithHmacSHA1";
    private static final int KEY_LENGTH = 128;
    private static final int ITERATION_COUNT = 1000;

     static SecretKey deriveKeyFromPassword(String password)
            throws NoSuchAlgorithmException, InvalidKeySpecException {
        SecretKeyFactory f = SecretKeyFactory.getInstance(DER_ALGORITHM);
        KeySpec ks = new PBEKeySpec(password.toCharArray(),
                "salt0123456789yo".getBytes(), ITERATION_COUNT, KEY_LENGTH);
        byte[] keyBytes = f.generateSecret(ks).getEncoded();
        return new SecretKeySpec(keyBytes, KEY_ALGORITHM);
    }// w ww .j  ava2 s. co  m
}

Related Tutorials