github.com/hyperledger/aries-framework-go@v0.3.2/pkg/internal/didkeyutil/util.go (about)

     1  /*
     2  Copyright Avast Software. All Rights Reserved.
     3  
     4  SPDX-License-Identifier: Apache-2.0
     5  */
     6  
     7  package didkeyutil
     8  
     9  import (
    10  	"strings"
    11  
    12  	"github.com/btcsuite/btcutil/base58"
    13  
    14  	"github.com/hyperledger/aries-framework-go/pkg/vdr/fingerprint"
    15  )
    16  
    17  // ConvertBase58KeysToDIDKeys converts base58 keys array to did:key keys array.
    18  func ConvertBase58KeysToDIDKeys(keys []string) []string {
    19  	var didKeys []string
    20  
    21  	for _, key := range keys {
    22  		if key == "" {
    23  			didKeys = append(didKeys, key)
    24  			continue
    25  		}
    26  
    27  		// skip if the key is a relative did-url (ie, it starts with ?, /, or #)
    28  		if strings.Contains("?/#", string(key[0])) { // nolint:gocritic
    29  			didKeys = append(didKeys, key)
    30  			continue
    31  		}
    32  
    33  		// skip if the key is already a did
    34  		if strings.HasPrefix(key, "did:") {
    35  			didKeys = append(didKeys, key)
    36  			continue
    37  		}
    38  
    39  		rawKey := base58.Decode(key)
    40  		if len(rawKey) == 0 {
    41  			didKeys = append(didKeys, key)
    42  			continue
    43  		}
    44  
    45  		didKey, _ := fingerprint.CreateDIDKey(rawKey)
    46  
    47  		didKeys = append(didKeys, didKey)
    48  	}
    49  
    50  	return didKeys
    51  }
    52  
    53  // ConvertDIDKeysToBase58Keys converts base58 keys array to did:key keys array.
    54  func ConvertDIDKeysToBase58Keys(keys []string) []string {
    55  	var base58Keys []string
    56  
    57  	for _, key := range keys {
    58  		if strings.HasPrefix(key, "did:key:") {
    59  			rawKey, _ := fingerprint.PubKeyFromDIDKey(key) //nolint: errcheck
    60  
    61  			base58Keys = append(base58Keys, base58.Encode(rawKey))
    62  		} else {
    63  			base58Keys = append(base58Keys, key)
    64  		}
    65  	}
    66  
    67  	return base58Keys
    68  }