github.com/hyperledger/aries-framework-go@v0.3.2/pkg/didcomm/transport/internal/helpers.go (about)

     1  /*
     2  Copyright SecureKey Technologies Inc. All Rights Reserved.
     3  
     4  SPDX-License-Identifier: Apache-2.0
     5  */
     6  
     7  package internal
     8  
     9  import (
    10  	"bytes"
    11  	"encoding/base64"
    12  	"fmt"
    13  
    14  	"github.com/hyperledger/aries-framework-go/pkg/common/log"
    15  	"github.com/hyperledger/aries-framework-go/pkg/didcomm/transport"
    16  )
    17  
    18  var logger = log.New("didcomm/transport/internal")
    19  
    20  // UnpackMessage using 'pack' with a 'source' of either 'ws' or 'http'.
    21  func UnpackMessage(message []byte, pack transport.Packager, source string) (*transport.Envelope, error) {
    22  	doubleQuote := []byte("\"")
    23  	msg := message
    24  
    25  	if bytes.HasPrefix(message, doubleQuote) && bytes.HasSuffix(message, doubleQuote) {
    26  		logger.Debugf("unpack msg from %s is wrapped with double quotes trying to base64 decode before unpacking..",
    27  			source)
    28  
    29  		msg = msg[1 : len(msg)-1]
    30  
    31  		var decodedMsg []byte
    32  
    33  		decodedMsg1, err1 := base64.URLEncoding.DecodeString(string(msg))
    34  		decodedMsg2, err2 := base64.RawURLEncoding.DecodeString(string(msg))
    35  
    36  		switch {
    37  		case err1 == nil:
    38  			decodedMsg = decodedMsg1
    39  		case err2 == nil:
    40  			decodedMsg = decodedMsg2
    41  		default:
    42  			return nil, fmt.Errorf("not base64 encoded message error from %s: URLEncoding error: %w, RawURLEncoding"+
    43  				" error: %v", source, err1, err2)
    44  		}
    45  
    46  		msg = decodedMsg
    47  	}
    48  
    49  	unpackMsg, err := pack.UnpackMessage(msg)
    50  	if err != nil {
    51  		return nil, fmt.Errorf("failed to unpack msg from %s: %w", source, err)
    52  	}
    53  
    54  	return unpackMsg, nil
    55  }