github.com/jackc/pgx/v5@v5.5.5/pgproto3/authentication_md5_password.go (about) 1 package pgproto3 2 3 import ( 4 "encoding/binary" 5 "encoding/json" 6 "errors" 7 8 "github.com/jackc/pgx/v5/internal/pgio" 9 ) 10 11 // AuthenticationMD5Password is a message sent from the backend indicating that an MD5 hashed password is required. 12 type AuthenticationMD5Password struct { 13 Salt [4]byte 14 } 15 16 // Backend identifies this message as sendable by the PostgreSQL backend. 17 func (*AuthenticationMD5Password) Backend() {} 18 19 // Backend identifies this message as an authentication response. 20 func (*AuthenticationMD5Password) AuthenticationResponse() {} 21 22 // Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message 23 // type identifier and 4 byte message length. 24 func (dst *AuthenticationMD5Password) Decode(src []byte) error { 25 if len(src) != 8 { 26 return errors.New("bad authentication message size") 27 } 28 29 authType := binary.BigEndian.Uint32(src) 30 31 if authType != AuthTypeMD5Password { 32 return errors.New("bad auth type") 33 } 34 35 copy(dst.Salt[:], src[4:8]) 36 37 return nil 38 } 39 40 // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. 41 func (src *AuthenticationMD5Password) Encode(dst []byte) ([]byte, error) { 42 dst, sp := beginMessage(dst, 'R') 43 dst = pgio.AppendUint32(dst, AuthTypeMD5Password) 44 dst = append(dst, src.Salt[:]...) 45 return finishMessage(dst, sp) 46 } 47 48 // MarshalJSON implements encoding/json.Marshaler. 49 func (src AuthenticationMD5Password) MarshalJSON() ([]byte, error) { 50 return json.Marshal(struct { 51 Type string 52 Salt [4]byte 53 }{ 54 Type: "AuthenticationMD5Password", 55 Salt: src.Salt, 56 }) 57 } 58 59 // UnmarshalJSON implements encoding/json.Unmarshaler. 60 func (dst *AuthenticationMD5Password) UnmarshalJSON(data []byte) error { 61 // Ignore null, like in the main JSON package. 62 if string(data) == "null" { 63 return nil 64 } 65 66 var msg struct { 67 Type string 68 Salt [4]byte 69 } 70 if err := json.Unmarshal(data, &msg); err != nil { 71 return err 72 } 73 74 dst.Salt = msg.Salt 75 return nil 76 }