0

I must decode with golang a string that contains words in Spanish, with accents and special characters. But what I have tried does not work. Could you please guide me on the right path, to get what I need. Thanks in advance. This is my current code:

import (
    "encoding/base64"
    "fmt"

    "golang.org/x/text/encoding/unicode"
)

    var authStr = "2m5pY2E6U+06e1v28V19Okludml0YWNp824="
    arB, _ := base64.StdEncoding.DecodeString(authStr)
    fmt.Println("De arB se obtuvo: ")
    fmt.Println(string(arB)) 
    // got->        �nica:S�:{[��]}:Invitaci�n
    // expected->   Única:Sí:{[öñ]}:Invitación
    dec := unicode.UTF8.NewDecoder()
    arButf8 := make([]byte, len(arB)*2)
    if n, _, err := dec.Transform(arButf8, []byte(arB), true); err != nil {
        fmt.Println("Error: ", err)
    } else {
        arButf8 = arButf8[:n]
        fmt.Println("De authStr se obtuvo: ")
        fmt.Println(string(arButf8)) 
        // got->        �nica:S�:{[��]}:Invitaci�n
        // expected->   Única:Sí:{[öñ]}:Invitación          
    }
    // If do with Javascript atob("2m5pY2E6U+06e1v28V19Okludml0YWNp824=") works fine
  • 1
    Your base64 encoding string is wrong: https://play.golang.org/p/F8yG_0dyvun. The encoded string `w5puaWNhOlPDrTp7W8O2w7FdfTpJbnZpdGFjacOzbg==` decodes properly to `Única:Sí:{[öñ]}:Invitación` – Kaedys May 22 '18 at 15:48
  • 2
    The source string is in [8859-1](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) or [Windows-1252](https://en.wikipedia.org/wiki/Windows-1252) encoding, not UTF-8 as the program expects. Use the [x/net/encoding](https://godoc.org/golang.org/x/text/encoding) to convert the string to UTF-8 – Charlie Tumahai May 22 '18 at 15:52
  • Maybe you are right, but the string of characters is as it is sent by the browser: atob("2m5pY2E6U+06e1v28V19Okludml0YWNp824=") btoa("Única:Sí:{[öñ]}:Invitación") Any other idea? – Carlos Zuñiga May 22 '18 at 16:04
  • #ThunderCat has right. i just changed this line and everything works. Thanks: dec := charmap.ISO8859_1.NewDecoder() – Carlos Zuñiga May 22 '18 at 16:13

1 Answers1

0

This is the correct code:

    import (
     "encoding/base64"
     "fmt"
     "golang.org/x/text/encoding/charmap"
    )
    var authStr = "2m5pY2E6U+06e1v28V19Okludml0YWNp824="
    arB, _ := base64.StdEncoding.DecodeString(authStr)
    fmt.Println("De arB se obtuvo: ")
    fmt.Println(string(arB)) 
    dec := charmap.ISO8859_1.NewDecoder()
    arBdest := make([]byte, len(arB)*2)
    if n, _, err := dec.Transform(arBdest, []byte(arB), true); err != nil {
        fmt.Println("Error: ", err)
    } else {
        arBdest = arBdest[:n]
        fmt.Println("De authStr se obtuvo: ")
        fmt.Println(string(arBdest))         
    }