github.com/mhilton/juju-juju@v0.0.0-20150901100907-a94dd2c73455/service/windows/securestring/securestring_test.go (about) 1 // Copyright 2015 Canonical Ltd. 2 // Copyright 2015 Cloudbase Solutions 3 // Licensed under the AGPLv3, see LICENCE file for details. 4 // 5 // +build windows 6 7 package securestring_test 8 9 import ( 10 "fmt" 11 "os/exec" 12 "strings" 13 "testing" 14 15 gc "gopkg.in/check.v1" 16 17 "github.com/juju/juju/service/windows/securestring" 18 ) 19 20 func Test(t *testing.T) { 21 gc.TestingT(t) 22 } 23 24 type SecureStringSuite struct{} 25 26 var _ = gc.Suite(&SecureStringSuite{}) 27 28 var testInputs []string = []string{ 29 "Simple", 30 "A longer string", 31 `A!string%with(a4239lot#of$&*special@characters{[]})`, 32 "Quite a very much longer string meant to push the envelope", 33 "fsdafsgdfgdfgdfgdfgsdfgdgdfgdmmghnh kv dfv dj fkvjjenrwenvfvvslfvnsljfvnlsfvlnsfjlvnssdwoewivdsvmxxvsdvsdv", 34 "â", 35 `âăzßșx€đ©rfvțgbyhnujmîkło§ł`, 36 `看看那些旧照片里的人们多么有趣啊`, 37 } 38 39 // tests whether encryption and decryption are symmetrical operations 40 func (s *SecureStringSuite) TestEncryptDecryptSymmetry(c *gc.C) { 41 for _, input := range testInputs { 42 enc, err := securestring.Encrypt(input) 43 c.Assert(err, gc.IsNil) 44 dec, err := securestring.Decrypt(enc) 45 c.Assert(err, gc.IsNil) 46 c.Assert(dec, gc.Equals, input) 47 } 48 } 49 50 func runPowerShellCommands(cmds string) (string, error) { 51 var invokePowerShellParams []string = []string{ 52 "-NoProfile", 53 "-NonInteractive", 54 "-Command", 55 fmt.Sprintf(`try{%s; exit $LastExitCode}catch{Write-Error -Message $Error[0]; exit 1}`, cmds), 56 } 57 ps, err := exec.Command("powershell.exe", invokePowerShellParams...).Output() 58 if err != nil { 59 return "", err 60 } 61 return strings.TrimSpace(string(ps)), nil 62 } 63 64 // tests whether the output of ConvertFrom-SecureString is compatible with the module and can be decrypted 65 func (s *SecureStringSuite) TestDecryptFromCFSS(c *gc.C) { 66 for _, input := range testInputs { 67 psenc, err := runPowerShellCommands(fmt.Sprintf("ConvertTo-SecureString \"%s\" -AsPlainText -Force | ConvertFrom-SecureString", input)) 68 c.Assert(err, gc.IsNil) 69 70 dec, err := securestring.Decrypt(psenc) 71 c.Assert(err, gc.IsNil) 72 c.Assert(fmt.Sprintf("%s", dec), gc.Equals, input) 73 } 74 } 75 76 // tests whether the output of the module is compatible with PowerShell's SecureString and is accepted as valid 77 func (s *SecureStringSuite) TestConvertEncryptedToPowerShellSS(c *gc.C) { 78 for _, input := range testInputs { 79 enc, err := securestring.Encrypt(input) 80 c.Assert(err, gc.IsNil) 81 82 psresp, err := runPowerShellCommands(fmt.Sprintf("\"%s\" | ConvertTo-SecureString", enc)) 83 c.Assert(err, gc.IsNil) 84 85 c.Assert(psresp, gc.Equals, "System.Security.SecureString") 86 } 87 }