MCPcopy Create free account
hub / github.com/mscdex/ssh2 / decrypt

Method decrypt

lib/protocol/crypto.js:637–753  ·  view source on GitHub ↗
(data, p, dataLen)

Source from the content-addressed store, hash-verified

635 }
636 free() {}
637 decrypt(data, p, dataLen) {
638 // `data` === encrypted data
639
640 while (p < dataLen) {
641 // Read packet length
642 if (this._lenPos < 4) {
643 let nb = Math.min(4 - this._lenPos, dataLen - p);
644 while (nb--)
645 this._lenBuf[this._lenPos++] = data[p++];
646 if (this._lenPos < 4)
647 return;
648
649 POLY1305_OUT_COMPUTE[0] = 0; // Set counter to 0 (little endian)
650 writeUInt32BE(POLY1305_OUT_COMPUTE, this.inSeqno, 12);
651
652 const decLenBytes =
653 createDecipheriv('chacha20', this._decKeyPktLen, POLY1305_OUT_COMPUTE)
654 .update(this._lenBuf);
655 this._len = readUInt32BE(decLenBytes, 0);
656
657 if (this._len > MAX_PACKET_SIZE
658 || this._len < 8
659 || (this._len & 7) !== 0) {
660 throw new Error('Bad packet length');
661 }
662 }
663
664 // Read padding length, payload, and padding
665 if (this._pktLen < this._len) {
666 if (p >= dataLen)
667 return;
668 const nb = Math.min(this._len - this._pktLen, dataLen - p);
669 let encrypted;
670 if (p !== 0 || nb !== dataLen)
671 encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb);
672 else
673 encrypted = data;
674 if (nb === this._len) {
675 this._packet = encrypted;
676 } else {
677 if (!this._packet)
678 this._packet = Buffer.allocUnsafe(this._len);
679 this._packet.set(encrypted, this._pktLen);
680 }
681 p += nb;
682 this._pktLen += nb;
683 if (this._pktLen < this._len || p >= dataLen)
684 return;
685 }
686
687 // Read Poly1305 MAC
688 {
689 const nb = Math.min(16 - this._macPos, dataLen - p);
690 // TODO: avoid copying if entire MAC is in current chunk
691 if (p !== 0 || nb !== dataLen) {
692 this._mac.set(
693 new Uint8Array(data.buffer, data.byteOffset + p, nb),
694 this._macPos

Callers

nothing calls this directly

Calls 3

writeUInt32BEFunction · 0.85
readUInt32BEFunction · 0.85
updateMethod · 0.80

Tested by

no test coverage detected