File tree Expand file tree Collapse file tree 2 files changed +33
-0
lines changed Expand file tree Collapse file tree 2 files changed +33
-0
lines changed Original file line number Diff line number Diff line change @@ -113,6 +113,28 @@ func (k *ApiKey) DecryptData(ciphertext []byte) ([]byte, error) {
113
113
return plaintext , nil
114
114
}
115
115
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
+
116
138
// DecryptLegacy uses the Secret to AES decrypt an arbitrary data block. This is intended only for legacy data such
117
139
// as U2F keys.
118
140
func (k * ApiKey ) DecryptLegacy (ciphertext []byte ) ([]byte , error ) {
Original file line number Diff line number Diff line change @@ -129,6 +129,17 @@ func TestApiKey_EncryptDecrypt(t *testing.T) {
129
129
}
130
130
}
131
131
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
+
132
143
func (ms * MfaSuite ) TestApiKeyActivate () {
133
144
notActive := ApiKey {
134
145
Key : "0000000000000000000000000000000000000000" ,
You can’t perform that action at this time.
0 commit comments