Swift strict Base64 encode and decode
Swift
import Foundation
enum Base64Error: Error { case invalidInput }
func encodeBase64(_ text: String) -> String {
Data(text.utf8).base64EncodedString()
}
func decodeBase64(_ encoded: String) throws -> String {
let cleaned = encoded.replacingOccurrences(of: "\n", with: "")
.replacingOccurrences(of: " ", with: "")
guard let data = Data(base64Encoded: cleaned),
let text = String(data: data, encoding: .utf8) else {
throw Base64Error.invalidInput
}
return text
}