hash例子

hash.digest([encoding]):计算摘要。encoding可以是、latin1或者base64。如果声明了encoding,那么返回字符串。否则,返回Buffer实例。注意,调用hash.digest()后,hash对象就作废了,再次调用就会出错。

hash.update(data[, input_encoding]):input_encoding可以是utf8ascii或者latin1。如果data是字符串,且没有指定 input_encoding,则默认是utf8。注意,hash.update()方法可以调用多次。

也可以这样:

  1. var crypto = require('crypto');
  2. var fs = require('fs');
  3. var input = fs.createReadStream('./test.txt', {encoding: 'utf8'});
  4. var hash = crypto.createHash('sha256');
  5. hash.setEncoding('hex');
  6. input.pipe(hash).pipe(process.stdout)
  7. // 输出内容为:
  8. // b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9

hash.digest()后,再次调用digest()或者update()

  1. var crypto = require('crypto');
  2. var fs = require('fs');
  3. var content = fs.readFileSync('./test.txt', {encoding: 'utf8'});
  4. var hash = crypto.createHash('sha256');
  5. var output;
  6. hash.update(content);
  7. hash.digest('hex');
  8. // 报错:Error: Digest already called
  9. hash.update(content);
  10. // 报错:Error: Digest already called
  11. hash.digest('hex');

HMAC例子

HMAC的全称是Hash-based Message Authentication Code,也即在hash的加盐运算。

算法细节可以参考附录链接,具体到使用的话,跟hash模块差不多,选定hash算法,指定“盐”即可。

例子1:

例子2:

  1. var crypto = require('crypto');
  2. var fs = require('fs');
  3. var secret = 'secret';
  4. var hmac = crypto.createHmac('sha256', secret);
  5. var input = fs.createReadStream('./test.txt', {encoding: 'utf8'});
  6. hmac.setEncoding('hex');
  7. // 输出:
  8. // 734cc62f32841568f45715aeb9f4d7891324e6d948e4c6c60c0621cdac48623a

加解密主要用到下面两组方法:

加密:

  • crypto.createCipher(algorithm, password)
  • crypto.createCipheriv(algorithm, key, iv)

解密:

  • crypto.createDecipher(algorithm, password)
  • crypto.createDecipheriv(algorithm, key, iv)

先来看下 crypto.createCipher(algorithm, password),两个参数分别是加密算法、密码

  • algorithm:加密算法,比如aes192,具体有哪些可选的算法,依赖于本地openssl的版本,可以通过openssl list-cipher-algorithms命令查看支持哪些算法。
  • password:用来生成密钥(key)、初始化向量(IV)。

备注:这里nodejs屏蔽了AES的使用/实现细节,关于key、IV,感兴趣的同学可以自行谷歌下。

  1. var crypto = require('crypto');
  2. var secret = 'secret';
  3. var cipher = crypto.createCipher('aes192', secret);
  4. var content = 'hello';
  5. var cryptedContent;
  6. cipher.update(content);
  7. cryptedContent = cipher.final('hex');
  8. console.log(cryptedContent);
  9. // 输出:
  10. // 71d30ec9bc926b5dbbd5150bf9d3e5fb

可以看作 crypto.createCipher(algorithm, password) 逆向操作,直接看例子

相对于 crypto.createCipher() 来说,crypto.createCipheriv() 需要提供keyiv,而 crypto.createCipher() 是根据用户提供的 password 算出来的。

key、iv 可以是Buffer,也可以是utf8编码的字符串,这里需要关注的是它们的长度:

  • key:根据选择的算法有关,比如 aes128、aes192、aes256,长度分别是128、192、256位(16、24、32字节)
  • iv:都是128位(16字节)
  1. var crypto = require('crypto');
  2. var key = crypto.randomBytes(192/8);
  3. var iv = crypto.randomBytes(128/8);
  4. var algorithm = 'aes192';
  5. function encrypt(text){
  6. var cipher = crypto.createCipheriv(algorithm, key, iv);
  7. cipher.update(text);
  8. return cipher.final('hex');
  9. }
  10. function decrypt(encrypted){
  11. var decipher = crypto.createDecipheriv(algorithm, key, iv);
  12. decipher.update(encrypted, 'hex');
  13. return decipher.final('utf8');
  14. }
  15. var content = 'hello';
  16. var crypted = encrypt('hello');
  17. console.log( crypted );
  18. console.log( decrypted ); // 输出:utf8

数字签名/签名校验

假设:

1、服务端原始信息为M,摘要算法为Hash,Hash(M)得出的摘要是H。
2、公钥为Pub,私钥为Piv,非对称加密算法为Encrypt,非对称解密算法为Decrypt。
3、Encrypt(H)得到的结果是S。
4、客户端拿到的信息为M1,利用Hash(M1)得出的结果是H1。

数字签名的产生、校验步骤分别如下:

1、数字签名的产生步骤:利用摘要算法Hash算出M的摘要,即Hash(M) == H,利用非对称加密算法对摘要进行加密Encrypt( H, Piv ),得到数字签名S。
2、数字签名的校验步骤:利用解密算法D对数字签名进行解密,即Decrypt(S) == H,计算M1的摘要 Hash(M1) == H1,对比 H、H1,如果两者相同,则通过校验。

私钥如何生成不是这里的重点,这里采用网上的服务来生成,点击。

  1. var fs = require('fs');
  2. var privateKey = fs.readFileSync('./private-key.pem'); // 私钥
  3. var publicKey = fs.readFileSync('./public-key.pem'); // 公钥
  4. var algorithm = 'RSA-SHA256'; // 加密算法 vs 摘要算法
  5. // 数字签名
  6. function sign(text){
  7. var sign = crypto.createSign(algorithm);
  8. sign.update(text);
  9. return sign.sign(privateKey, 'hex');
  10. }
  11. // 校验签名
  12. function verify(oriContent, signature){
  13. var verifier = crypto.createVerify(algorithm);
  14. verifier.update(oriContent);
  15. return verifier.verify(publicKey, signature, 'hex');
  16. }
  17. // 对内容进行签名
  18. var content = 'hello world';
  19. var signature = sign(content);
  20. console.log(signature);
  21. // 校验签名,如果通过,返回true
  22. var verified = verify(content, signature);
  23. console.log(verified);

DiffieHellman

DiffieHellman:Diffie–Hellman key exchange,缩写为D-H,是一种安全协议,让通信双方在预先没有对方信息的情况下,通过不安全通信信道,创建一个密钥。这个密钥可以在后续的通信中,作为对称加密的密钥加密传递的信息。

代码如下,原理待补充 TODO

代码如下,原理待补充 TODO

  1. const crypto = require('crypto');
  2. const assert = require('assert');
  3. // Generate Alice's keys...
  4. const alice = crypto.createECDH('secp521r1');
  5. const alice_key = alice.generateKeys();
  6. // Generate Bob's keys...
  7. const bob = crypto.createECDH('secp521r1');
  8. const bob_key = bob.generateKeys();
  9. // Exchange and generate the secret...
  10. const alice_secret = alice.computeSecret(bob_key);
  11. const bob_secret = bob.computeSecret(alice_key);
  12. // OK

证书

SPKAC:

SPKI:Simple public-key infrastructure

关键点

md5:固定长度(128bit)、不可逆(重要)、不同数据的散列值可能相同(重要)、高度离散型(原文细微的变化,会导致散列值差异巨大)

sha1:固定长度160bit,广泛使用(如TLS,目前安全性受到密码学家的质疑)

SHA-256/SHA-384/SHA-512:后面表示摘要的长度。

用途:数字签名、文件完整性校验

关系:sha1 基于 MD5,MD5 基于 MD4

md5(1991) -> SHA1

sha家族:由美国国家安全局(NSA)所设计,并由美国国家标准与技术研究院(NIST)发布;是美国的政府标准。

SPKAC:Signed Public Key and Challenge

MD5:Message-Digest Algorithm 5,信息-摘要算法。

SHA:Secure Hash Algorithm,安全散列算法。

HMAC:Hash-based Message Authentication Code,密钥相关的哈希运算消息认证码。

SPKAC:

对称加密:比如AES、DES

非对称加密:比如RSA、DSA

AES:Advanced Encryption Standard(高级加密标准),密钥长度可以是128、192和256位。

DiffieHellman:Diffie–Hellman key exchange,缩写为D-H,是一种安全协议,让通信双方在预先没有对方信息的情况下,通过不安全通信信道,创建一个密钥。这个密钥可以在后续的通信中,作为对称加密的密钥加密传递的信息。(备注,使是用协议的发明者命名)

相关链接

字符编码笔记:ASCII,Unicode和UTF-8 - 阮一峰的网络日志
http://www.ruanyifeng.com/blog/2007/10/ascii_unicode_and_utf-8.html

Unicode与JavaScript详解

Base64笔记
http://www.ruanyifeng.com/blog/2008/06/base64.html

MIME笔记

SHA家族
https://zh.wikipedia.org/wiki/SHA%E5%AE%B6%E6%97%8F

加盐密码哈希:如何正确使用

HMAC-MD5算法原理及实现
http://www.jianshu.com/p/067f9eb6b252

Encrypting using AES-256, can I use 256 bits IV?

分组对称加密模式:ECB/CBC/CFB/OFB
http://blog.csdn.net/aaaaatiger/article/details/2525561

在线生成非对称加密公钥私钥对、在线生成公私钥对、RSA Key pair create、生成RSA密钥对

Diffie–Hellman key exchange
https://zh.wikipedia.org/wiki/%E8%BF%AA%E8%8F%B2-%E8%B5%AB%E7%88%BE%E6%9B%BC%E5%AF%86%E9%91%B0%E4%BA%A4%E6%8F%9B

理解 Deffie-Hellman 密钥交换算法

What is the difference between DHE and ECDH?
http://stackoverflow.com/questions/2701294/how-does-the-elliptic-curve-version-of-diffie-hellman-cryptography-work?rq=1

Example application for working with SPKAC (signed public key & challege) data coming from the element.

Using Padding in Encryption
http://www.di-mgt.com.au/cryptopad.html#randompadding

对称加密和分组加密中的四种模式(ECB、CBC、CFB、OFB)

分组密码工作模式
https://zh.wikipedia.org/wiki/%E5%88%86%E7%BB%84%E5%AF%86%E7%A0%81%E5%B7%A5%E4%BD%9C%E6%A8%A1%E5%BC%8F#.E5.AF.86.E7.A0.81.E5.9D.97.E9.93.BE.E6.8E.A5.EF.BC.88CBC.EF.BC.89

为什么说密文链接模式已经丧失安全性?

Elliptic Curve Cryptography: a gentle introduction
http://andrea.corbellini.name/2015/05/17/elliptic-curve-cryptography-a-gentle-introduction/

Elliptic Curve Cryptography: ECDH and ECDSA