wireguard-apple/WireGuard/Shared/Model/Data+KeyEncoding.swift

55 lines
1.4 KiB
Swift
Raw Normal View History

2019-02-07 23:44:14 +00:00
// SPDX-License-Identifier: MIT
// Copyright © 2018-2019 WireGuard LLC. All Rights Reserved.
import Foundation
extension Data {
func isKey() -> Bool {
return self.count == WG_KEY_LEN
2019-02-07 23:44:14 +00:00
}
func hexKey() -> String? {
if self.count != WG_KEY_LEN {
2019-02-07 23:44:14 +00:00
return nil
}
var out = Data(repeating: 0, count: Int(WG_KEY_LEN_HEX))
out.withUnsafeMutableBytes { outBytes in
self.withUnsafeBytes { inBytes in
key_to_hex(outBytes, inBytes)
}
2019-02-07 23:44:14 +00:00
}
out.removeLast()
return String(data: out, encoding: .ascii)
2019-02-07 23:44:14 +00:00
}
init?(hexKey hexString: String) {
self.init(repeating: 0, count: Int(WG_KEY_LEN))
2019-02-07 23:44:14 +00:00
if !self.withUnsafeMutableBytes { key_from_hex($0, hexString) } {
2019-02-07 23:44:14 +00:00
return nil
}
}
func base64Key() -> String? {
if self.count != WG_KEY_LEN {
2019-02-07 23:44:14 +00:00
return nil
}
var out = Data(repeating: 0, count: Int(WG_KEY_LEN_BASE64))
out.withUnsafeMutableBytes { outBytes in
self.withUnsafeBytes { inBytes in
key_to_base64(outBytes, inBytes)
}
2019-02-07 23:44:14 +00:00
}
out.removeLast()
return String(data: out, encoding: .ascii)
2019-02-07 23:44:14 +00:00
}
init?(base64Key base64String: String) {
self.init(repeating: 0, count: Int(WG_KEY_LEN))
2019-02-07 23:44:14 +00:00
if !self.withUnsafeMutableBytes { key_from_base64($0, base64String) } {
2019-02-07 23:44:14 +00:00
return nil
}
}
}