Alamofire without evaluation and with sending client certificate - ios

Hello i am currently going crazy with alamofire :).
What I'm trying to do is to disable evaluation because server has no valid SSL certificate but I have to connect by https and I have to send a x509 certificate made on IOS device by OpenSSL
I am currently using alamofire 4 and I was trying to do:
open class CertTrustPolicyManager: ServerTrustPolicyManager {
open override func serverTrustPolicy(forHost host: String) -> ServerTrustPolicy? {
let policy = ServerTrustPolicy.disableEvaluation;
// let policy = ServerTrustPolicy.pinCertificates(certificates: [certificateToPin], validateCertificateChain: true, validateHost: false);
// var policy = ServerTrustPolicy.pinCertificates(certificates: [certificateToPin], validateCertificateChain: false, validateHost: false);
return policy
}
let trustPolicies = CertTrustPolicyManager(policies: [:])
let alamofireManager:SessionManager = Alamofire.SessionManager(configuration: configuration, delegate: SessionDelegate(), serverTrustPolicyManager: trustPolicies)
also trying
var serverTrustPolicy:[String: ServerTrustPolicy] = [
Router.baseURLString : .pinCertificates(
certificates: [certificateToPin],
validateCertificateChain: false,
validateHost: false)
]
let alamofireManager:SessionManager = Alamofire.SessionManager(configuration: configuration, delegate: SessionDelegate(), serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicy))
First approach with
let policy = ServerTrustPolicy.disableEvaluation;
gave me successful connection but then I'm unable to pin certificate ( or I don't know how)
second approach produces and god knows whats next :)
2017-05-10 08:37:13.801894+0200 App[10117:1120893] [] nw_coretls_callback_handshake_message_block_invoke_3 tls_handshake_continue: [-9812]
2017-05-10 08:37:13.802 App[10117:1120907] NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9813)
I don't even know if I'm sending it correctly.
any tips?
EDIT this made my connection good but I'm not sending certificate
alamofireManager.delegate.sessionDidReceiveChallenge = { session, challenge in
var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling
var credential: URLCredential?
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
disposition = URLSession.AuthChallengeDisposition.useCredential
credential = URLCredential(trust: challenge.protectionSpace.serverTrust!)
} else {
if challenge.previousFailureCount > 0 {
disposition = .cancelAuthenticationChallenge
} else {
credential = alamofireManager.session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace)
if credential != nil {
disposition = .useCredential
}
}
}
return (disposition, credential)
}
Cheers

Problem self solved.
now the answer for SENDING CLIENT SIDE CERTIFICATE maybe someone will need it :)
We need PKCS12 to send certificate so
import Foundation
public class PKCS12 {
let label:String?
let keyID:NSData?
let trust:SecTrust?
let certChain:[SecTrust]?
let identity:SecIdentity?
public init(PKCS12Data:NSData,password:String)
{
let importPasswordOption:NSDictionary = [kSecImportExportPassphrase as NSString:password]
var items : CFArray?
let secError:OSStatus = SecPKCS12Import(PKCS12Data, importPasswordOption, &items)
guard secError == errSecSuccess else {
if secError == errSecAuthFailed {
NSLog("ERROR: SecPKCS12Import returned errSecAuthFailed. Incorrect password?")
}
fatalError("SecPKCS12Import returned an error trying to import PKCS12 data")
}
guard let theItemsCFArray = items else { fatalError() }
let theItemsNSArray:NSArray = theItemsCFArray as NSArray
guard let dictArray = theItemsNSArray as? [[String:AnyObject]] else { fatalError() }
func f<T>(key:CFString) -> T? {
for d in dictArray {
if let v = d[key as String] as? T {
return v
}
}
return nil
}
self.label = f(key: kSecImportItemLabel)
self.keyID = f(key: kSecImportItemKeyID)
self.trust = f(key: kSecImportItemTrust)
self.certChain = f(key: kSecImportItemCertChain)
self.identity = f(key: kSecImportItemIdentity)
}
}
extension URLCredential {
public convenience init?(PKCS12 thePKCS12:PKCS12) {
if let identity = thePKCS12.identity {
self.init(
identity: identity,
certificates: thePKCS12.certChain,
persistence: URLCredential.Persistence.forSession)
}
else { return nil }
}
}
we need x509 also to do PKCS12 I was in need of generating certificates dynamically so theres the code bridged from C
-(void) createX509{
OPENSSL_init();
NSString *docPath = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents/cert"];
NSString *docPathKey = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents/key"];
NSString *docPathp12 = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents/p12"];
NSString *dataFile = [NSString stringWithContentsOfFile:docPath
encoding:NSUTF8StringEncoding
error:NULL];
FILE *fp = fopen(docPath.UTF8String, "r");
if(fp == NULL){
fp = fopen(docPath.UTF8String, "w+");
FILE *fpKey = fopen(docPathKey.UTF8String, "w+");
EVP_PKEY * pkey;
pkey = EVP_PKEY_new();
RSA * rsa;
rsa = RSA_generate_key(
2048, /* number of bits for the key - 2048 is a sensible value */
RSA_F4, /* exponent - RSA_F4 is defined as 0x10001L */
NULL, /* callback - can be NULL if we aren't displaying progress */
NULL /* callback argument - not needed in this case */
);
EVP_PKEY_assign_RSA(pkey, rsa);
X509 * x509;
x509 = X509_new();
ASN1_INTEGER_set(X509_get_serialNumber(x509), 1);
X509_gmtime_adj(X509_get_notBefore(x509), 0);
X509_gmtime_adj(X509_get_notAfter(x509), 31536000000L);
X509_set_pubkey(x509, pkey);
X509_NAME * name;
name = X509_get_subject_name(x509);
X509_NAME_add_entry_by_txt(name, "C", MBSTRING_ASC,
(unsigned char *)"CA", -1, -1, 0);
X509_NAME_add_entry_by_txt(name, "O", MBSTRING_ASC,
(unsigned char *)"company", -1, -1, 0);
X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC,
(unsigned char *)"localhost", -1, -1, 0);
X509_set_issuer_name(x509, name);
X509_sign(x509, pkey, EVP_sha1());
[#"" writeToFile:docPath
atomically:YES
encoding:NSUTF8StringEncoding
error:NULL];
fp = fopen(docPath.UTF8String, "a+");
PEM_write_X509(
fp, /* write the certificate to the file we've opened */
x509 /* our certificate */);
PEM_write_PrivateKey(fpKey, pkey, NULL, NULL, 0, NULL, NULL);
fflush(fpKey);
fclose(fpKey);
fflush(fp);
fclose(fp);
dataFile = [NSString stringWithContentsOfFile:docPath
encoding:NSUTF8StringEncoding
error:NULL];
OpenSSL_add_all_algorithms();
OpenSSL_add_all_ciphers();
OpenSSL_add_all_digests();
PKCS12* p12;
p12 = PKCS12_create("password", "login", pkey, x509, NULL, 0,0,0,0,0);
if(!p12) {
fprintf(stderr, "Error creating PKCS#12 structure\n");
ERR_print_errors_fp(stderr);
exit(1);
}
fp = fopen(docPathp12.UTF8String, "w+");
if (!(fp = fopen(docPathp12.UTF8String, "wb"))) {
ERR_print_errors_fp(stderr);
exit(1);
}
i2d_PKCS12_fp(fp, p12);
PKCS12_free(p12);
fflush(fp);
fclose(fp);
}
The pkcs12 and x05 is now made so we continue in swift
public let alamofireManager: SessionManager = {
let obj = OpenSSL();
obj.createX509()
var path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first;
var certPEM:String!;
var keyPEM:String!;
var certificateToPin:SecCertificate!;
var pkcs12:PKCS12?;
do{
try certPEM = String(contentsOfFile: path! + "/cert").replacingOccurrences(of: "\n", with: "")
try keyPEM = String(contentsOfFile: path! + "/key").replacingOccurrences(of: "\n", with: "")
let p12 = NSData(contentsOfFile: path! + "/p12");
pkcs12 = PKCS12.init(PKCS12Data: p12!, password: "password")
let docsurl = try! FileManager.default.url(for:.documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let urlAp = docsurl.appendingPathComponent("cert");
var cert64 = certPEM.replacingOccurrences(of: "-----BEGIN CERTIFICATE-----", with: "")
cert64 = cert64.replacingOccurrences(of: "-----END CERTIFICATE-----", with: "")
let certificateData = NSData(base64Encoded: cert64, options: .ignoreUnknownCharacters)
certificateToPin = SecCertificateCreateWithData(kCFAllocatorMalloc, certificateData!)
var trust: SecTrust?
let policy = SecPolicyCreateBasicX509()
let status = SecTrustCreateWithCertificates(certificateToPin!, policy, &trust)
let publicKey:SecKey?;
if status == errSecSuccess {
publicKey = SecTrustCopyPublicKey(trust!)!;
}
let dictionary = SecPolicyCopyProperties(policy)
}catch{
print("err")
}
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForResource = Request.settings.timeout
let trustPolicies = CertTrustPolicyManager(policies: [:])
var serverTrustPolicy:[String: ServerTrustPolicy] = [
Router.baseURLString : .pinCertificates(
certificates: [certificateToPin],
validateCertificateChain: false,
validateHost: false)
]
var alamofireManager:SessionManager = Alamofire.SessionManager(configuration: configuration, delegate: SessionDelegate(), serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicy))
alamofireManager.delegate.sessionDidReceiveChallenge = { session, challenge in
var disposition: URLSession.AuthChallengeDisposition = .useCredential
var credential: URLCredential?
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
disposition = URLSession.AuthChallengeDisposition.useCredential
credential = URLCredential(trust: challenge.protectionSpace.serverTrust!)
} else {
if challenge.previousFailureCount > 0 {
disposition = .cancelAuthenticationChallenge
} else {
credential = alamofireManager.session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace)
if credential != nil {
disposition = .useCredential
}
}
}
let certs = [certificateToPin]
let persist = URLCredential.Persistence.forSession;
return (disposition, URLCredential.init(PKCS12: pkcs12!))
}
return alamofireManager
}()
There I was in need to get certificates, probably some of code is useless or badly wrote but its working ( I'm new to IOS :) ), I was also converting PEM certificates to DER there but after these operations I was finally able to do insecure connection with sending client side and created certificate with Alamofire.
The code above is gathered from everywhere!
Cheers

Related

Decrypting AES/CBC/PKCS5Padding in iOS

I have a file that has been encrypted on Android using this code:
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class AESUtils {
private static final String IV_STRING = "123456789876543";
private String key = "mysecretkey12345";
public static byte[] encryptData(String key, byte[] byteContent) {
byte[] encryptedBytes = null;
try {
byte[] enCodeFormat = key.getBytes();
SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");
byte[] initParam = IV_STRING.getBytes();
IvParameterSpec ivParameterSpec = new IvParameterSpec(initParam);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
encryptedBytes = cipher.doFinal(byteContent);
} catch (Exception e) {
e.printStackTrace();
}
return encryptedBytes;
}
public static byte[] decryptData(String key, byte[] encryptedBytes) {
byte[] result = null ;
try {
byte[] sEnCodeFormat = key.getBytes();
SecretKeySpec secretKey = new SecretKeySpec(sEnCodeFormat, "AES");
byte[] initParam = IV_STRING.getBytes();
IvParameterSpec ivParameterSpec = new IvParameterSpec(initParam);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
result = cipher.doFinal(encryptedBytes);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
I tried to reverse engineer the decryption in Swift using CommonCrypto like this:
import CommonCrypto
let keyStr:String = "mysecretkey12345"
let ivStr:String = "123456789876543"
func aesDecrypt(data:NSData) -> Data? {
let k:NSData = keyStr.data(using: .utf8)! as NSData
let dbytes = data.bytes
let kbytes=k.bytes
if let keyData = keyStr.data(using: .utf8),
let cryptData = NSMutableData(length: Int((data.length)) + kCCBlockSizeAES128) {
let keyLength = size_t(kCCKeySizeAES128)
let operation: CCOperation = UInt32(kCCDecrypt)
let algoritm: CCAlgorithm = UInt32(kCCAlgorithmAES128)
let options: CCOptions = UInt32(kCCOptionPKCS7Padding)
var numBytesEncrypted :size_t = 0
let cryptStatus = CCCrypt(operation,
algoritm,
options,
kbytes, keyLength,
ivStr,
dbytes, data.length,
cryptData.mutableBytes, cryptData.length,
&numBytesEncrypted)
if UInt32(cryptStatus) == UInt32(kCCSuccess) {
cryptData.length = Int(numBytesEncrypted)
return (cryptData.copy() as! Data)
}
else {
return nil
}
}
return nil
}
I am quite new to encryption, but from my research I found that CC uses CBC by default and PKCS7Padding is basically identical to PKCS5Padding. However, the decryption does not deliver the results that I expect!
The swift code was frankensteined together from various sources, including many solutions suggested here on stackoverflow. Main problem is that most examples use key and iv as Data, whereas I have strings - not sure my conversion causes problems. Secondly, many simply convert string messages, whereas I convert data (from files) directly - should not affect it too much, actually makes the code simpler avoiding data->string conversion.
But since it doesn't work, what did I miss?
Okay, I think I figured the problem. Obviously, there is a problem with NSData.bytes and one should work withUnsafeBytes. Furthermore, my issue may was that the IV was not part of the data, as many examples assumed, so I missed 16 bytes when decrypting. The following code works for me, hope it will help someone!
func decrypt(data: Data) -> Data {
let key: Data = keyStr.data(using: .utf8) ?? Data()
let iv: Data = ivStr.data(using: .utf8) ?? Data()
if(keyStr.count == kCCKeySizeAES128){print("Key OKAY")} else {print("Key NOT okay")}
if(ivStr.count == kCCBlockSizeAES128){print("IV OKAY")} else {print("IV NOT okay")}
var buffer = Data(count: data.count)
var numberBytesDecrypted: Int = 0
let cryptStatus: CCCryptorStatus = key.withUnsafeBytes {keyBytes in
data.withUnsafeBytes {dataBytes in
buffer.withUnsafeMutableBytes {bufferBytes in iv.withUnsafeBytes {ivBytes in
CCCrypt( // Stateless, one-shot encrypt operation
CCOperation(kCCDecrypt), // op: CCOperation
CCAlgorithm(kCCAlgorithmAES128), // alg: CCAlgorithm
CCOptions(kCCOptionPKCS7Padding), // options: CCOptions
keyBytes.baseAddress, // key: the "password"
key.count, // keyLength: the "password" size
ivBytes.baseAddress, // iv: Initialization Vector
dataBytes.baseAddress!, // dataIn: Data to decrypt bytes
data.count, // dataInLength: Data to decrypt size
bufferBytes.baseAddress, // dataOut: decrypted Data buffer
data.count, // dataOutAvailable: decrypted Data buffer size
&numberBytesDecrypted // dataOutMoved: the number of bytes written
)}
}
}
}
if(cryptStatus == CCCryptorStatus(kCCSuccess)){
return buffer[..<numberBytesDecrypted]
} else {
print("Decryption failed")
return data
}
}
Okay, turned out one of my test files was corrupted and my decryption worked all along. Here is a simpler version without withUnsafeBytes:
func decrypt(data: Data) -> Data {
let key:Data = keyStr.data(using: .utf8)!
let iv:Data = ivStr.data(using: .utf8)!
var buffer = [UInt8](repeating: 0, count: data.count + kCCBlockSizeAES128)
var bufferLen: Int = 0
let status = CCCrypt(
CCOperation(kCCDecrypt),
CCAlgorithm(kCCAlgorithmAES128),
CCOptions(kCCOptionPKCS7Padding),
[UInt8](key),
kCCBlockSizeAES128,
[UInt8](iv),
[UInt8](data),
data.count,
&buffer,
buffer.count,
&bufferLen
)
if(status == kCCSuccess) {
return Data(bytes: buffer, count: bufferLen)}
else {
print("Decryption failed")
return data
}
}

Upload image to S3 with Amazon Educate Starter Account

I just want to upload an image to S3, but I am using AWS Educate Account and I'm trying since 4 hours to get this done and have ZERO ideas what isn't working correctly.
So I've set up everything on the AWS console and the bucket is public to EVERYONE + Region US West N.Virginia like it should be with AWS Educate Accounts.
So here is my code:
let accessKey = "accessKey"
let secretKey = "secretKey"
let credentialsProvider = AWSStaticCredentialsProvider(accessKey: accessKey, secretKey: secretKey)
let configuration = AWSServiceConfiguration(region: AWSRegionType.USEast1, credentialsProvider: credentialsProvider)
AWSServiceManager.default().defaultServiceConfiguration = configuration
let transferUtility = AWSS3TransferUtility.default()
let bucketname = "bucketname"
let expression = AWSS3TransferUtilityUploadExpression()
transferUtility.uploadData(jpegData, bucket: bucketname, key: "myTransferUtilityUpload.jpg", contentType: "image/jpg", expression: expression) { (task, error) in
if let error = error {
print(error.localizedDescription)
}
if let response = task.response {
print(response)
}
}
Can anyone tell me what I do wrong?
I get this error message:
The operation couldn’t be completed.
(com.amazonaws.AWSS3TransferUtilityErrorDomain error 2.)
accessKey + secretKey I got from Account Details + AWS CLI on the 'Welcome to AWS Educate Starter Account' Dashboard and obviously the bucket name is the same name like in my console
EDIT:
if let jpegData = image.jpegData(compressionQuality: 0.7) {
let fileManager = FileManager.default
if let documentDirectory = fileManager.urls(for: .documentDirectory,
in: .userDomainMask).first {
var sourceFolderURL = documentDirectory.appendingPathComponent("image.jpg")
do {
try jpegData.write(to: sourceFolderURL)
} catch {
print(error.localizedDescription)
completionHandler(nil)
return
}
let accessKey = "-"
let secretKey = "-"
let bucketname = "-"
let credentialsProvider = AWSStaticCredentialsProvider(accessKey: accessKey, secretKey: secretKey)
let configuration = AWSServiceConfiguration(region: AWSRegionType.USEast1, credentialsProvider: credentialsProvider)
AWSServiceManager.default().defaultServiceConfiguration = configuration
let uploadRequest = AWSS3TransferManagerUploadRequest()!
uploadRequest.body = sourceFolderURL
uploadRequest.key = "image.jpg"
uploadRequest.bucket = bucketname
uploadRequest.contentType = "image/jpeg"
uploadRequest.acl = .publicReadWrite
let transferManager = AWSS3TransferManager.default()
transferManager.upload(uploadRequest).continueWith { [weak self] (task) -> Any? in
if let error = task.error {
print("Upload failed with error: (\(error.localizedDescription))")
completionHandler(nil)
return nil
}
if task.result != nil {
let url = AWSS3.default().configuration.endpoint.url
let publicURL = url?.appendingPathComponent(uploadRequest.bucket!).appendingPathComponent(uploadRequest.key!)
if let absoluteString = publicURL?.absoluteString {
print("Uploaded to:\(absoluteString)")
completionHandler(nil)
}
}
completionHandler(nil)
return nil
}
}
}
I have uploaded an image to S3 bucket with the following code:
First, save the image to a temporary directory.
func uploadImageToS3(imageName:String, completion:#escaping (Bool) -> Void) {
let accessKey = "accessKey"
let secretKey = "secretKey"
let credentialsProvider = AWSStaticCredentialsProvider(accessKey: accessKey, secretKey: secretKey)
let configuration = AWSServiceConfiguration(region:AWSRegionType.APSoutheast2, credentialsProvider:credentialsProvider)
AWSServiceManager.default().defaultServiceConfiguration = configuration
let S3BucketName = "bucketname"
let uploadRequest = AWSS3TransferManagerUploadRequest()!
uploadRequest.body = self.getImageURLWithName(imageName:imageName)
uploadRequest.key = "\(imageName)"
uploadRequest.bucket = S3BucketName
uploadRequest.contentType = "image/jpeg"
//You can specify private or public here
uploadRequest.acl = .private
let transferManager = AWSS3TransferManager.default()
transferManager.upload(uploadRequest).continueWith { [weak self] (task) -> Any? in
ProgressIndicatorHelper.hideGlobalHUD()
if let error = task.error {
print("Upload failed with error: (\(error.localizedDescription))")
completion(false)
}
if task.result != nil {
let url = AWSS3.default().configuration.endpoint.url
let publicURL = url?.appendingPathComponent(uploadRequest.bucket!).appendingPathComponent(uploadRequest.key!)
if let absoluteString = publicURL?.absoluteString {
print("Uploaded to:\(absoluteString)")
completion(true)
}
}
return nil
}
}
For getting image from Path following code I have used:
func getImageURLWithName(imageName:String) -> URL {
var sourceImageURL: URL!
let fileManager = FileManager.default
if let documentDirectory = fileManager.urls(for: .documentDirectory,
in: .userDomainMask).first {
var sourceFolderURL:URL!
sourceFolderURL = documentDirectory.appendingPathComponent("YourTempFolder")
sourceImageURL = sourceFolderURL.appendingPathComponent(imageName)
}
return sourceImageURL
}
Hope this helps.
Moreover: Right now I don't think you can directly upload image from memory.
I searched for it. Following are links for same:
https://github.com/aws-amplify/aws-sdk-ios/issues/42
How to upload a UIImage to S3 with AWS iOS SDK v2
Let me know if you find any error.
Maybe it's a policy issue?
Try attaching this policy to your bucket (bucket policies)
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:*"
],
"Resource": [
"arn:aws:s3:::mybucketname/*"
]
}
]
}

Migrate from unencrypted realm to encrypted realm

I'm trying to migrate from unencrypted realm to encrypted but I don't know how and where to use Realm().writeCopy(toFile: url, encryptionKey: key).
or even if there is another way to do it.
Thank you.
I found a way to do that, you can find it below:
private static var realm: Realm! {
// Get the encryptionKey
var realmKey = Keychain.realmKey
if realmKey == nil {
var key = Data(count: 64)
key.withUnsafeMutableBytes { (bytes) -> Void in
_ = SecRandomCopyBytes(kSecRandomDefault, 64, bytes)
}
realmKey = key
Keychain.realmKey = realmKey
}
// Check if the user has the unencrypted Realm
let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let fileManager = FileManager.default
let unencryptedRealmPath = "\(documentDirectory)/default.realm"
let encryptedPath = "\(documentDirectory)/default_new.realm"
let isUnencryptedRealmExsist = fileManager.fileExists(atPath: unencryptedRealmPath)
let isEncryptedRealmExsist = fileManager.fileExists(atPath: encryptedPath)
if isUnencryptedRealmExsist && !isEncryptedRealmExsist {
let unencryptedRealm = try! Realm(configuration: Realm.Configuration(schemaVersion: 7))
// if the user has unencrypted Realm write a copy to new path
try? unencryptedRealm.writeCopy(toFile: URL(fileURLWithPath: encryptedPath), encryptionKey: realmKey)
}
// read from the new encrypted Realm path
let configuration = Realm.Configuration(fileURL: URL(fileURLWithPath: encryptedPath), encryptionKey: realmKey, schemaVersion: 7, migrationBlock: { migration, oldSchemaVersion in })
return try! Realm(configuration: configuration)
}
According to #Abedalkareem Omreyh's answer
You can also Retrieve the existing encryption key for the app if it exists or create a new one.
func getencryptionKey() -> Data {
// Identifier for our keychain entry - should be unique for your application
let keychainIdentifier = "io.Realm.EncryptionExampleKey"
let keychainIdentifierData = keychainIdentifier.data(using: String.Encoding.utf8, allowLossyConversion: false)!
// First check in the keychain for an existing key
var query: [NSString: AnyObject] = [
kSecClass: kSecClassKey,
kSecAttrApplicationTag: keychainIdentifierData as AnyObject,
kSecAttrKeySizeInBits: 512 as AnyObject,
kSecReturnData: true as AnyObject
]
// To avoid Swift optimization bug, should use withUnsafeMutablePointer() function to retrieve the keychain item
// See also: http://stackoverflow.com/questions/24145838/querying-ios-keychain-using-swift/27721328#27721328
var dataTypeRef: AnyObject?
var status = withUnsafeMutablePointer(to: &dataTypeRef) { SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0)) }
if status == errSecSuccess {
// swiftlint:disable:next force_cast
return dataTypeRef as! Data
}
// No pre-existing key from this application, so generate a new one
// Generate a random encryption key
var key = Data(count: 64)
key.withUnsafeMutableBytes({ (pointer: UnsafeMutableRawBufferPointer) in
let result = SecRandomCopyBytes(kSecRandomDefault, 64, pointer.baseAddress!)
assert(result == 0, "Failed to get random bytes")
})
// Store the key in the keychain
query = [
kSecClass: kSecClassKey,
kSecAttrApplicationTag: keychainIdentifierData as AnyObject,
kSecAttrKeySizeInBits: 512 as AnyObject,
kSecValueData: key as AnyObject
]
status = SecItemAdd(query as CFDictionary, nil)
assert(status == errSecSuccess, "Failed to insert the new key in the keychain")
return key
}
// ...
// Use the getKey() function to get the stored encryption key or create a new one
var config = Realm.Configuration(encryptionKey: getKey())
do {
// Open the realm with the configuration
let realm = try Realm(configuration: config)
// Use the realm as normal
} catch let error as NSError {
// If the encryption key is wrong, `error` will say that it's an invalid database
fatalError("Error opening realm: \(error)")
}
you can use this encryption Key for above code and don't need to check nil value of key.
// Get the encryptionKey
var realmKey = getencryptionKey()
Reference link Encrypt a Realm

Download file from AZURE with REST API for iOS Swift 3

I want to download file from azure with REST API and I written below code for iOS Swift >3, but when I run the download task, get this error:
InvalidHeaderValueThe value for one of the HTTP headers is not in the correct format.
RequestId:10d9c8f8-001a-00db-283c-1ab1d1000000
Time:2017-08-21T05:14:18.2768791Zx-ms-version
private let account = "myAccount"
private let key = "My key is encrypted as base64"
private let fileName = "My file name which have to download"
private let SHARE_NAME = "My share name"
let date = Date().currentTimeZoneDate() + " GMT"
func downloadFileFromAzure(fileName:String)
{
// Create destination URL
let documentsUrl:URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL!
let destinationFileUrl = documentsUrl.appendingPathComponent(fileName)
//Create URL to the source file you want to download
let fileURL = URL(string: "https://\(account).file.core.windows.net/\(SHARE_NAME)/\(fileName)")!
//create session
let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig)
//create headers field
var request = URLRequest(url:fileURL)
request.setValue(date,forHTTPHeaderField: "x-ms-date")
request.setValue("2014-02-14", forHTTPHeaderField: "x-ms-version")
request.setValue("\(getFileRequest(account:account, fileName: fileName))", forHTTPHeaderField: "Authorization")
//download files
let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
if let tempLocalUrl = tempLocalUrl, error == nil {
// Success
if let statusCode = (response as? HTTPURLResponse)?.statusCode {
print("Successfully downloaded. Status code: \(statusCode)")
}
do {
try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
print("tempLocalUrl: \(tempLocalUrl)")
print("destinationFileUrl: \(destinationFileUrl)")
//reading
do {
let text = try String(contentsOf: destinationFileUrl, encoding: String.Encoding.utf8)
print("reading files data : \(text)")
}
catch (let writeError){
print("Error reading a file \(writeError)")
}
} catch (let writeError) {
print("Error creating a file \(destinationFileUrl) : \(writeError)")
}
} else {
print("Error took place while downloading a file. Error description: %#", error?.localizedDescription);
}
}
task.resume()
}
public func getFileRequest(account:String,fileName:String)->String
{
let canonicalizedResources = "/\(account)/\(SHARE_NAME)/\(fileName)"
let canonicalizedHeaders = "x-ms-date:\(date)\nx-ms-version:2014-02-14"
let stringToSign = "GET\n\n\n\n\n\n\n\n\n\n\n\n\(canonicalizedHeaders)\n\(canonicalizedResources)"
let auth = getAuthenticationString(stringToSign:stringToSign);
return auth
}
///getAuthenticationString
public func getAuthenticationString(stringToSign:String)->String
{
let authKey: String = stringToSign.hmac(algorithm: HMACAlgorithm.SHA256, key: key)
let auth = "SharedKey " + account + ":" + authKey;
return auth;
}
enum HMACAlgorithm
{
case MD5, SHA1, SHA224, SHA256, SHA384, SHA512;
func toCCHmacAlgorithm() -> CCHmacAlgorithm {
var result: Int = 0
switch self {
case .MD5:
result = kCCHmacAlgMD5
case .SHA1:
result = kCCHmacAlgSHA1
case .SHA224:
result = kCCHmacAlgSHA224
case .SHA256:
result = kCCHmacAlgSHA256
case .SHA384:
result = kCCHmacAlgSHA384
case .SHA512:
result = kCCHmacAlgSHA512
}
return CCHmacAlgorithm(result)
}
func digestLength() -> Int {
var result: CInt = 0
switch self {
case .MD5:
result = CC_MD5_DIGEST_LENGTH
case .SHA1:
result = CC_SHA1_DIGEST_LENGTH
case .SHA224:
result = CC_SHA224_DIGEST_LENGTH
case .SHA256:
result = CC_SHA256_DIGEST_LENGTH
case .SHA384:
result = CC_SHA384_DIGEST_LENGTH
case .SHA512:
result = CC_SHA512_DIGEST_LENGTH
}
return Int(result)
}
}
extension String {
func hmac(algorithm: HMACAlgorithm, key: String) -> String {
let keyBytes = key.base64DecodeAsData()
let dataBytes = self.cString(using: String.Encoding.utf8)
var result = [CUnsignedChar](repeating: 0, count: Int(algorithm.digestLength()))
CCHmac(algorithm.toCCHmacAlgorithm(), keyBytes.bytes, keyBytes.length, dataBytes!, Int(strlen(dataBytes!)), &result)
let hmacData:NSData = NSData(bytes: result, length: (Int(algorithm.digestLength())))
let hmacBase64 = hmacData.base64EncodedString(options: NSData.Base64EncodingOptions.lineLength76Characters)
return String(hmacBase64)
}
func base64DecodeAsData() -> NSData {
let decodedData = NSData(base64Encoded: self, options: NSData.Base64DecodingOptions(rawValue: 0))
return decodedData!
}
Edit:
I only get this error in the Xcode.
InvalidHeaderValueThe value for one of the HTTP headers is not in the correct format.
RequestId:10d9c8f8-001a-00db-283c-1ab1d1000000
Time:2017-08-21T05:14:18.2768791Zx-ms-version
But when I tried sharedKey(which is generated in ios) in the android source get this error:
AuthenticationFailedServer failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.equestId:379c5c1b-001a-0017-1a19-1bd564000000ime:2017-08-22T07:38:04.8712051ZThe MAC signature found in the HTTP request 'tJcl9LyzF2BzlZMdW9ULtMojDamn9HnEY9LulpDOsYg=' is not the same as any computed signature. Server used following string to sign: 'GETx-ms-date:Tue, 22 Aug 2017 07:32:52 GMT-ms-version:2014-02-14account/SHARE_NAME/fileName'.
SOLVED
Change this line
let hmacBase64 = hmacData.base64EncodedString(options: NSData.Base64EncodingOptions.lineLength76Characters)
To:
let hmacBase64 = hmacData.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
Also change this line
let stringToSign = "GET\n\n\n\n\n\n\n\n\n\n\n\n(canonicalizedHeaders)\n(canonicalizedResources)"
To:
let stringToSign = "GET\n"
+ "\n" // content encoding
+ "\n" // content language
+ "\n" // content length
+ "\n" // content md5
+ "\n" // content type
+ "\n" // date
+ "\n" // if modified since
+ "\n" // if match
+ "\n" // if none match
+ "\n" // if unmodified since
+ "\n" // range
+ "(canonicalizedHeaders)\n" //headers
+ "(canonicalizedResources)"// resources
Please delete your stored file before create new one by this func:
func deleteFileFromDirectory(fileNameToDelete:String)
{
var filePath = ""
// Fine documents directory on device
let dirs : [String] = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.allDomainsMask, true)
if dirs.count > 0 {
let dir = dirs[0] //documents directory
filePath = dir.appendingFormat("/" + fileNameToDelete)
print("Local path = \(filePath)")
} else {
print("Could not find local directory to store file")
return
}
do {
let fileManager = FileManager.default
// Check if file exists
if fileManager.fileExists(atPath: filePath) {
// Delete file
try fileManager.removeItem(atPath: filePath)
} else {
print("File does not exist")
}
}
catch let error as NSError {
print("An error took place: \(error)")
}
}
I believe the problem is in these 2 lines of code:
let canonicalizedHeaders = "x-ms-date:\(date)\nx-ms-version:2016-05-31\n"
let stringToSign = "GET\n\n\n\n\n\n\n\n\n\n\n\n\(canonicalizedHeaders)\n\(canonicalizedResources)"
I noticed there's an extra new line character (\n). Can you either remove the \n character at the end of canonicalizedHeaders or between (canonicalizedHeaders) and (canonicalizedResources) in stringToSign?

Alamofire cert pinning doesn't blocking requests

I've some trouble about SSL Pinning in Alamofire. I've examine all the document that I can found but I couldn't manage to handle it. I might get it wrong.
Currently, I am working on an example
https://github.com/antekarin/ios-ssl-pinning
I converted it to swift 3 and updated the pods to the latest version of Alamofire.
To make it clear; the project is use "github.com.cer" certificate, and because I define domain (like below) I expect to get success when I go to "https://github.com" and to get failure when I enter (in example) "https://twitter.com". But in every condition my request return some value and does not block other requests.
self.serverTrustPolicies = [
"github.com": self.serverTrustPolicy!
]
Code:
let githubCert = "github.com"
let corruptedCert = "corrupted"
var urlSession: Foundation.URLSession!
var serverTrustPolicy: ServerTrustPolicy!
var serverTrustPolicies: [String: ServerTrustPolicy]!
var afManager: SessionManager!
var isSimulatingCertificateCorruption = false
override func viewDidLoad() {
super.viewDidLoad()
self.configureAlamoFireSSLPinning()
self.configureURLSession()
self.activityIndicator.hidesWhenStopped = true
}
// MARK: SSL Config
func configureAlamoFireSSLPinning() {
let pathToCert = Bundle.main.path(forResource: githubCert, ofType: "cer")
let localCertificate:NSData = NSData(contentsOfFile: pathToCert!)!
self.serverTrustPolicy = ServerTrustPolicy.pinCertificates(
certificates: [SecCertificateCreateWithData(nil, localCertificate)!],
validateCertificateChain: true,
validateHost: true
)
self.serverTrustPolicies = [
"github.com": self.serverTrustPolicy!
]
self.afManager = SessionManager(
configuration: URLSessionConfiguration.default,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: self.serverTrustPolicies)
)
}
// MARK: Button actions
#IBAction func alamoFireRequestHandler(_ sender: UIButton) {
self.activityIndicator.startAnimating()
if let urlText = self.urlTextField.text {
self.afManager.request(urlText).responseString { response in
guard let data = response.data, response.error == nil else {
self.responseTextView.text = response.error.debugDescription
self.responseTextView.textColor = UIColor.red
return
}
self.responseTextView.text = String(data: data, encoding: String.Encoding.utf8)!
self.responseTextView.textColor = UIColor.black
}
}
}

Resources