本文整理匯總了Golang中github.com/docker/notary/cryptoservice.NewCryptoService函數的典型用法代碼示例。如果您正苦於以下問題:Golang NewCryptoService函數的具體用法?Golang NewCryptoService怎麽用?Golang NewCryptoService使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了NewCryptoService函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: filestoreWithTwoCerts
// Generates a Manager in a temporary directory and returns the
// manager and certificates for two keys which have been added to the keystore.
// Also returns the temporary directory so it can be cleaned up.
func filestoreWithTwoCerts(t *testing.T, gun, keyAlg string) (
string, *Manager, *cryptoservice.CryptoService, []*x509.Certificate) {
tempBaseDir, err := ioutil.TempDir("", "notary-test-")
assert.NoError(t, err, "failed to create a temporary directory: %s", err)
fileKeyStore, err := trustmanager.NewKeyFileStore(tempBaseDir, passphraseRetriever)
assert.NoError(t, err)
cryptoService := cryptoservice.NewCryptoService(gun, fileKeyStore)
// Create a Manager
certManager, err := NewManager(tempBaseDir)
assert.NoError(t, err)
certificates := make([]*x509.Certificate, 2)
for i := 0; i < 2; i++ {
pubKey, err := cryptoService.Create("root", keyAlg)
assert.NoError(t, err)
key, _, err := fileKeyStore.GetKey(pubKey.ID())
assert.NoError(t, err)
cert, err := cryptoservice.GenerateTestingCertificate(key.CryptoSigner(), gun)
assert.NoError(t, err)
certificates[i] = cert
}
return tempBaseDir, certManager, cryptoService, certificates
}
示例2: 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)
}
示例3: TestSoftwareSignHandler
func TestSoftwareSignHandler(t *testing.T) {
keyStore := trustmanager.NewKeyMemoryStore(passphraseRetriever)
cryptoService := cryptoservice.NewCryptoService("", keyStore)
setup(signer.CryptoServiceIndex{data.ED25519Key: cryptoService, data.RSAKey: cryptoService, data.ECDSAKey: cryptoService})
tufKey, err := cryptoService.Create("", data.ED25519Key)
assert.Nil(t, err)
sigRequest := &pb.SignatureRequest{KeyID: &pb.KeyID{ID: tufKey.ID()}, Content: make([]byte, 10)}
requestJson, _ := json.Marshal(sigRequest)
reader = strings.NewReader(string(requestJson))
request, err := http.NewRequest("POST", signBaseURL, reader)
assert.Nil(t, err)
res, err := http.DefaultClient.Do(request)
assert.Nil(t, err)
assert.Equal(t, 200, res.StatusCode)
jsonBlob, err := ioutil.ReadAll(res.Body)
assert.Nil(t, err)
var sig *pb.Signature
err = json.Unmarshal(jsonBlob, &sig)
assert.Nil(t, err)
assert.Equal(t, tufKey.ID(), sig.KeyInfo.KeyID.ID)
}
示例4: TestKeyInfoHandler
func TestKeyInfoHandler(t *testing.T) {
keyStore := trustmanager.NewKeyMemoryStore(passphraseRetriever)
cryptoService := cryptoservice.NewCryptoService("", keyStore)
setup(signer.CryptoServiceIndex{data.ED25519Key: cryptoService, data.RSAKey: cryptoService, data.ECDSAKey: cryptoService})
tufKey, _ := cryptoService.Create("", data.ED25519Key)
assert.NotNil(t, tufKey)
keyInfoURL := fmt.Sprintf("%s/%s", keyInfoBaseURL, tufKey.ID())
request, err := http.NewRequest("GET", keyInfoURL, nil)
assert.Nil(t, err)
res, err := http.DefaultClient.Do(request)
assert.Nil(t, err)
jsonBlob, err := ioutil.ReadAll(res.Body)
assert.Nil(t, err)
var pubKey *pb.PublicKey
err = json.Unmarshal(jsonBlob, &pubKey)
assert.Nil(t, err)
assert.Equal(t, tufKey.ID(), pubKey.KeyInfo.KeyID.ID)
assert.Equal(t, 200, res.StatusCode)
}
示例5: NewNotaryRepository
// NewNotaryRepository is a helper method that returns a new notary repository.
// It takes the base directory under where all the trust files will be stored
// (usually ~/.docker/trust/).
func NewNotaryRepository(baseDir, gun, baseURL string, rt http.RoundTripper,
passphraseRetriever passphrase.Retriever) (*NotaryRepository, error) {
keyStoreManager, err := keystoremanager.NewKeyStoreManager(baseDir, passphraseRetriever)
if err != nil {
return nil, err
}
cryptoService := cryptoservice.NewCryptoService(gun, keyStoreManager.NonRootKeyStore())
nRepo := &NotaryRepository{
gun: gun,
baseDir: baseDir,
baseURL: baseURL,
tufRepoPath: filepath.Join(baseDir, tufDir, filepath.FromSlash(gun)),
cryptoService: cryptoService,
roundTrip: rt,
KeyStoreManager: keyStoreManager,
}
fileStore, err := store.NewFilesystemStore(
nRepo.tufRepoPath,
"metadata",
"json",
"",
)
if err != nil {
return nil, err
}
nRepo.fileStore = fileStore
return nRepo, nil
}
示例6: keysImportRoot
// keysImportRoot imports a root key from a PEM file
func (k *keyCommander) keysImportRoot(cmd *cobra.Command, args []string) error {
if len(args) != 1 {
return fmt.Errorf("Must specify input filename for import")
}
config := k.configGetter()
ks, err := k.getKeyStores(config, true)
if err != nil {
return err
}
cs := cryptoservice.NewCryptoService("", ks...)
importFilename := args[0]
importFile, err := os.Open(importFilename)
if err != nil {
return fmt.Errorf("Opening file for import: %v", err)
}
defer importFile.Close()
err = cs.ImportRootKey(importFile)
if err != nil {
return fmt.Errorf("Error importing root key: %v", err)
}
return nil
}
示例7: keysRestore
// keysRestore imports keys from a ZIP file
func (k *keyCommander) keysRestore(cmd *cobra.Command, args []string) error {
if len(args) < 1 {
cmd.Usage()
return fmt.Errorf("Must specify input filename for import")
}
importFilename := args[0]
config, err := k.configGetter()
if err != nil {
return err
}
ks, err := k.getKeyStores(config, true, false)
if err != nil {
return err
}
cs := cryptoservice.NewCryptoService(ks...)
zipReader, err := zip.OpenReader(importFilename)
if err != nil {
return fmt.Errorf("Opening file for import: %v", err)
}
defer zipReader.Close()
err = cs.ImportKeysZip(zipReader.Reader, k.getRetriever())
if err != nil {
return fmt.Errorf("Error importing keys: %v", err)
}
return nil
}
示例8: keysImportRoot
// keysImportRoot imports a root key from a PEM file
func keysImportRoot(cmd *cobra.Command, args []string) {
if len(args) != 1 {
cmd.Usage()
fatalf("Must specify input filename for import")
}
parseConfig()
cs := cryptoservice.NewCryptoService(
"",
getKeyStores(cmd, mainViper.GetString("trust_dir"), retriever, true)...,
)
importFilename := args[0]
importFile, err := os.Open(importFilename)
if err != nil {
fatalf("Opening file for import: %v", err)
}
defer importFile.Close()
err = cs.ImportRootKey(importFile)
if err != nil {
fatalf("Error importing root key: %v", err)
}
}
示例9: 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()
}
示例10: keysRestore
// keysRestore imports keys from a ZIP file
func keysRestore(cmd *cobra.Command, args []string) {
if len(args) < 1 {
cmd.Usage()
fatalf("Must specify input filename for import")
}
importFilename := args[0]
parseConfig()
cs := cryptoservice.NewCryptoService(
"",
getKeyStores(cmd, mainViper.GetString("trust_dir"), retriever, true)...,
)
zipReader, err := zip.OpenReader(importFilename)
if err != nil {
fatalf("Opening file for import: %v", err)
}
defer zipReader.Close()
err = cs.ImportKeysZip(zipReader.Reader)
if err != nil {
fatalf("Error importing keys: %v", err)
}
}
示例11: keysBackup
// keysBackup exports a collection of keys to a ZIP file
func keysBackup(cmd *cobra.Command, args []string) {
if len(args) < 1 {
cmd.Usage()
fatalf("Must specify output filename for export")
}
parseConfig()
exportFilename := args[0]
cs := cryptoservice.NewCryptoService(
"",
getKeyStores(cmd, mainViper.GetString("trust_dir"), retriever, false)...,
)
exportFile, err := os.Create(exportFilename)
if err != nil {
fatalf("Error creating output file: %v", err)
}
// Must use a different passphrase retriever to avoid caching the
// unlocking passphrase and reusing that.
exportRetriever := getRetriever()
if keysExportGUN != "" {
err = cs.ExportKeysByGUN(exportFile, keysExportGUN, exportRetriever)
} else {
err = cs.ExportAllKeys(exportFile, exportRetriever)
}
exportFile.Close()
if err != nil {
os.Remove(exportFilename)
fatalf("Error exporting keys: %v", err)
}
}
示例12: repositoryFromKeystores
// repositoryFromKeystores is a helper function for NewNotaryRepository that
// takes some basic NotaryRepository parameters as well as keystores (in order
// of usage preference), and returns a NotaryRepository.
func repositoryFromKeystores(baseDir, gun, baseURL string, rt http.RoundTripper,
keyStores []trustmanager.KeyStore) (*NotaryRepository, error) {
certManager, err := certs.NewManager(baseDir)
if err != nil {
return nil, err
}
cryptoService := cryptoservice.NewCryptoService(gun, keyStores...)
nRepo := &NotaryRepository{
gun: gun,
baseDir: baseDir,
baseURL: baseURL,
tufRepoPath: filepath.Join(baseDir, tufDir, filepath.FromSlash(gun)),
CryptoService: cryptoService,
roundTrip: rt,
CertManager: certManager,
}
fileStore, err := store.NewFilesystemStore(
nRepo.tufRepoPath,
"metadata",
"json",
"",
)
if err != nil {
return nil, err
}
nRepo.fileStore = fileStore
return nRepo, nil
}
示例13: TestSignRootOldKeyCertMissing
func TestSignRootOldKeyCertMissing(t *testing.T) {
gun := "docker/test-sign-root"
referenceTime := time.Now()
cs := cryptoservice.NewCryptoService(trustmanager.NewKeyMemoryStore(
passphrase.ConstantRetriever("password")))
rootPublicKey, err := cs.Create(data.CanonicalRootRole, gun, data.ECDSAKey)
require.NoError(t, err)
rootPrivateKey, _, err := cs.GetPrivateKey(rootPublicKey.ID())
require.NoError(t, err)
oldRootCert, err := cryptoservice.GenerateCertificate(rootPrivateKey, gun, referenceTime.AddDate(-9, 0, 0),
referenceTime.AddDate(1, 0, 0))
require.NoError(t, err)
oldRootCertKey := trustmanager.CertToKey(oldRootCert)
repo := initRepoWithRoot(t, cs, oldRootCertKey)
// Create a first signature, using the old key.
signedRoot, err := repo.SignRoot(data.DefaultExpires(data.CanonicalRootRole))
require.NoError(t, err)
verifySignatureList(t, signedRoot, oldRootCertKey)
err = verifyRootSignatureAgainstKey(t, signedRoot, oldRootCertKey)
require.NoError(t, err)
// Create a new certificate
newRootCert, err := cryptoservice.GenerateCertificate(rootPrivateKey, gun, referenceTime, referenceTime.AddDate(10, 0, 0))
require.NoError(t, err)
newRootCertKey := trustmanager.CertToKey(newRootCert)
require.NotEqual(t, oldRootCertKey.ID(), newRootCertKey.ID())
// Only trust the new certificate
err = repo.ReplaceBaseKeys(data.CanonicalRootRole, newRootCertKey)
require.NoError(t, err)
updatedRootRole, err := repo.GetBaseRole(data.CanonicalRootRole)
require.NoError(t, err)
updatedRootKeyIDs := updatedRootRole.ListKeyIDs()
require.Equal(t, 1, len(updatedRootKeyIDs))
require.Equal(t, newRootCertKey.ID(), updatedRootKeyIDs[0])
// Now forget all about the old certificate: drop it from the Root carried keys
delete(repo.Root.Signed.Keys, oldRootCertKey.ID())
repo2 := NewRepo(cs)
repo2.Root = repo.Root
repo2.originalRootRole = updatedRootRole
// Create a second signature
signedRoot, err = repo2.SignRoot(data.DefaultExpires(data.CanonicalRootRole))
require.NoError(t, err)
verifySignatureList(t, signedRoot, newRootCertKey) // Without oldRootCertKey
// Verify that the signature can be verified when trusting the new certificate
err = verifyRootSignatureAgainstKey(t, signedRoot, newRootCertKey)
require.NoError(t, err)
err = verifyRootSignatureAgainstKey(t, signedRoot, oldRootCertKey)
require.Error(t, err)
}
示例14: GetRootCryptoService
// GetRootCryptoService retreives a root key and a cryptoservice to use with it
func (km *KeyStoreManager) GetRootCryptoService(rootKeyID, passphrase string) (*cryptoservice.UnlockedCryptoService, error) {
privKey, err := km.rootKeyStore.GetDecryptedKey(rootKeyID, passphrase)
if err != nil {
return nil, fmt.Errorf("could not get decrypted root key with keyID: %s, %v", rootKeyID, err)
}
cryptoService := cryptoservice.NewCryptoService("", km.rootKeyStore, passphrase)
return cryptoservice.NewUnlockedCryptoService(privKey, cryptoService), nil
}
示例15: CopyKeys
// CopyKeys copies keys of a particular role to a new cryptoservice, and returns that cryptoservice
func CopyKeys(t *testing.T, from signed.CryptoService, roles ...string) signed.CryptoService {
memKeyStore := trustmanager.NewKeyMemoryStore(passphrase.ConstantRetriever("pass"))
for _, role := range roles {
for _, keyID := range from.ListKeys(role) {
key, _, err := from.GetPrivateKey(keyID)
require.NoError(t, err)
memKeyStore.AddKey(trustmanager.KeyInfo{Role: role}, key)
}
}
return cryptoservice.NewCryptoService(memKeyStore)
}