IMAP UTF-7 conversion with native Javascript

446 Views Asked by At

I have been trying to get a handle on a good code that will provide Javascript for converting IMAP UTF7 mailboxes to JS to UTF-16 string. There seems to be no such work done. Anyone of you built one of these or have one available to share? I am happy to build one but didn't want to if there is someone who has it already.

As I look at the specs it looks like string between '&' and '-' is first decoded with base64 and then decoded as UTF-16 Big Endian, and the reverse process for encoding non-ascii text into UTF-16 portions and then base64. The base64 +/ is represented as +, for file safe operations instead of +_ in other cases.

Let me know if anyone has a solution and I will happy to use it or write one and put it in Github!

Thanks

Vijay

1

There are 1 best solutions below

0
On

I think I found a simple enough solution to this, as no one responded. Hopefully somebody finds this little script helpful for converting UTF7

>z='Συστήματα_Ανίχνευσης_Εισ & related security.pdf'
>encode_imap_utf7(z)
"&A6MDxQPDA8QDtwMBA7wDsQPEA7E-_&A5EDvQO5AwEDxwO9A7UDxQPDA7cDwg-_&A5UDuQPD- &- related security.pdf"
>decode_imap_utf7(encode_imap_utf7(z))
"Συστήματα_Ανίχνευσης_Εισ & related security.pdf"
>decode_imap_utf7(encode_imap_utf7(z)) == z
true
/* Se RFC 2060 - no / ~ \ in folder names */
function ureplacer(pmatch) {
    var ret = ""
    pmatch = pmatch.replace(/\,/g,'/')
    var ix = pmatch.substr(1,pmatch.length-2)

    if (ix.length % 4 != 0) 
      ix = ix.padEnd(ix.length+ 4 - ix.length % 4,"=")
    try {
    var dx = atob(ix)
    for (var j = 0; j < dx.length; j = j+2) {
        ret = ret + String.fromCharCode((dx.charCodeAt(j) << 8) + dx.charCodeAt(j+1))
    }
    } catch(err) {
    console.log("Error in decoding foldername IMAP UTF7, sending empty string back")
    console.log(err)
    ret = ""
    }
    return ret
}

function breplacer(umatch) {
    var bst = ""
    for (var i=0; i < umatch.length; i++) {
      var f = umatch.charCodeAt(i)
      bst = bst + String.fromCharCode(f >> 8) + String.fromCharCode(f & 255)
    }

    try {
    bst = '&'+btoa(bst).replace(/\//g,',').replace(/=+/,'')+'-'
    }catch(err) {
    console.log("Error in encoding foldername IMAP UTF7, sending empty string back")
    console.log(err)
    bst = ""
    }
    return bst
}

function decode_imap_utf7(mstring) {
    var stm = new RegExp(/(\&[A-Za-z0-9\+\,]+\-)/,'g')
    return mstring.replace(stm,ureplacer).replace('&-','&')
}

function encode_imap_utf7(ustring) {
    ustring = ustring.replace(/\/|\~|\\/g,'')
    var vgm = new RegExp(/([^\x20-\x7e]+)/,'g')
    return ustring.replace('&','&-').replace(vgm,breplacer)
}