github.com/xxf098/lite-proxy@v0.15.1-0.20230422081941-12c69f323218/utils/b64.go (about)

     1  package utils
     2  
     3  import (
     4  	"encoding/base64"
     5  	"strings"
     6  )
     7  
     8  func DecodeB64(s string) (string, error) {
     9  	// s = strings.ReplaceAll(s, "-", "+")
    10  	// s = strings.ReplaceAll(s, "_", "/")
    11  	// data, err := base64.StdEncoding.DecodeString(s)
    12  	// if err != nil {
    13  	// 	if data, err = base64.RawStdEncoding.DecodeString(s); err != nil {
    14  	// 		return "", err
    15  	// 	}
    16  	// }
    17  	// return string(data), nil
    18  	data, err := DecodeB64Bytes(s)
    19  	if err != nil {
    20  		return "", err
    21  	}
    22  	return B2s(data), nil
    23  }
    24  
    25  func DecodeB64Bytes(s string) ([]byte, error) {
    26  	s = strings.TrimSpace(s)
    27  	s = strings.ReplaceAll(s, "-", "+")
    28  	s = strings.ReplaceAll(s, "_", "/")
    29  	if pad := len(s) % 4; pad != 0 {
    30  		s += strings.Repeat("=", 4-pad)
    31  	}
    32  	data, err := base64.StdEncoding.DecodeString(s)
    33  	if err != nil {
    34  		// URLEncoding
    35  		if data, err = base64.RawStdEncoding.DecodeString(s); err != nil {
    36  			return nil, err
    37  		}
    38  	}
    39  	return data, nil
    40  }