0

I need to generate Data from an user password in Swift. I'm currently using:

let password = "replace_it_for_smt_related_to_the_user"
var securityKey:Data! = Data()
securityKey = self.password.data(using: .utf16, allowLossyConversion: true)?.subdata(in: 0...32)

But then, using it with a library, I get the error: "securityKey must be 256 bits". I don't really care about the encoding type, but I need to create Data from a string that is 256 bits. Any help?

Thanks

Jaime Alcántara Arnela
  • 2,062
  • 5
  • 25
  • 56
  • 256 bits is equal to `256/8 = 32 bytes`. Using ASCII encoding (1 byte per character), your string must be 32 ASCII characters long. Using `UTF-8` encoding, a character can take anywhere from 1 to 4 bytes. So it depends on what your password is to create the correct length `Data`. What's likely in this case is that you should hash your password to a fixed size of 32 bytes, this way, any password when hashed and transformed to `Data` will be of the correct length. [128 bit MD5 hashing will produce a hash of 32 bits when represented as hexadecimal](https://stackoverflow.com/a/6317289/1305067). – paulvs Aug 22 '17 at 13:09
  • `subdata(in: 0...32)` extracts **33** bytes = 264 bits. Perhaps you meant `subdata(in: 0..<32)` ? – Martin R Aug 22 '17 at 13:33
  • @MartinR well that was probably one problem. I've solved with the answer below but thanks anyway. – Jaime Alcántara Arnela Aug 28 '17 at 10:44

1 Answers1

1

Make use of extension:

extension String{
 //convert base64 string to string
  func decodeToBase64() -> String {
    return Data(self.utf8).base64EncodedString()
  }

//convert string to base64 String
func encodeFromBase64() -> String? {
    guard let data = Data(base64Encoded: self) else {
      return nil
    }
    return String(data: data, encoding: .utf8)
  }

}

How to use it:

let pwdStr = "replace_it_for_smt_related_to_the_user".decodeToBase64()//use extension method
print(pwdStr)
Brijesh Shiroya
  • 3,323
  • 1
  • 13
  • 20