src/pkg/crypto/subtle/constant_time.go - The Go Programming Language

Golang

Source file src/pkg/crypto/subtle/constant_time.go

     1	// Copyright 2009 The Go Authors. All rights reserved.
     2	// Use of this source code is governed by a BSD-style
     3	// license that can be found in the LICENSE file.
     4	
     5	// Package subtle implements functions that are often useful in cryptographic
     6	// code but require careful thought to use correctly.
     7	package subtle
     8	
     9	// ConstantTimeCompare returns 1 iff the two equal length slices, x
    10	// and y, have equal contents. The time taken is a function of the length of
    11	// the slices and is independent of the contents.
    12	func ConstantTimeCompare(x, y []byte) int {
    13		var v byte
    14	
    15		for i := 0; i < len(x); i++ {
    16			v |= x[i] ^ y[i]
    17		}
    18	
    19		return ConstantTimeByteEq(v, 0)
    20	}
    21	
    22	// ConstantTimeSelect returns x if v is 1 and y if v is 0.
    23	// Its behavior is undefined if v takes any other value.
    24	func ConstantTimeSelect(v, x, y int) int { return ^(v-1)&x | (v-1)&y }
    25	
    26	// ConstantTimeByteEq returns 1 if x == y and 0 otherwise.
    27	func ConstantTimeByteEq(x, y uint8) int {
    28		z := ^(x ^ y)
    29		z &= z >> 4
    30		z &= z >> 2
    31		z &= z >> 1
    32	
    33		return int(z)
    34	}
    35	
    36	// ConstantTimeEq returns 1 if x == y and 0 otherwise.
    37	func ConstantTimeEq(x, y int32) int {
    38		z := ^(x ^ y)
    39		z &= z >> 16
    40		z &= z >> 8
    41		z &= z >> 4
    42		z &= z >> 2
    43		z &= z >> 1
    44	
    45		return int(z & 1)
    46	}
    47	
    48	// ConstantTimeCopy copies the contents of y into x iff v == 1. If v == 0, x is left unchanged.
    49	// Its behavior is undefined if v takes any other value.
    50	func ConstantTimeCopy(v int, x, y []byte) {
    51		xmask := byte(v - 1)
    52		ymask := byte(^(v - 1))
    53		for i := 0; i < len(x); i++ {
    54			x[i] = x[i]&xmask | y[i]&ymask
    55		}
    56		return
    57	}