本文整理匯總了Golang中github.com/docker/notary/trustmanager.NewKeyMemoryStore函數的典型用法代碼示例。如果您正苦於以下問題:Golang NewKeyMemoryStore函數的具體用法?Golang NewKeyMemoryStore怎麽用?Golang NewKeyMemoryStore使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了NewKeyMemoryStore函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: TestRemoveMultikeysAbortChoice
// If there is more than one key, removeKeyInteractively will ask which key to
// delete. Then it will confirm whether they want to delete, and the user can
// abort at that confirmation.
func TestRemoveMultikeysAbortChoice(t *testing.T) {
in := bytes.NewBuffer([]byte("1\nn\n"))
key, err := trustmanager.GenerateED25519Key(rand.Reader)
assert.NoError(t, err)
stores := []trustmanager.KeyStore{
trustmanager.NewKeyMemoryStore(ret),
trustmanager.NewKeyMemoryStore(ret),
}
err = stores[0].AddKey(key.ID(), "root", key)
assert.NoError(t, err)
err = stores[1].AddKey("gun/"+key.ID(), "target", key)
assert.NoError(t, err)
var out bytes.Buffer
err = removeKeyInteractively(stores, key.ID(), in, &out)
assert.NoError(t, err) // no error to abort deleting
text, err := ioutil.ReadAll(&out)
assert.NoError(t, err)
assert.Len(t, stores[0].ListKeys(), 1)
assert.Len(t, stores[1].ListKeys(), 1)
// It should have listed the keys, asked whether the user really wanted to
// delete, and then aborted.
output := string(text)
assert.Contains(t, output, "Found the following matching keys")
assert.Contains(t, output, "Are you sure")
assert.Contains(t, output, "Aborting action")
}
示例2: TestYubiImportExistingKey
// Importing an existing key succeeds, but doesn't actually add the key, nor
// does it write it to backup.
func TestYubiImportExistingKey(t *testing.T) {
if !YubikeyAccessible() {
t.Skip("Must have Yubikey access.")
}
clearAllKeys(t)
SetYubikeyKeyMode(KeymodeNone)
defer func() {
SetYubikeyKeyMode(KeymodeTouch | KeymodePinOnce)
}()
store, err := NewYubiKeyStore(trustmanager.NewKeyMemoryStore(ret), ret)
assert.NoError(t, err)
key, err := testAddKey(t, store)
backup := trustmanager.NewKeyMemoryStore(ret)
newStore, err := NewYubiKeyStore(backup, ret)
assert.NoError(t, err)
// for sanity, ensure that the key is already in the Yubikey
k, _, err := newStore.GetKey(key.ID())
assert.NoError(t, err)
assert.NotNil(t, k)
// import the key, which should have already been added to the yubikey
pemBytes, err := trustmanager.EncryptPrivateKey(key, "passphrase")
assert.NoError(t, err)
err = newStore.ImportKey(pemBytes, "root")
assert.NoError(t, err)
// key is not in backup store
_, _, err = backup.GetKey(key.ID())
assert.Error(t, err)
}
示例3: TestYubiAddDuplicateKeySucceedsButDoesNotBackup
// If, when adding a key to the Yubikey, and it already exists, we succeed
// without adding it to the backup store.
func TestYubiAddDuplicateKeySucceedsButDoesNotBackup(t *testing.T) {
if !IsAccessible() {
t.Skip("Must have Yubikey access.")
}
clearAllKeys(t)
SetYubikeyKeyMode(KeymodeNone)
defer func() {
SetYubikeyKeyMode(KeymodeTouch | KeymodePinOnce)
}()
origStore, err := NewYubiStore(trustmanager.NewKeyMemoryStore(ret), ret)
require.NoError(t, err)
key, err := testAddKey(t, origStore)
require.NoError(t, err)
backup := trustmanager.NewKeyMemoryStore(ret)
cleanStore, err := NewYubiStore(backup, ret)
require.NoError(t, err)
require.Len(t, cleanStore.ListKeys(), 1)
err = cleanStore.AddKey(trustmanager.KeyInfo{Role: data.CanonicalRootRole, Gun: ""}, key)
require.NoError(t, err)
// there should be just 1 key on the yubikey
require.Len(t, cleanListKeys(t), 1)
// nothing was added to the backup
require.Len(t, backup.ListKeys(), 0)
}
示例4: TestRemoveMultikeysAbortChoice
// If there is more than one key, removeKeyInteractively will ask which key to
// delete. Then it will confirm whether they want to delete, and the user can
// abort at that confirmation.
func TestRemoveMultikeysAbortChoice(t *testing.T) {
setUp(t)
in := bytes.NewBuffer([]byte("1\nn\n"))
key, err := utils.GenerateED25519Key(rand.Reader)
require.NoError(t, err)
stores := []trustmanager.KeyStore{
trustmanager.NewKeyMemoryStore(ret),
trustmanager.NewKeyMemoryStore(ret),
}
err = stores[0].AddKey(trustmanager.KeyInfo{Role: data.CanonicalRootRole, Gun: ""}, key)
require.NoError(t, err)
err = stores[1].AddKey(trustmanager.KeyInfo{Role: data.CanonicalTargetsRole, Gun: "gun"}, key)
require.NoError(t, err)
var out bytes.Buffer
err = removeKeyInteractively(stores, key.ID(), in, &out)
require.NoError(t, err) // no error to abort deleting
text, err := ioutil.ReadAll(&out)
require.NoError(t, err)
require.Len(t, stores[0].ListKeys(), 1)
require.Len(t, stores[1].ListKeys(), 1)
// It should have listed the keys, asked whether the user really wanted to
// delete, and then aborted.
output := string(text)
require.Contains(t, output, "Found the following matching keys")
require.Contains(t, output, "Are you sure")
require.Contains(t, output, "Aborting action")
}
示例5: TestYubiAddDuplicateKeySucceedsButDoesNotBackup
// If, when adding a key to the Yubikey, and it already exists, we succeed
// without adding it to the backup store.
func TestYubiAddDuplicateKeySucceedsButDoesNotBackup(t *testing.T) {
if !YubikeyAccessible() {
t.Skip("Must have Yubikey access.")
}
clearAllKeys(t)
SetYubikeyKeyMode(KeymodeNone)
defer func() {
SetYubikeyKeyMode(KeymodeTouch | KeymodePinOnce)
}()
origStore, err := NewYubiKeyStore(trustmanager.NewKeyMemoryStore(ret), ret)
assert.NoError(t, err)
key, err := testAddKey(t, origStore)
assert.NoError(t, err)
backup := trustmanager.NewKeyMemoryStore(ret)
cleanStore, err := NewYubiKeyStore(backup, ret)
assert.NoError(t, err)
assert.Len(t, cleanStore.ListKeys(), 1)
err = cleanStore.AddKey(key.ID(), "root", key)
assert.NoError(t, err)
// there should be just 1 key on the yubikey
assert.Len(t, cleanListKeys(t), 1)
// nothing was added to the backup
assert.Len(t, backup.ListKeys(), 0)
}
示例6: TestYubiAddKeyCanAddToMiddleSlot
// If some random key in the middle was removed, adding a key will work (keys
// do not have to be deleted/added in order)
func TestYubiAddKeyCanAddToMiddleSlot(t *testing.T) {
if !IsAccessible() {
t.Skip("Must have Yubikey access.")
}
clearAllKeys(t)
SetYubikeyKeyMode(KeymodeNone)
defer func() {
SetYubikeyKeyMode(KeymodeTouch | KeymodePinOnce)
}()
// create 4 keys on the original store
backup := trustmanager.NewKeyMemoryStore(ret)
store, err := NewYubiStore(backup, ret)
require.NoError(t, err)
keys := addMaxKeys(t, store)
// delete one of the middle keys, and assert we can still create a new key
keyIDToDelete := keys[numSlots/2]
err = store.RemoveKey(keyIDToDelete)
require.NoError(t, err)
newKey, err := testAddKey(t, store)
require.NoError(t, err)
// create a new store, since we want to be sure the original store's cache
// is not masking any issues
cleanStore, err := NewYubiStore(trustmanager.NewKeyMemoryStore(ret), ret)
require.NoError(t, err)
// The new key should be in the original store, in the new clean store, and
// in the backup store. The old key should not be in the original store,
// or the new clean store.
for _, store := range []trustmanager.KeyStore{store, cleanStore, backup} {
// new key should appear in all stores
gottenKey, _, err := store.GetKey(newKey.ID())
require.NoError(t, err)
require.Equal(t, gottenKey.ID(), newKey.ID())
listedKeys := store.ListKeys()
_, ok := listedKeys[newKey.ID()]
require.True(t, ok)
// old key should not be in the non-backup stores
if store != backup {
_, _, err := store.GetKey(keyIDToDelete)
require.Error(t, err)
_, ok = listedKeys[keyIDToDelete]
require.False(t, ok)
}
}
}
示例7: TestRemoveOneKeyConfirm
// If there is one key, asking to remove it will ask for confirmation. Passing
// 'yes'/'y' response will continue the deletion.
func TestRemoveOneKeyConfirm(t *testing.T) {
setUp(t)
yesses := []string{"yes", " Y "}
for _, yesAnswer := range yesses {
store := trustmanager.NewKeyMemoryStore(ret)
key, err := trustmanager.GenerateED25519Key(rand.Reader)
require.NoError(t, err)
err = store.AddKey(trustmanager.KeyInfo{Role: data.CanonicalRootRole, Gun: ""}, key)
require.NoError(t, err)
var out bytes.Buffer
in := bytes.NewBuffer([]byte(yesAnswer + "\n"))
err = removeKeyInteractively(
[]trustmanager.KeyStore{store}, key.ID(), in, &out)
require.NoError(t, err)
text, err := ioutil.ReadAll(&out)
require.NoError(t, err)
output := string(text)
require.Contains(t, output, "Are you sure")
require.Contains(t, output, "Deleted "+key.ID())
require.Len(t, store.ListKeys(), 0)
}
}
示例8: setUpRepo
// initialize a repo with keys, so they can be rotated
func setUpRepo(t *testing.T, tempBaseDir, gun string, ret notary.PassRetriever) (
*httptest.Server, map[string]string) {
// Set up server
ctx := context.WithValue(
context.Background(), "metaStore", storage.NewMemStorage())
// Do not pass one of the const KeyAlgorithms here as the value! Passing a
// string is in itself good test that we are handling it correctly as we
// will be receiving a string from the configuration.
ctx = context.WithValue(ctx, "keyAlgorithm", "ecdsa")
// Eat the logs instead of spewing them out
l := logrus.New()
l.Out = bytes.NewBuffer(nil)
ctx = ctxu.WithLogger(ctx, logrus.NewEntry(l))
cryptoService := cryptoservice.NewCryptoService(trustmanager.NewKeyMemoryStore(ret))
ts := httptest.NewServer(server.RootHandler(nil, ctx, cryptoService, nil, nil, nil))
repo, err := client.NewNotaryRepository(
tempBaseDir, gun, ts.URL, http.DefaultTransport, ret, trustpinning.TrustPinConfig{})
require.NoError(t, err, "error creating repo: %s", err)
rootPubKey, err := repo.CryptoService.Create("root", "", data.ECDSAKey)
require.NoError(t, err, "error generating root key: %s", err)
err = repo.Initialize(rootPubKey.ID())
require.NoError(t, err)
return ts, repo.CryptoService.ListAllKeys()
}
示例9: TestRemoveOneKeyAbort
// If there is one key, asking to remove it will ask for confirmation. Passing
// anything other than 'yes'/'y'/'' response will abort the deletion and
// not delete the key.
func TestRemoveOneKeyAbort(t *testing.T) {
setUp(t)
nos := []string{"no", "NO", "AAAARGH", " N "}
store := trustmanager.NewKeyMemoryStore(ret)
key, err := utils.GenerateED25519Key(rand.Reader)
require.NoError(t, err)
err = store.AddKey(trustmanager.KeyInfo{Role: data.CanonicalRootRole, Gun: ""}, key)
require.NoError(t, err)
stores := []trustmanager.KeyStore{store}
for _, noAnswer := range nos {
var out bytes.Buffer
in := bytes.NewBuffer([]byte(noAnswer + "\n"))
err := removeKeyInteractively(stores, key.ID(), in, &out)
require.NoError(t, err)
text, err := ioutil.ReadAll(&out)
require.NoError(t, err)
output := string(text)
require.Contains(t, output, "Are you sure")
require.Contains(t, output, "Aborting action")
require.Len(t, store.ListKeys(), 1)
}
}
示例10: TestUnlockedSigner
func TestUnlockedSigner(t *testing.T) {
privKey, err := trustmanager.GenerateECDSAKey(rand.Reader)
assert.NoError(t, err, "could not generate key")
keyStore := trustmanager.NewKeyMemoryStore(passphraseRetriever)
err = keyStore.AddKey(privKey.ID(), "root", privKey)
assert.NoError(t, err, "could not add key to store")
cryptoService := NewCryptoService("", keyStore)
uCryptoService := NewUnlockedCryptoService(privKey, cryptoService)
// Check ID method
assert.Equal(t, privKey.ID(), uCryptoService.ID())
// Check Public method
assert.Equal(t, privKey.Public(), uCryptoService.PublicKey().Public())
assert.Equal(t, privKey.ID(), uCryptoService.PublicKey().ID())
// Check GenerateCertificate method
gun := "docker.com/notary"
cert, err := uCryptoService.GenerateCertificate(gun)
assert.NoError(t, err, "could not generate certificate")
// Check public key
ecdsaPrivateKey, err := x509.ParseECPrivateKey(privKey.Private())
assert.NoError(t, err)
ecdsaPublicKey := ecdsaPrivateKey.Public()
assert.Equal(t, ecdsaPublicKey, cert.PublicKey)
// Check CommonName
assert.Equal(t, cert.Subject.CommonName, gun)
}
示例11: TestCreateAndGetWhenMultipleKeystores
// If there are multiple keystores, ensure that a key is only added to one -
// the first in the list of keyStores (which is in order of preference)
func (c CryptoServiceTester) TestCreateAndGetWhenMultipleKeystores(t *testing.T) {
cryptoService := c.cryptoServiceFactory()
cryptoService.keyStores = append(cryptoService.keyStores,
trustmanager.NewKeyMemoryStore(passphraseRetriever))
// Test Create
tufKey, err := cryptoService.Create(c.role, c.keyAlgo)
assert.NoError(t, err, c.errorMsg("error creating key"))
// Only the first keystore should have the key
keyPath := tufKey.ID()
if c.role != data.CanonicalRootRole && cryptoService.gun != "" {
keyPath = filepath.Join(cryptoService.gun, keyPath)
}
_, _, err = cryptoService.keyStores[0].GetKey(keyPath)
assert.NoError(t, err, c.errorMsg(
"First keystore does not have the key %s", keyPath))
_, _, err = cryptoService.keyStores[1].GetKey(keyPath)
assert.Error(t, err, c.errorMsg(
"Second keystore has the key %s", keyPath))
// GetKey works across multiple keystores
retrievedKey := cryptoService.GetKey(tufKey.ID())
assert.NotNil(t, retrievedKey,
c.errorMsg("Could not find key ID %s", tufKey.ID()))
}
示例12: testCryptoService
func testCryptoService(t *testing.T, gun string) {
getTestingCryptoService := func() *CryptoService {
return NewCryptoService(
gun, trustmanager.NewKeyMemoryStore(passphraseRetriever))
}
roles := []string{
data.CanonicalRootRole,
data.CanonicalTargetsRole,
data.CanonicalSnapshotRole,
data.CanonicalTimestampRole,
}
for _, role := range roles {
for algo := range algoToSigType {
cst := CryptoServiceTester{
cryptoServiceFactory: getTestingCryptoService,
role: role,
keyAlgo: algo,
}
cst.TestCreateAndGetKey(t)
cst.TestCreateAndGetWhenMultipleKeystores(t)
cst.TestGetNonexistentKey(t)
cst.TestSignWithKey(t)
cst.TestSignNoMatchingKeys(t)
cst.TestSignWhenMultipleKeystores(t)
cst.TestRemoveCreatedKey(t)
cst.TestRemoveFromMultipleKeystores(t)
cst.TestListFromMultipleKeystores(t)
}
}
}
示例13: TestYubiImportNonRootKey
// Importing a key not as root fails, and it is not added to the backup store
func TestYubiImportNonRootKey(t *testing.T) {
if !YubikeyAccessible() {
t.Skip("Must have Yubikey access.")
}
clearAllKeys(t)
SetYubikeyKeyMode(KeymodeNone)
defer func() {
SetYubikeyKeyMode(KeymodeTouch | KeymodePinOnce)
}()
backup := trustmanager.NewKeyMemoryStore(ret)
store, err := NewYubiKeyStore(backup, ret)
assert.NoError(t, err)
// generate key and import it
privKey, err := trustmanager.GenerateECDSAKey(rand.Reader)
assert.NoError(t, err)
pemBytes, err := trustmanager.EncryptPrivateKey(privKey, "passphrase")
assert.NoError(t, err)
err = store.ImportKey(pemBytes, privKey.ID())
assert.Error(t, err)
// key is not in backup store
_, _, err = backup.GetKey(privKey.ID())
assert.Error(t, err)
}
示例14: init
func init() {
pr = func(string, string, bool, int) (string, bool, error) { return "passphrase", false, nil }
keyStore := trustmanager.NewKeyMemoryStore(pr)
cryptoService := cryptoservice.NewCryptoService("", keyStore)
cryptoServices := signer.CryptoServiceIndex{data.ED25519Key: cryptoService, data.RSAKey: cryptoService, data.ECDSAKey: cryptoService}
void = &pb.Void{}
fakeHealth := func() map[string]string {
return health
}
//server setup
kms := &api.KeyManagementServer{CryptoServices: cryptoServices,
HealthChecker: fakeHealth}
ss := &api.SignerServer{CryptoServices: cryptoServices,
HealthChecker: fakeHealth}
grpcServer = grpc.NewServer()
pb.RegisterKeyManagementServer(grpcServer, kms)
pb.RegisterSignerServer(grpcServer, ss)
lis, err := net.Listen("tcp", "127.0.0.1:7899")
if err != nil {
log.Fatalf("failed to listen %v", err)
}
go grpcServer.Serve(lis)
//client setup
conn, err := grpc.Dial("127.0.0.1:7899", grpc.WithInsecure())
if err != nil {
log.Fatalf("fail to dial: %v", err)
}
kmClient = pb.NewKeyManagementClient(conn)
sClient = pb.NewSignerClient(conn)
}
示例15: testCryptoService
func testCryptoService(t *testing.T, keyAlgo data.KeyAlgorithm, verifier signed.Verifier) {
content := []byte("this is a secret")
keyStore := trustmanager.NewKeyMemoryStore(passphraseRetriever)
cryptoService := NewCryptoService("", keyStore)
// Test Create
tufKey, err := cryptoService.Create("", keyAlgo)
assert.NoError(t, err, "error creating key")
// Test Sign
signatures, err := cryptoService.Sign([]string{tufKey.ID()}, content)
assert.NoError(t, err, "signing failed")
assert.Len(t, signatures, 1, "wrong number of signatures")
err = verifier.Verify(tufKey, signatures[0].Signature, content)
assert.NoError(t, err, "verification failed")
// Test GetKey
retrievedKey := cryptoService.GetKey(tufKey.ID())
assert.Equal(t, tufKey.Public(), retrievedKey.Public(), "retrieved key didn't match")
assert.Nil(t, cryptoService.GetKey("boguskeyid"), "non-nil result for bogus keyid")
// Test RemoveKey
err = cryptoService.RemoveKey(tufKey.ID())
assert.NoError(t, err, "could not remove key")
retrievedKey = cryptoService.GetKey(tufKey.ID())
assert.Nil(t, retrievedKey, "remove didn't work")
}