Skip to content

Commit 6fea7ec

Browse files
committed
add new function EncryptLegacy to prepare for credential rotation
1 parent 974e765 commit 6fea7ec

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

apikey.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,28 @@ func (k *ApiKey) DecryptData(ciphertext []byte) ([]byte, error) {
113113
return plaintext, nil
114114
}
115115

116+
// EncryptLegacy uses the Secret to AES encrypt an arbitrary data block. This is intended only for legacy data such
117+
// as U2F keys. The returned data is the Base64-encoded IV and the Base64-encoded cipher text separated by a colon.
118+
func (k *ApiKey) EncryptLegacy(plaintext []byte) ([]byte, error) {
119+
block, err := newCipherBlock(k.Secret)
120+
if err != nil {
121+
return nil, err
122+
}
123+
124+
iv := make([]byte, aes.BlockSize)
125+
if _, err = io.ReadFull(rand.Reader, iv); err != nil {
126+
return nil, fmt.Errorf("failed to create random data for initialization vector: %w", err)
127+
}
128+
129+
ciphertext := make([]byte, len(plaintext))
130+
stream := cipher.NewCTR(block, iv)
131+
stream.XORKeyStream(ciphertext, plaintext)
132+
133+
ivBase64 := base64.StdEncoding.EncodeToString(iv)
134+
cipherBase64 := base64.StdEncoding.EncodeToString(ciphertext)
135+
return []byte(ivBase64 + ":" + cipherBase64), nil
136+
}
137+
116138
// DecryptLegacy uses the Secret to AES decrypt an arbitrary data block. This is intended only for legacy data such
117139
// as U2F keys.
118140
func (k *ApiKey) DecryptLegacy(ciphertext []byte) ([]byte, error) {

apikey_test.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,17 @@ func TestApiKey_EncryptDecrypt(t *testing.T) {
129129
}
130130
}
131131

132+
func (ms *MfaSuite) TestApiKeyEncryptDecryptLegacy() {
133+
plaintext := []byte("this is a plaintext string to be encrypted")
134+
key := &ApiKey{Secret: "ED86600E-3DBF-4C23-A0DA-9C55D448"}
135+
136+
encrypted, err := key.EncryptLegacy(plaintext)
137+
ms.NoError(err)
138+
decrypted, err := key.DecryptLegacy(encrypted)
139+
ms.NoError(err)
140+
ms.Equal(plaintext, decrypted)
141+
}
142+
132143
func (ms *MfaSuite) TestApiKeyActivate() {
133144
notActive := ApiKey{
134145
Key: "0000000000000000000000000000000000000000",

0 commit comments

Comments
 (0)