fs.readFile(
'./downsuccess/'
+name+
''
, {flag:
'r+'
, encoding:
''
},
function
(err, data) {
console.log(
'讀取中'
)
if
(err) {
return
;
}
let b =
new
Buffer(data);
let c = b.toString(
'hex'
);
let cipherBuffer = _this.cipher(data);
fs.writeFile(
'./downsuccess/'
+name+
''
,cipherBuffer,[],
function
(){
console.log(`${name}加密完成`);
_this.downAll(_this.downList,_this.downCall)
})
});
export
function
cipher (buf) {
var
encrypted =
""
;
var
cip = crypto.createCipher(
'rc4'
,
'密匙'
);
encrypted += cip.update(buf,
'hex'
,
'hex'
);
encrypted += cip.final(
'hex'
);
return
encrypted
};
Node.js加解密
無論加密解密、字符轉換,都需要使用byte,而node對byte的支持不如其他語言(如c/java,可以直接使用byte[]
)方便快捷,但是也有模塊對byte提供支持。
node對byte處理的支持
Buffer
Buffer支持很多格式轉換(Ascii, urf8, usc2, utf16le, base64, binary, hex),傳入字符串可以直接進行格式轉換:
new Buffer(size); // with size
new Buffer(array) // with array
new Buffer(str[, encoding]) // with string[, encoding = 'utf8']
- write
Buffer寫可以直接使用[index]
來寫入,也可以使用方法.write
buf.write(string[, offset][, length][, encoding])
buf.writeIntLE(value, offset, byteLength[, noAssert])
... - read
Buffer讀可以直接使用[index]
來讀取,也可以使用方法.read
buf.readUInt8(offset[, noAssert])
buf.readInt8(offset[, noAssert])
...
Int*Array
構造函數如下(都是一樣的),因此不能直接傳入字符串:
Int8Array(bufferOrArrayOrLength,byteOffset,length)
使用Buffer可以直接將字符串轉為HEX,使用Int8Array可以直接轉換為標准byte(-128 ~ 127)數組:
// hex: 41 ~ 5A
var UPPER = new Int8Array(new Buffer('ABCDEFGHIJKLMNOPQRSTUVWXYZ'));
// hex: 61 ~ 7A
var lower = new Int8Array(new Buffer('abcdefghijklmnopqrstuvwxyz0123456789'));
// hex: 30 ~ 39
var number = new Int8Array(new Buffer('0123456789'));
如果使用Uint8Array,則轉換為無符號的byte(0 ~ 255)數組:
var u = new Uint8Array(new Buffer('123456'));
使用的第三模塊
forge -
npm install node-forge --save
froge Buffer
使用forge,加解密byte數據都需要使用forge.util.ByteStringBuffer
。
可以通過方法forge.util.createBuffer()
來創建一個新的Buffer。
// put, get
util.ByteStringBuffer.prototype.putByte = function(b)
util.ByteStringBuffer.prototype.getByte = function()
...
util.ByteStringBuffer.prototype.at = function(i)
Buffer內部有兩個游標,read cursor和write cursor,只用put和get均會使游標前進,使用.at(i)
可以不影響游標而直接獲取相應的值。
rsa
生成KeyPair:
var rsa = forge.pki.rsa;
// generate an RSA key pair synchronously
var keypair = rsa.generateKeyPair({bits: 2048, e: 0x10001});
// generate an RSA key pair asynchronously (uses web workers if available)
// use workers: -1 to run a fast core estimator to optimize # of workers
rsa.generateKeyPair({bits: 2048, workers: 2}, function(err, keypair) {
// keypair.privateKey, keypair.publicKey
});
使用
// encrypt data with a public key using RSAES-OAEP/SHA-256/MGF1-SHA-1
// compatible with Java's RSA/ECB/OAEPWithSHA-256AndMGF1Padding
var encrypted = publicKey.encrypt(bytes, 'RSA-OAEP', {
md: forge.md.sha256.create(),
mgf1: {
md: forge.md.sha1.create()
}
});
// decrypt data with a private key using RSAES-OAEP/SHA-256/MGF1-SHA-1
// compatible with Java's RSA/ECB/OAEPWithSHA-256AndMGF1Padding
var decrypted = privateKey.decrypt(encrypted, 'RSA-OAEP', {
md: forge.md.sha256.create(),
mgf1: {
md: forge.md.sha1.create()
}
});
通過已經生成的key(asn1格式)來生成Key對象
// public key
var key = forge.asn1.fromDer(pubKey);
var publicKey = forge.pki.publicKeyFromAsn1(key);
// private key
var key = forge.asn1.fromDer(priKey);
var privateKey = forge.pki.privateKeyFromAsn1(key);
生成Key對象后解密
/**
* @param ed the encrypted data to decrypt in as a byte string.
* @param key the RSA key to use.
* @param pub true for a public key operation, false for private.
* @param ml the message length, if known, false to disable padding.
*
* @return the decrypted message as a byte string.
*/
pki.rsa.decrypt = function(ed, key, pub, ml)
解密后的字符串實際上是
util.ByteStringBuffer.prototype.getBytes = function() {...}
aes
aes通過forge.cipher.createCipher('AES-ECB', key)
來創建cipher使用(JAVA中AES
對應的即是AES-ECB
)。
// decrypt aes, aesKey[ByteStringBuffer]
var aesCipher = forge.cipher.createDecipher('AES-ECB', aesKey);
aesCipher.start();
aesCipher.update(encryptedData);
if (!aesCipher.finish()) {
throw new Error('decrypt error');
}
var decryptData = aesCipher.output;
md5
// verify md5
var md = forge.md.md5.create();
md.update(decryptData);
var mdToVerify = md.digest();
感謝: http://www.jianshu.com/p/85f152944527