Skip to content

Comments

Partial fix for #45#119

Open
guptasanchit90 wants to merge 2 commits intotravist:masterfrom
guptasanchit90:master
Open

Partial fix for #45#119
guptasanchit90 wants to merge 2 commits intotravist:masterfrom
guptasanchit90:master

Conversation

@guptasanchit90
Copy link

Decrypt Base64(from bytes) / Binary data

To convert this to Base64 string use the following code

private static toBase64FromDecryptedByteData(decryptedByteData: any){
    return this.toBase64StringFromBytes(this.toBytesGromBinaryString(this.toBinayFromString(decryptedByteData)));
  }

  private static toBinayFromString(str) {
    function zeroPad(num) {
      return '00000000'.slice(String(num).length) + num
    }

    return str.replace(/[\s\S]/g, function(message) {
      message = zeroPad(message.charCodeAt(0).toString(2))

      return message
    })
  }

  private static toBytesGromBinaryString(message) {
    if (message.length % 8 > 0) {
      message = ('0000000' + message).substr(message.length % 8 - 1)
    }
    const bytes = this.chunk(message, 8).map((byteString, index) => {
      return parseInt(byteString, 2)
    })

    return new Uint8Array(bytes)
  }

  private static chunk(message, length) {
    return message !== '' ? message.match(new RegExp(`.{1,${length}}`, 'g')) : []
  }

  private static toBase64StringFromBytes(bytes) {
    const options = {
      label: "Standard 'base64' (RFC 3548, RFC 4648)",
      alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' + '+/',
      padCharacter: '=',
      padCharacterOptional: false,
      foreignCharactersForbidden: true,
    }
    const alphabet = options.alphabet
    const padCharacter = !options.padCharacterOptional && options.padCharacter ? options.padCharacter : ''

    // encode each 3-byte-pair
    let message = ''
    let byte1
    let byte2
    let byte3
    let octet1
    let octet2
    let octet3
    let octet4

    for (let i = 0; i < bytes.length; i += 3) {
      // collect pair bytes
      byte1 = bytes[i]
      byte2 = i + 1 < bytes.length ? bytes[i + 1] : NaN
      byte3 = i + 2 < bytes.length ? bytes[i + 2] : NaN

      // bits 1-6 from byte 1
      octet1 = byte1 >> 2

      // bits 7-8 from byte 1 joined by bits 1-4 from byte 2
      octet2 = ((byte1 & 3) << 4) | (byte2 >> 4)

      // bits 4-8 from byte 2 joined by bits 1-2 from byte 3
      octet3 = ((byte2 & 15) << 2) | (byte3 >> 6)

      // bits 3-8 from byte 3
      octet4 = byte3 & 63

      // map octets to characters
      message +=
        alphabet[octet1] +
        alphabet[octet2] +
        (!isNaN(byte2) ? alphabet[octet3] : padCharacter) +
        (!isNaN(byte3) ? alphabet[octet4] : padCharacter)
    }

    return message
  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant