aes 加密 解密with salt

aes加密with salt  ,可变输出密文, 密度更高级别,现在没有实际使用。

package util;

import java.security.SecureRandom;
import java.security.spec.KeySpec;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import android.annotation.SuppressLint;
import android.util.Base64;

public class CipherADesSalt {
	final static	int interationCount = 1000;
	final static 	int keyLength = 256;
	final static 	int saltLenth = keyLength;
	
	private byte mSalt[];
	private byte mIvi[];
	@SuppressLint("TrulyRandom")
	public String encrypt(String plaintext,String password) throws Exception{	
		SecureRandom random = new SecureRandom();
		byte[] salt = new byte[saltLenth];
		random.nextBytes(salt);
		KeySpec keySpec = new PBEKeySpec(password.toCharArray(),salt,interationCount,keyLength);
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
		byte[] keyBytes = keyFactory.generateSecret(keySpec).getEncoded();
		SecretKey key = new SecretKeySpec(keyBytes, "AES");
		
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
		byte[] iv = new byte[cipher.getBlockSize()];
		random.nextBytes(iv);
		IvParameterSpec ivParams = new IvParameterSpec(iv);
		cipher.init(Cipher.ENCRYPT_MODE,key,ivParams);
		byte[] ciphertext = cipher.doFinal(plaintext.getBytes("UTF-8"));
		
		mSalt = salt;
		mIvi = iv;
		
		return Base64.encodeToString(ciphertext, Base64.DEFAULT);
	}
	
	public byte[] getDecrySalt(){
		return mSalt;
	}
	
	public byte[] getDecryIvi(){
		return mIvi;
	}
	
    public String decrypt(String encry,String password,byte salt[],byte ivi[]) throws Exception{    			
		KeySpec keySpec = new PBEKeySpec(password.toCharArray(),salt,interationCount,keyLength);
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
		byte[] keyBytes = keyFactory.generateSecret(keySpec).getEncoded();
		SecretKey key = new SecretKeySpec(keyBytes, "AES");			
	
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");		
		IvParameterSpec ivParams2 = new IvParameterSpec(ivi);
		cipher.init(Cipher.DECRYPT_MODE,key,ivParams2);
		
		
		byte decry[] = cipher.doFinal(Base64.decode(encry, Base64.DEFAULT));
		return new String(decry,"UTF-8");
    }
}

 

你可能感兴趣的:(加密,aes,SALT)