Copyright (c) 2014 - Gustavo Niemeyer <gustavo@niemeyer.net> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Package scram implements a SCRAM-{SHA-1,etc} client per RFC5802. http://tools.ietf.org/html/rfc5802
package scram

import (
	
	
	
	
	
	
	
	
)
Client implements a SCRAM-* client (SCRAM-SHA-1, SCRAM-SHA-256, etc). A Client may be used within a SASL conversation with logic resembling: var in []byte var client = scram.NewClient(sha1.New, user, pass) for client.Step(in) { out := client.Out() // send out to server in := serverOut } if client.Err() != nil { // auth failed }
NewClient returns a new SCRAM-* client with the provided hash algorithm. For SCRAM-SHA-256, for example, use: client := scram.NewClient(sha256.New, user, pass)
func ( func() hash.Hash, ,  string) *Client {
	 := &Client{
		newHash: ,
		user:    ,
		pass:    ,
	}
	.out.Grow(256)
	.authMsg.Grow(256)
	return 
}
Out returns the data to be sent to the server in the current step.
func ( *Client) () []byte {
	if .out.Len() == 0 {
		return nil
	}
	return .out.Bytes()
}
Err returns the error that occurred, or nil if there were no errors.
func ( *Client) () error {
	return .err
}
SetNonce sets the client nonce to the provided value. If not set, the nonce is generated automatically out of crypto/rand on the first step.
func ( *Client) ( []byte) {
	.clientNonce = 
}

var escaper = strings.NewReplacer("=", "=3D", ",", "=2C")
Step processes the incoming data from the server and makes the next round of data for the server available via Client.Out. Step returns false if there are no errors and more data is still expected.
func ( *Client) ( []byte) bool {
	.out.Reset()
	if .step > 2 || .err != nil {
		return false
	}
	.step++
	switch .step {
	case 1:
		.err = .step1()
	case 2:
		.err = .step2()
	case 3:
		.err = .step3()
	}
	return .step > 2 || .err != nil
}

func ( *Client) ( []byte) error {
	if len(.clientNonce) == 0 {
		const  = 16
		 := make([]byte, +b64.EncodedLen())
		if ,  := rand.Read([:]);  != nil {
			return fmt.Errorf("cannot read random SCRAM-SHA-256 nonce from operating system: %v", )
		}
		.clientNonce = [:]
		b64.Encode(.clientNonce, [:])
	}
	.authMsg.WriteString("n=")
	escaper.WriteString(&.authMsg, .user)
	.authMsg.WriteString(",r=")
	.authMsg.Write(.clientNonce)

	.out.WriteString("n,,")
	.out.Write(.authMsg.Bytes())
	return nil
}

var b64 = base64.StdEncoding

func ( *Client) ( []byte) error {
	.authMsg.WriteByte(',')
	.authMsg.Write()

	 := bytes.Split(, []byte(","))
	if len() != 3 {
		return fmt.Errorf("expected 3 fields in first SCRAM-SHA-256 server message, got %d: %q", len(), )
	}
	if !bytes.HasPrefix([0], []byte("r=")) || len([0]) < 2 {
		return fmt.Errorf("server sent an invalid SCRAM-SHA-256 nonce: %q", [0])
	}
	if !bytes.HasPrefix([1], []byte("s=")) || len([1]) < 6 {
		return fmt.Errorf("server sent an invalid SCRAM-SHA-256 salt: %q", [1])
	}
	if !bytes.HasPrefix([2], []byte("i=")) || len([2]) < 6 {
		return fmt.Errorf("server sent an invalid SCRAM-SHA-256 iteration count: %q", [2])
	}

	.serverNonce = [0][2:]
	if !bytes.HasPrefix(.serverNonce, .clientNonce) {
		return fmt.Errorf("server SCRAM-SHA-256 nonce is not prefixed by client nonce: got %q, want %q+\"...\"", .serverNonce, .clientNonce)
	}

	 := make([]byte, b64.DecodedLen(len([1][2:])))
	,  := b64.Decode(, [1][2:])
	if  != nil {
		return fmt.Errorf("cannot decode SCRAM-SHA-256 salt sent by server: %q", [1])
	}
	 = [:]
	,  := strconv.Atoi(string([2][2:]))
	if  != nil {
		return fmt.Errorf("server sent an invalid SCRAM-SHA-256 iteration count: %q", [2])
	}
	.saltPassword(, )

	.authMsg.WriteString(",c=biws,r=")
	.authMsg.Write(.serverNonce)

	.out.WriteString("c=biws,r=")
	.out.Write(.serverNonce)
	.out.WriteString(",p=")
	.out.Write(.clientProof())
	return nil
}

func ( *Client) ( []byte) error {
	var ,  bool
	var  = bytes.Split(, []byte(","))
	if len() == 1 {
		 = bytes.HasPrefix([0], []byte("v="))
		 = bytes.HasPrefix([0], []byte("e="))
	}
	if  {
		return fmt.Errorf("SCRAM-SHA-256 authentication error: %s", [0][2:])
	} else if ! {
		return fmt.Errorf("unsupported SCRAM-SHA-256 final message from server: %q", )
	}
	if !bytes.Equal(.serverSignature(), [0][2:]) {
		return fmt.Errorf("cannot authenticate SCRAM-SHA-256 server signature: %q", [0][2:])
	}
	return nil
}

func ( *Client) ( []byte,  int) {
	 := hmac.New(.newHash, []byte(.pass))
	.Write()
	.Write([]byte{0, 0, 0, 1})
	 := .Sum(nil)
	 := make([]byte, len())
	copy(, )
	for  := 1;  < ; ++ {
		.Reset()
		.Write()
		.Sum([:0])
		for ,  := range  {
			[] ^= 
		}
	}
	.saltedPass = 
}

func ( *Client) () []byte {
	 := hmac.New(.newHash, .saltedPass)
	.Write([]byte("Client Key"))
	 := .Sum(nil)
	 := .newHash()
	.Write()
	 := .Sum(nil)
	 = hmac.New(.newHash, )
	.Write(.authMsg.Bytes())
	 := .Sum(nil)
	for ,  := range  {
		[] ^= 
	}
	 := make([]byte, b64.EncodedLen(len()))
	b64.Encode(, )
	return 
}

func ( *Client) () []byte {
	 := hmac.New(.newHash, .saltedPass)
	.Write([]byte("Server Key"))
	 := .Sum(nil)

	 = hmac.New(.newHash, )
	.Write(.authMsg.Bytes())
	 := .Sum(nil)

	 := make([]byte, b64.EncodedLen(len()))
	b64.Encode(, )
	return