PBKDF2WithHmacSHA1算法-程序员宅基地

技术标签: c#  

     主要用于明文密码加密字符串存入数据库。由棱镜门思考。目前大部分企业中都是明文密码。一旦被攻破。危害非常大。现在主流加密技术是MD5加密。不过MD5的存在小概率碰撞(根据密码学的定义,如果内容不同的明文,通过散列算法得出的结果(密码学称为信息摘要)相同,就称为发生了“碰撞”。).如何生成md5碰撞的算法论文http://www.infosec.sdu.edu.cn/paper/md5-attack.pdf。一些黑客破获密码的方法是一种被称为“跑字典”的方法。有两种方法得到字典,一种是日常搜集的用做密码的字符串表,另一种是用排列组合方法生成的,先用MD5程序计算出这些字典项的MD5值,然后再用目标的MD5值在这个字典中检索。即使假设密码的最大长度为8,同时密码只能是字母和数字,共26+26+10=62个字符,排列组合出的字典的项数则是P(62,1)+P (62,2)….+P(62,8),那也已经是一个很天文的数字了,存储这个字典就需要TB级的磁盘组,而且这种方法还有一个前提,就是能获得目标账户的 密码MD5值的情况下才可以。当如果用户的密码是弱密码的就很危险了。

  PBKDF2WithHmacSHA1算法比MD5算法更安全。它可以同样密码在不同时间生成不同加密Hash。跑字典将无效。下面是算法Demo。

  1 package hashpassword;
  2 import java.security.SecureRandom;
  3 import javax.crypto.spec.PBEKeySpec;
  4 import javax.crypto.SecretKeyFactory;
  5 import java.math.BigInteger;
  6 import java.security.NoSuchAlgorithmException;
  7 import java.security.spec.InvalidKeySpecException;
  8 
  9 /*
 10  * PBKDF2 salted password hashing.
 11  * Author: havoc AT defuse.ca
 12  * www: http://crackstation.net/hashing-security.htm
 13  */
 14 public class PasswordHash
 15 {
 16     public static final String PBKDF2_ALGORITHM = "PBKDF2WithHmacSHA1";
 17 
 18     // The following constants may be changed without breaking existing hashes.
 19     public static final int SALT_BYTE_SIZE = 24;
 20     public static final int HASH_BYTE_SIZE = 24;
 21     public static final int PBKDF2_ITERATIONS = 10;
 22 
 23     public static final int ITERATION_INDEX = 0;
 24     public static final int SALT_INDEX = 1;
 25     public static final int PBKDF2_INDEX = 2;
 26 
 27     public static String createHash(String password)
 28         throws NoSuchAlgorithmException, InvalidKeySpecException
 29     {
 30         return createHash(password.toCharArray());
 31     }
 32 
 33     /**
 34      * Returns a salted PBKDF2 hash of the password.
 35      * 返回一个加盐后的PBKDF2哈希密码
 36      * @param   password    the password to hash
 37      * @return              a salted PBKDF2 hash of the password
 38      */
 39     public static String createHash(char[] password)
 40         throws NoSuchAlgorithmException, InvalidKeySpecException
 41     {
 42         // Generate a random salt 随即盐序列
 43         SecureRandom random = new SecureRandom();
 44         byte[] salt = new byte[SALT_BYTE_SIZE];
 45         random.nextBytes(salt);
 46 
 47         // Hash the password  生成哈希密码
 48         byte[] hash = pbkdf2(password, salt, PBKDF2_ITERATIONS, HASH_BYTE_SIZE);
 49         // format iterations:salt:hash 格式化 迭代次数:盐:哈希
 50         return PBKDF2_ITERATIONS + ":" + toHex(salt) + ":" +  toHex(hash);
 51     }
 52 
 53     /**
 54      * Validates a password using a hash.
 55      *
 56      * @param   password        the password to check
 57      * @param   correctHash     the hash of the valid password
 58      * @return                  true if the password is correct, false if not
 59      */
 60     public static boolean validatePassword(String password, String correctHash)
 61         throws NoSuchAlgorithmException, InvalidKeySpecException
 62     {
 63         return validatePassword(password.toCharArray(), correctHash);
 64     }
 65 
 66     /**
 67      * Validates a password using a hash.
 68      *
 69      * @param   password        the password to check
 70      * @param   correctHash     the hash of the valid password
 71      * @return                  true if the password is correct, false if not
 72      */
 73     public static boolean validatePassword(char[] password, String correctHash)
 74         throws NoSuchAlgorithmException, InvalidKeySpecException
 75     {
 76         // Decode the hash into its parameters
 77         String[] params = correctHash.split(":");
 78         int iterations = Integer.parseInt(params[ITERATION_INDEX]);
 79         byte[] salt = fromHex(params[SALT_INDEX]);
 80         byte[] hash = fromHex(params[PBKDF2_INDEX]);
 81         // Compute the hash of the provided password, using the same salt, 
 82         // iteration count, and hash length
 83         byte[] testHash = pbkdf2(password, salt, iterations, hash.length);
 84         // Compare the hashes in constant time. The password is correct if
 85         // both hashes match.
 86         return slowEquals(hash, testHash);
 87     }
 88 
 89     /**
 90      * Compares two byte arrays in length-constant time. This comparison method
 91      * is used so that password hashes cannot be extracted from an on-line 
 92      * system using a timing attack and then attacked off-line.
 93      * 
 94      * @param   a       the first byte array
 95      * @param   b       the second byte array 
 96      * @return          true if both byte arrays are the same, false if not
 97      */
 98     private static boolean slowEquals(byte[] a, byte[] b)
 99     {
100         int diff = a.length ^ b.length;
101         for(int i = 0; i < a.length && i < b.length; i++)
102             diff |= a[i] ^ b[i];
103         return diff == 0;
104     }
105 
106     /**
107      *  Computes the PBKDF2 hash of a password.
108      *  计算PBKDF2哈希密码
109      * @param   password    the password to hash.   需要加密的明文密码
110      * @param   salt        the salt                盐增加调味 增加密码破解难度
111      * @param   iterations  the iteration count (slowness factor)  迭代次数
112      * @param   bytes       the length of the hash to compute in bytes  计算密码后的 哈希长度
113      * @return              the PBDKF2 hash of the password
114      */
115     private static byte[] pbkdf2(char[] password, byte[] salt, int iterations, int bytes)
116         throws NoSuchAlgorithmException, InvalidKeySpecException
117     {
118         PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, bytes * 8);
119         SecretKeyFactory skf = SecretKeyFactory.getInstance(PBKDF2_ALGORITHM);
120         return skf.generateSecret(spec).getEncoded();
121     }
122 
123     /**
124      * Converts a string of hexadecimal characters into a byte array.
125      *
126      * @param   hex         the hex string
127      * @return              the hex string decoded into a byte array
128      */
129     private static byte[] fromHex(String hex)
130     {
131         byte[] binary = new byte[hex.length() / 2];
132         for(int i = 0; i < binary.length; i++)
133         {
134             binary[i] = (byte)Integer.parseInt(hex.substring(2*i, 2*i+2), 16);
135         }
136         return binary;
137     }
138 
139     /**
140      * Converts a byte array into a hexadecimal string.
141      *
142      * @param   array       the byte array to convert
143      * @return              a length*2 character string encoding the byte array
144      */
145     private static String toHex(byte[] array)
146     {
147         BigInteger bi = new BigInteger(1, array);
148         String hex = bi.toString(16);
149         int paddingLength = (array.length * 2) - hex.length();
150         if(paddingLength > 0) 
151             return String.format("%0" + paddingLength + "d", 0) + hex;
152         else
153             return hex;
154     }
155 
156     /**
157      * Tests the basic functionality of the PasswordHash class
158      *
159      * @param   args        ignored
160      */
161     public static void main(String[] args)
162     {
163         try
164         {
165             // Print out 10 hashes
166             for(int i = 0; i < 10; i++)
167                 System.out.println(PasswordHash.createHash("p\r\nassw0Rd!"));
168 
169             // Test password validation
170             boolean failure = false;
171             System.out.println("Running tests...");
172             for(int i = 0; i < 100; i++)
173             {
174                 String password = ""+i;
175                 String hash = createHash(password);
176                 String secondHash = createHash(password);
177                 if(hash.equals(secondHash)) {
178                     System.out.println("FAILURE: TWO HASHES ARE EQUAL!");
179                     failure = true;
180                 }
181                 String wrongPassword = ""+(i+1);
182                 if(validatePassword(wrongPassword, hash)) {
183                     System.out.println("FAILURE: WRONG PASSWORD ACCEPTED!");
184                     failure = true;
185                 }
186                 if(!validatePassword(password, hash)) {
187                     System.out.println("FAILURE: GOOD PASSWORD NOT ACCEPTED!");
188                     failure = true;
189                 }
190             }
191             if(failure)
192                 System.out.println("TESTS FAILED!");
193             else
194                 System.out.println("TESTS PASSED!");
195         }
196         catch(Exception ex)
197         {
198             System.out.println("ERROR: " + ex);
199         }
200     }
201 
202 }

 https://crackstation.net/hashing-security.htm

转载于:https://www.cnblogs.com/stay-9527/p/3665668.html

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_30896825/article/details/95363813

智能推荐

树莓派ubuntu:vscode remote-ssh免密登录(Mac)_树莓派怎么免密ssh连接-程序员宅基地

文章浏览阅读618次,点赞10次,收藏11次。Vscode remove-ssh远程开发很方便,但是每次登陆都会频繁要求输入密码,使用期间也会多次断开重连,提示再次输入密码。_树莓派怎么免密ssh连接

人工神经网络—多层神经网络_二层神经网络模型例子-程序员宅基地

文章浏览阅读5.4k次,点赞10次,收藏25次。多层神经网络1. 回顾2. 多层神经网络结构1. 回顾在上一讲中,我们提到从上个世纪80年代开始,人工神经网络领域迎来了新的突破,产生了多层神经网络,人们终于可以利用人工神经网络处理非线性问题了。2. 多层神经网络结构这一讲主要介绍多层神经网络的结构。下面这幅图是最简单的多层神经网络,它包含2层,总共由3个神经元相互连接而成。图1 两层神经网络例子输入XXX向量,有两个分量x1x_1x1​,x2x_2x2​,输出yyy是一个数值。我们逐层写出输入到输出之间的关系:  a1=ω11x1+ω12_二层神经网络模型例子

项目经理带你-零基础学习C++_新手学习笔记VS2010_1 项目3-黑客攻击系统-输入的优化-56.数组的概念和定义_vs2010定义数组-程序员宅基地

文章浏览阅读111次。/*项目经理带你-零基础学习C++_新手学习笔记VS2010_1项目3-黑客攻击系统-输入的优化-56.数组的概念和定义*/#include #include <Windows.h>#include //using namespace std;int main(){float girlFirends[8];girlFirends[5]=1.78;std::co..._vs2010定义数组

Navicat Premium实现mysql数据库备份/还原_navicat 还原mysql数据是否需要停服-程序员宅基地

文章浏览阅读1.7w次。转发请备注原文地址:https://www.niwoxuexi.com/blog/php/article/161.htm...Navicat Premium 是一个非常好用的数据库(支持 MySQL、SQLite、Oracle、SQL Server 及 PostgreSQL 等数据库)的图形化工具,今天我们主要是讲解如何用Navicat(Navicat Premium ,或者Navic_navicat 还原mysql数据是否需要停服

第三周:模型创建步骤与nn.Module_深度学习删除模块-程序员宅基地

文章浏览阅读917次。第三周:模型创建步骤与nn.Module1. 网络模型创建步骤例子:逐步执行观察预置的LeNet初始化Foward2. nn.Module2.1 nn.Module简介3. 模型容器(Containers)3.1 nn.Sequential (序列)3.1 nn.Sequential (OrderedDict)3.2 nn.ModuleList3.3 nn.ModuleDict例子:AlexNet4. 神经网络中常用的层4.1 nn.Conv2d4.2 转置卷积(Frantionally-Strided C_深度学习删除模块

从头开始学MySQL-------存储过程与存储函数(1)_mysql存储过程-程序员宅基地

文章浏览阅读6.2w次,点赞42次,收藏291次。10.1.1 创建存储过程 存储过程就是一条或者多条SQL语句的集合,可以视为批文件。它可以定义批量插入的语句,也可以定义一个接收不同条件的SQL。 创建存储过程的语句为 CREATE PROCEDURE,创建存储函数的语句为CREATE FUNCTION。 调用存储过程的语句为CALL。 调用存储函数的形式就像调用MyS......_mysql存储过程

随便推点

Sketch webView方式插件开发技术总结-程序员宅基地

文章浏览阅读354次。相信大家都对Sketch有一定的了解和认识。除了基础的矢量设计功能以外,插件更是让Sketch保持强大的独门秘籍。Sketch开放了第三方插件接口,设计师可以在几百种的插件中轻松找到适合自己工作方式的插件,并且他们都非常容易获得和安装。这里主要介绍使用Javascript API for Sketch开发Sketch插件。Sketch成为梦想中的“设计师工具箱”。但是每个人都..._sketch 插件 webview 调用接口

OnLineML:时序数据挖掘-程序员宅基地

文章浏览阅读158次。关于时序分析: 我们跟随时间的脚步,试图解释现在、理解过去、甚至预测未来........原文链接:http://blog.sciencenet.cn/home.php?mod=space&uid=34250&do=blog&id=287173简介: 时间序列是一种重要的高维数据类型,它是由客观..._a symbolic representation of time series, with implications for streaming al

Caused by: java.sql.SQLException: 无法转换为内部表示解决方法_在应用中使用hibernate进行开发的三种方式有-程序员宅基地

文章浏览阅读2.6k次。Hibernate应用有三种开发方式:自底向上从数据库到持久化类;自顶向下从持久化类到数据库表;从中间出发向上和向下同时发展。 如果从下往上开发,使用Database Explorer反向生成PO,其中的配置文件并不那么智能,比如如下规则NUMBER(1)~NUMBER(18) 都_在应用中使用hibernate进行开发的三种方式有

大容量nc文件解析_【MOT】对JDE的深度解析-程序员宅基地

文章浏览阅读583次。1 前言前面我们已经在目标追踪专栏发表了一些对单目标追踪(SOT)的论文和代码解读了,链接分别如下:周威:【SOT】siameseFC论文和代码解析​zhuanlan.zhihu.com周威:【SOT】Siamese RPN论文解读和代码解析​zhuanlan.zhihu.com周威:【SOT】Siamese RPN++ 论文和代码解析​zhuanlan.zhihu.com周威:【SOT】Siam..._ncjde

【RK3399】1.RK3399开发板基础配置_firefly开关rk3399-程序员宅基地

文章浏览阅读2.7k次,点赞2次,收藏7次。最近在小黄鱼入手了一个RK3399的开发板,RK的芯片我也是第一次使用。FireFly配套提供了完善的教程,可以在他们的WIKI上找到。上面有的内容就不在本文叙述了,大家可以参考教程https://wiki.t-firefly.com/zh_CN/Firefly-RK3399/linux_compile_gpt.html这篇文章主要如何对板子做一些基础的配置。_firefly开关rk3399

关于下载cuda和cudnn官方网站访问不了的替代方案_cuda官网打不开-程序员宅基地

文章浏览阅读1.6w次,点赞78次,收藏48次。一、背景最近一段时间在做深度学习Tensorflow2.x的项目,由于涉及到了docker环境下的tensorfow的GPU加速,于是我就在电脑(飞行堡垒)装双系统win10+ubuntu,后改成了win10上面装WSL(Win10的linux子系统)。由于前边装双系统的过程中系统出了一些问题,就重装了win10系统,之前装的cuda和cudnn也需要重装。无奈,国内访问Nvida的官网进不去,只能另寻他法二、访问Nvida网站下载cuda和cudnn方法探索1、通过腾讯云购买按量付费(_cuda官网打不开

推荐文章

热门文章

相关标签