get.pme.sh/pnats@v0.0.0-20240304004023-26bb5a137ed0/server/nkey.go (about) 1 // Copyright 2018 The NATS Authors 2 // Licensed under the Apache License, Version 2.0 (the "License"); 3 // you may not use this file except in compliance with the License. 4 // You may obtain a copy of the License at 5 // 6 // http://www.apache.org/licenses/LICENSE-2.0 7 // 8 // Unless required by applicable law or agreed to in writing, software 9 // distributed under the License is distributed on an "AS IS" BASIS, 10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 package server 15 16 import ( 17 crand "crypto/rand" 18 "encoding/base64" 19 ) 20 21 // Raw length of the nonce challenge 22 const ( 23 nonceRawLen = 11 24 nonceLen = 15 // base64.RawURLEncoding.EncodedLen(nonceRawLen) 25 ) 26 27 // NonceRequired tells us if we should send a nonce. 28 func (s *Server) NonceRequired() bool { 29 s.mu.Lock() 30 defer s.mu.Unlock() 31 return s.nonceRequired() 32 } 33 34 // nonceRequired tells us if we should send a nonce. 35 // Lock should be held on entry. 36 func (s *Server) nonceRequired() bool { 37 return s.getOpts().AlwaysEnableNonce || len(s.nkeys) > 0 || s.trustedKeys != nil 38 } 39 40 // Generate a nonce for INFO challenge. 41 // Assumes server lock is held 42 func (s *Server) generateNonce(n []byte) { 43 var raw [nonceRawLen]byte 44 data := raw[:] 45 crand.Read(data) 46 base64.RawURLEncoding.Encode(n, data) 47 }