storj/pkg/piecestore/rpc/client/pieceid.go
Kaloyan Raev a6bafa993a
Obscure piece id across piece store nodes (#120)
* Obscure piece id across piece store nodes

* Add line separator in imports

* Avoid potential panic if hash < 32 bytes
2018-07-06 11:51:13 +03:00

50 lines
959 B
Go

// Copyright (C) 2018 Storj Labs, Inc.
// See LICENSE for copying information.
package client
import (
"crypto/hmac"
"crypto/rand"
"crypto/sha512"
"github.com/mr-tron/base58/base58"
)
// PieceID is the unique identifier for pieces
type PieceID string
// NewPieceID creates a PieceID
func NewPieceID() PieceID {
b := make([]byte, 32)
_, err := rand.Read(b)
if err != nil {
panic(err)
}
return PieceID(base58.Encode(b))
}
// String representation of the PieceID
func (id PieceID) String() string {
return string(id)
}
// IsValid checks if the current PieceID is valid
func (id PieceID) IsValid() bool {
return len(id) >= 20
}
// Derive a new PieceID from the current PieceID and the given secret
func (id PieceID) Derive(secret []byte) PieceID {
mac := hmac.New(sha512.New, secret)
mac.Write([]byte(id))
h := mac.Sum(nil)
// Trim the hash if greater than 32 bytes
if len(h) > 32 {
h = h[:32]
}
return PieceID(base58.Encode(h))
}