github.com/rahart/packer@v0.12.2-0.20161229105310-282bb6ad370f/provisioner/powershell/powershell.go (about)

     1  package powershell
     2  
     3  import (
     4  	"encoding/base64"
     5  	"encoding/binary"
     6  	"unicode/utf16"
     7  	"unicode/utf8"
     8  
     9  	"golang.org/x/text/encoding/unicode"
    10  )
    11  
    12  func convertUtf8ToUtf16LE(message string) (string, error) {
    13  	utf16le := unicode.UTF16(unicode.LittleEndian, unicode.IgnoreBOM)
    14  	utfEncoder := utf16le.NewEncoder()
    15  	ut16LeEncodedMessage, err := utfEncoder.String(message)
    16  
    17  	return ut16LeEncodedMessage, err
    18  }
    19  
    20  // UTF16BytesToString converts UTF-16 encoded bytes, in big or little endian byte order,
    21  // to a UTF-8 encoded string.
    22  func UTF16BytesToString(b []byte, o binary.ByteOrder) string {
    23  	utf := make([]uint16, (len(b)+(2-1))/2)
    24  	for i := 0; i+(2-1) < len(b); i += 2 {
    25  		utf[i/2] = o.Uint16(b[i:])
    26  	}
    27  	if len(b)/2 < len(utf) {
    28  		utf[len(utf)-1] = utf8.RuneError
    29  	}
    30  	return string(utf16.Decode(utf))
    31  }
    32  
    33  func powershellEncode(message string) (string, error) {
    34  	utf16LEEncodedMessage, err := convertUtf8ToUtf16LE(message)
    35  	if err != nil {
    36  		return "", err
    37  	}
    38  
    39  	// Base64 encode the command
    40  	input := []uint8(utf16LEEncodedMessage)
    41  	return base64.StdEncoding.EncodeToString(input), nil
    42  }
    43  
    44  func powershellDecode(messageBase64 string) (retour string, err error) {
    45  	messageUtf16LeByteArray, err := base64.StdEncoding.DecodeString(messageBase64)
    46  
    47  	if err != nil {
    48  		return "", err
    49  	}
    50  
    51  	message := UTF16BytesToString(messageUtf16LeByteArray, binary.LittleEndian)
    52  
    53  	return message, nil
    54  }