crypto: add custom errors to crypto lib (#9522)

pull/9536/head
Atakan Yenel 2021-03-30 14:27:57 +02:00 committed by GitHub
parent ab6e0ed0b3
commit 70b189d751
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 9 additions and 8 deletions

View File

@ -4,6 +4,7 @@
module rand module rand
const ( struct ReadError {
read_error = error('crypto.rand.read() error reading random bytes') msg string = 'crypto.rand.read() error reading random bytes'
) code int
}

View File

@ -12,10 +12,10 @@ fn C.SecRandomCopyBytes(rnd C.SecRandomRef, count size_t, bytes voidptr) int
// read returns an array of `bytes_needed` random bytes read from the OS. // read returns an array of `bytes_needed` random bytes read from the OS.
pub fn read(bytes_needed int) ?[]byte { pub fn read(bytes_needed int) ?[]byte {
mut buffer := []byte{ len: bytes_needed } mut buffer := []byte{len: bytes_needed}
status := C.SecRandomCopyBytes(C.SecRandomRef(0), bytes_needed, buffer.data) status := C.SecRandomCopyBytes(C.SecRandomRef(0), bytes_needed, buffer.data)
if status != 0 { if status != 0 {
return read_error return IError(&ReadError{})
} }
return buffer return buffer
} }

View File

@ -19,7 +19,7 @@ pub fn read(bytes_needed int) ?[]byte {
rbytes := unsafe { getrandom(batch_size, buffer + bytes_read) } rbytes := unsafe { getrandom(batch_size, buffer + bytes_read) }
if rbytes == -1 { if rbytes == -1 {
unsafe { free(buffer) } unsafe { free(buffer) }
return read_error return IError(&ReadError{})
} }
bytes_read += rbytes bytes_read += rbytes
} }

View File

@ -23,7 +23,7 @@ pub fn read(bytes_needed int) ?[]byte {
rbytes := unsafe { getrandom(batch_size, buffer + bytes_read) } rbytes := unsafe { getrandom(batch_size, buffer + bytes_read) }
if rbytes == -1 { if rbytes == -1 {
unsafe { free(buffer) } unsafe { free(buffer) }
return read_error return IError(&ReadError{})
} }
bytes_read += rbytes bytes_read += rbytes
} }

View File

@ -19,7 +19,7 @@ pub fn read(bytes_needed int) ?[]byte {
// use bcrypt_use_system_preferred_rng because we passed null as algo // use bcrypt_use_system_preferred_rng because we passed null as algo
status := C.BCryptGenRandom(0, buffer.data, bytes_needed, bcrypt_use_system_preferred_rng) status := C.BCryptGenRandom(0, buffer.data, bytes_needed, bcrypt_use_system_preferred_rng)
if status != status_success { if status != status_success {
return read_error return IError(&ReadError{})
} }
return buffer return buffer
} }