Skip to content

Instantly share code, notes, and snippets.

@1f604
Last active June 16, 2021 21:25
Show Gist options
  • Save 1f604/f573269488fd21fa3f1bd5057b6bee13 to your computer and use it in GitHub Desktop.
Save 1f604/f573269488fd21fa3f1bd5057b6bee13 to your computer and use it in GitHub Desktop.
Swift to golang AES-GCM encryption decryption working example code
// The following code has been tested. It compiles and works.
// Swift code
func encrypt(input: [UInt8]) -> Data? {
let key = SymmetricKey(size: .bits256)
let key64 = key.withUnsafeBytes {
return Data(Array($0)).base64EncodedString()
}
print("key64:", key64)
var sealedBox: AES.GCM.SealedBox
do {
try sealedBox = AES.GCM.seal(input, using: key)
print("Combined:\n\(sealedBox.combined!.base64EncodedString())\n") // pass this to the decrypt function
return sealedBox.combined!
} catch {
print("seal failed!")
return nil
}
}
// Go golang code
func decrypt(s string) string { // parameter is the sealedBox.combined!.base64EncodedString() output.
key := decode64(key64)
bytes := decode64(s) //convert base 64 to bytes
nonce := bytes[0:12] //get the nonce
ciphertext := bytes[12:] //get the ciphertext + tag. DO NOT split out the tag!
block, err := aes.NewCipher(key)
if err != nil {
panic(err.Error())
}
aesgcm, err := cipher.NewGCM(block)
if err != nil {
panic(err.Error())
}
plaintext, err := aesgcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
panic(err.Error())
}
fmt.Printf("%s\n", plaintext)
return string(plaintext)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment