Java 常用的 4 种加密方式

一、工具类

 md5 加密工具类

public class MD5Utils  

    private static final String hexDigIts[] = {“0″,”1″,”2″,”3″,”4″,”5″,”6″,”7″,”8″,”9″,”a”,”b”,”c”,”d”,”e”,”f”};

    /**

     * MD5 加密

     * @param origin 字符

     * @param charsetname 编码

     * @return

     */

    public static String MD5Encode(String origin, String charsetname){

        String resultString = null;

        try{

            resultString = new String(origin);

            MessageDigest md = MessageDigest.getInstance(“MD5”);

            if(null == charsetname || “”.equals(charsetname)){

                resultString = byteArrayToHexString(md.digest(resultString.getBytes()));

            }else{

                resultString = byteArrayToHexString(md.digest(resultString.getBytes(charsetname)));

            }

        }catch (Exception e){

        }

        return resultString;

    }

    public static String byteArrayToHexString(byte b[]){

        StringBuffer resultSb = new StringBuffer();

        for(int i = 0; i < b.length; i++){

            resultSb.append(byteToHexString(b[i]));

        }

        return resultSb.toString();

    }

    public static String byteToHexString(byte b){

        int n = b;

        if(n < 0){

            n += 256;

        }

        int d1 = n / 16;

        int d2 = n % 16;

        return hexDigIts[d1] + hexDigIts[d2];

    }

}

Java MD5 哈希示例

public class SimpleMD5Example

{

    public static void main(String[] args)

    {

        String passwordToHash = “password”;

        String generatedPassword = null;

        try {

            // Create MessageDigest instance for MD5

            MessageDigest md = MessageDigest.getInstance(“MD5”);

            //Add password bytes to digest

            md.update(passwordToHash.getBytes());

            //Get the hash’s bytes

            byte[] bytes = md.digest();

            //This bytes[] has bytes in decimal format;

            //Convert it to hexadecimal format

            StringBuilder sb = new StringBuilder();

            for(int i=0; i< bytes.length ;i++)

            {

                sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));

            }

            //Get complete hashed password in hex format

           generatedPassword = sb.toString();

        }

        catch (NoSuchAlgorithmException e)

        {

            e.printStackTrace();

       }

        System.out.println(generatedPassword);

    }

}

尽管MD5 是一种广泛使用的散列算法,但远非安全, MD5 会产生相当弱的哈希值。它的主要优点是速度快,易于实施。但这也意味着它容易受到 蛮力和字典攻击。

生成单词和散列的彩虹表允许非常快速地搜索已知散列并获得原始单词。

MD5 不是抗冲突的,这意味着不同的密码最终会导致相同的哈希。

今天,如果您在应用程序中使用MD5 哈希,请考虑在安全性中添加一些盐。

使用salt 使 MD5 更安全

请记住,添加盐不是MD5 特定的。您也可以将其添加到其他算法中。因此,请关注它的应用方式,而不是它与 MD5 的关系。

维基百科将salt 定义为随机数据,用作哈希密码或密码短语的单向函数的附加输入。更简单的说, salt 是一些随机生成的文本,在获取哈希值之前会附加到密码中。

salting 的最初意图主要是打败预先计算的彩虹表攻击,否则可以用来大大提高数据库的效率。现在更大的好处是减慢并行操作,将一次密码猜测的哈希值与多个密码哈希值进行比较。

重要提示:我们总是需要使用SecureRandom 来创建好的盐,而在 Java 中, SecureRandom 类支持“ SHA1PRNG ”伪随机数生成器算法,我们可以利用它。

如何为Hash 生成 Salt

让我们看看应该如何生成盐。

private static byte[] getSalt() throws NoSuchAlgorithmException

{

    //Always use a SecureRandom generator

    SecureRandom sr = SecureRandom.getInstance(“SHA1PRNG”);

    //Create array for salt

    byte[] salt = new byte[16];

    //Get a random salt

    sr.nextBytes(salt);

    //return salt

    return salt;

}

SHA1PRNG 算法用作基于 SHA-1 消息摘要算法的加密强伪随机数生成器。请注意,如果未提供种子,它将从真正的随机数生成器( TRNG )生成种子。

Java MD5 与盐的例子

现在,让我们看看修改后的MD5 哈希示例:

public class SaltedMD5Example

{

    public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchProviderException

    {

        String passwordToHash = “password”;

        byte[] salt = getSalt();

        String securePassword = getSecurePassword(passwordToHash, salt);

        System.out.println(securePassword); //Prints 83ee5baeea20b6c21635e4ea67847f66  

        String regeneratedPassowrdToVerify = getSecurePassword(passwordToHash, salt);

        System.out.println(regeneratedPassowrdToVerify); //Prints 83ee5baeea20b6c21635e4ea67847f66

    }

private static String getSecurePassword(String passwordToHash, byte[] salt)

    {

        String generatedPassword = null;

        try {

            // Create MessageDigest instance for MD5

            MessageDigest md = MessageDigest.getInstance(“MD5”);

            //Add password bytes to digest

            md.update(salt);

            //Get the hash’s bytes

            byte[] bytes = md.digest(passwordToHash.getBytes());

            //This bytes[] has bytes in decimal format;

            //Convert it to hexadecimal format

            StringBuilder sb = new StringBuilder();

            for(int i=0; i< bytes.length ;i++)

            {

                sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));

            }

            //Get complete hashed password in hex format

            generatedPassword = sb.toString();

        }

        catch (NoSuchAlgorithmException e) {

           e.printStackTrace();

        }

        return generatedPassword;

    }

    //Add salt

    private static byte[] getSalt() throws NoSuchAlgorithmException, NoSuchProviderException

    {

        //Always use a SecureRandom generator

        SecureRandom sr = SecureRandom.getInstance(“SHA1PRNG”, “SUN”);

        //Create array for salt

        byte[] salt = new byte[16];

        //Get a random salt

        sr.nextBytes(salt);

        //return salt

        return salt;

    }

}

重要提示:请注意,现在您必须为您散列的每个密码存储此salt 值。因为当用户在系统中重新登录时,必须仅使用最初生成的 salt 再次创建哈希以匹配存储的哈希。如果使用不同的外汇返佣http://www.kaifx.cn/盐(我们生成随机盐),则生成的散列将不同。

此外,您可能听说过疯狂散列和腌制这个术语。它通常指创建自定义组合。

base64 加密工具类

public class Base64Util {

    // 字符串编码

    private static final String UTF_8 = “UTF-8”;

    /**

     * 加密字符串

     * @param inputData

     * @return

     */

    public static String decodeData(String inputData) {

        try {

            if (null == inputData) {

                return null;

            }

            return new String(Base64.decodeBase64(inputData.getBytes(UTF_8)), UTF_8);

        } catch (UnsupportedEncodingException e) {

        }

        return null;

    }

    /**

     * 解密加密后的字符串

     * @param inputData

     * @return

     */

    public static String encodeData(String inputData) {

        try {

            if (null == inputData) {

                return null;

            }

            return new String(Base64.encodeBase64(inputData.getBytes(UTF_8)), UTF_8);

        } catch (UnsupportedEncodingException e) {

        }

        return null;

    }

    public static void main(String[] args) {

        System.out.println(Base64Util.encodeData(” 我是中文 “));

        String enStr = Base64Util.encodeData(” 我是中文 “);

        System.out.println(Base64Util.decodeData(enStr));

    }

}

 Bcrypt 工具类

public class BcryptCipher {

  // generate salt seed

  private static final int SALT_SEED = 12;

  // the head fo salt

  private static final String SALT_STARTSWITH = “$2a$12”;

  public static final String SALT_KEY = “salt”;  

  public static final String CIPHER_KEY = “cipher”;

  /**

   * Bcrypt encryption algorithm method

   * @param encryptSource

   * need to encrypt the string

   * @return Map , two values in Map , salt and cipher

   */

  public static Map<String, String> Bcrypt(final String encryptSource) {

    String salt = BCrypt.gensalt(SALT_SEED);

    Map<String, String> bcryptResult = Bcrypt(salt, encryptSource);

    return bcryptResult;

  }

  /**

   *

   * @param salt encrypt salt, Must conform to the rules

   * @param encryptSource

   * @return

   */

  public static Map<String, String> Bcrypt(final String salt, final String encryptSource) {

    if (StringUtils.isBlank(encryptSource)) {

      throw new RuntimeException(“Bcrypt encrypt input params can not be empty”);

    }

    if (StringUtils.isBlank(salt) || salt.length() != 29) {

      throw new RuntimeException(“Salt can’t be empty and length must be to 29”);

    }

    if (!salt.startsWith(SALT_STARTSWITH)) {

      throw new RuntimeException(“Invalid salt version, salt version is $2a$12”);

    }

    String cipher = BCrypt.hashpw(encryptSource, salt);

    Map<String, String> bcryptResult = new HashMap<String, String>();

    bcryptResult.put(SALT_KEY, salt);

    bcryptResult.put(CIPHER_KEY, cipher);

    return bcryptResult;

  }

}

二、加密测试

MD5 加密测试

/**

 * MD5 加密

 */

public class MD5Test {

  public static void main(String[] args) {

    String string = ” 你好 世界 “;

    String byteArrayToHexString = MD5Utils.byteArrayToHexString(string.getBytes());

    System.out.println(byteArrayToHexString);//e68891e698afe4b880e58fa5e8af9d

  }

}

base64 加密测试

/**

 * base64 加密

 */

public class Bast64Tester {

  public static void main(String[] args) {

    String string = ” 你好 世界 “;

    String encodeData = Base64Util.encodeData(string); // 加密

    String decodeData = Base64Util.decodeData(encodeData); // 解密

    System.out.println(encodeData);//5oiR5piv5LiA5Liq5a2X56ym5Liy

    System.out.println(decodeData);// 你好 世界

  }

}

SHA 加密测试

/**

 * SHA 加密

 */

public class ShaTest {

  public static void main(String[] args) {

    String string = ” 你好 世界 “;

    String sha256Crypt = Sha2Crypt.sha256Crypt(string.getBytes());   System.out.println(sha256Crypt);//$5$AFoQTeyt$TiqmobvcQXjXaAQMYosAAO4KI8LfigZMGHzq.Dlp4NC

  }

}

BCrypt 加密测试

/**

 * BCrypt 加密

 */

public class BCryptTest {

  public static void main(String[] args) {

    String string = ” 你好世界 “;

    Map<String, String> bcrypt = BcryptCipher.Bcrypt(string);

    System.out.println(bcrypt.keySet()); //[cipher, salt]

    System.out.println(bcrypt.get(“cipher”)); //$2a$12$ylb92Z84gqlrSfzIztlCV.dK0xNbw.pOv3UwXXA76llOsNRTJsE/.

    System.out.println(bcrypt.get(“salt”)); //$2a$12$ylb92Z84gqlrSfzIztlCV.

    Map<String, String> bcrypt2 = BcryptCipher.Bcrypt(bcrypt.get(“salt”),string);

    System.out.println(bcrypt2.get(“SALT_KEY”)); //null

    System.out.println(bcrypt2.get(“CIPHER_KEY”)); //null

  }

}

    原文作者:蝴蝶飞啊飞
    原文地址: http://blog.itpub.net/69946279/viewspace-2661081/
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞