49 lines
1.4 KiB
Go
49 lines
1.4 KiB
Go
package securebytes
|
|
|
|
import (
|
|
"errors"
|
|
|
|
"github.com/awnumar/memguard"
|
|
)
|
|
|
|
// SecureBytes is used to store a byte slice securely in memory.
|
|
// It uses memguard to protect sensitive data from being exposed in memory dumps,
|
|
// swap files, or other memory scanning attacks.
|
|
type SecureBytes struct {
|
|
buffer *memguard.LockedBuffer
|
|
}
|
|
|
|
// NewSecureBytes creates a new SecureBytes instance from the given byte slice.
|
|
// The original byte slice should be wiped after creating SecureBytes to ensure
|
|
// the sensitive data is only stored in the secure buffer.
|
|
func NewSecureBytes(b []byte) (*SecureBytes, error) {
|
|
if len(b) == 0 {
|
|
return nil, errors.New("byte slice cannot be empty")
|
|
}
|
|
|
|
buffer := memguard.NewBuffer(len(b))
|
|
|
|
// Check if buffer was created successfully
|
|
if buffer == nil {
|
|
return nil, errors.New("failed to create buffer")
|
|
}
|
|
|
|
copy(buffer.Bytes(), b)
|
|
|
|
return &SecureBytes{buffer: buffer}, nil
|
|
}
|
|
|
|
// Bytes returns the securely stored byte slice.
|
|
// WARNING: The returned bytes are still protected by memguard, but any copies
|
|
// made from this slice will not be protected. Use with caution.
|
|
func (sb *SecureBytes) Bytes() []byte {
|
|
return sb.buffer.Bytes()
|
|
}
|
|
|
|
// Wipe removes the byte slice from memory and makes it unrecoverable.
|
|
// After calling Wipe, the SecureBytes instance should not be used.
|
|
func (sb *SecureBytes) Wipe() error {
|
|
sb.buffer.Wipe()
|
|
sb.buffer = nil
|
|
return nil
|
|
}
|