Files
Packer-Cn/provisioner/powershell/powershell.go
T

55 lines
1.3 KiB
Go
Raw Normal View History

2015-06-14 11:01:28 -07:00
package powershell
import (
"encoding/base64"
2016-07-24 14:44:07 +01:00
"encoding/binary"
"unicode/utf16"
"unicode/utf8"
2016-07-13 00:28:14 +01:00
"golang.org/x/text/encoding/unicode"
2015-06-14 11:01:28 -07:00
)
2016-07-24 14:44:07 +01:00
func convertUtf8ToUtf16LE(message string) (string, error) {
utf16le := unicode.UTF16(unicode.LittleEndian, unicode.IgnoreBOM)
utfEncoder := utf16le.NewEncoder()
ut16LeEncodedMessage, err := utfEncoder.String(message)
2016-07-13 00:28:14 +01:00
2016-07-24 14:44:07 +01:00
return ut16LeEncodedMessage, err
}
// UTF16BytesToString converts UTF-16 encoded bytes, in big or little endian byte order,
// to a UTF-8 encoded string.
func UTF16BytesToString(b []byte, o binary.ByteOrder) string {
utf := make([]uint16, (len(b)+(2-1))/2)
for i := 0; i+(2-1) < len(b); i += 2 {
utf[i/2] = o.Uint16(b[i:])
}
if len(b)/2 < len(utf) {
utf[len(utf)-1] = utf8.RuneError
}
return string(utf16.Decode(utf))
2016-07-13 00:28:14 +01:00
}
func powershellEncode(message string) (string, error) {
2016-07-24 14:44:07 +01:00
utf16LEEncodedMessage, err := convertUtf8ToUtf16LE(message)
2016-07-13 00:28:14 +01:00
if err != nil {
return "", err
2015-06-14 11:01:28 -07:00
}
// Base64 encode the command
2016-07-24 14:44:07 +01:00
input := []uint8(utf16LEEncodedMessage)
2016-07-13 00:28:14 +01:00
return base64.StdEncoding.EncodeToString(input), nil
2015-06-14 11:01:28 -07:00
}
2016-07-24 14:44:07 +01:00
func powershellDecode(messageBase64 string) (retour string, err error) {
messageUtf16LeByteArray, err := base64.StdEncoding.DecodeString(messageBase64)
2016-07-13 00:28:14 +01:00
if err != nil {
return "", err
}
2016-07-24 14:44:07 +01:00
message := UTF16BytesToString(messageUtf16LeByteArray, binary.LittleEndian)
return message, nil
}