Java SecureRandom create "SHA1PRNG" instance

Description

Java SecureRandom create "SHA1PRNG" instance


//package com.demo2s;

import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class Main {


    public static String aesDecrypt(String cipherText, String key) {
        try {//from   w w w .  ja  v  a  2s  .  c  om
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(key.getBytes());
            kgen.init(128, secureRandom);
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec keySpec = new SecretKeySpec(enCodeFormat, "AES");
            Cipher aes = Cipher.getInstance("AES");
            aes.init(2, keySpec);
            return new String(aes.doFinal(hex2byte(cipherText)));
        } catch (Exception e) {
            throw new RuntimeException("failed", e);
        }
    }

    public static byte[] hex2byte(String hex) {
        if (hex.length() < 1) {
            return null;
        }
        byte[] result = new byte[hex.length() / 2];
        for (int i = 0; i < hex.length() / 2; i++) {
            int high = Integer.parseInt(hex.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hex.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = ((byte) (high * 16 + low));
        }
        return result;
    }
}



PreviousNext

Related