diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 5eede1e44..06887e5c8 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -99,8 +99,8 @@ jobs: - name: Set up Homebrew id: set-up-homebrew uses: Homebrew/actions/setup-homebrew@master - - name: Install Swift-sh - run: brew install swift-sh + - name: Install Swift-sh and FlatBuffers + run: brew install swift-sh flatbuffers - name: Build and Archive env: APP_PROVISIONING_PROFILE_UUID: ${{ secrets.APP_PROVISIONING_PROFILE_UUID }} diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index a9411675e..d0c717f92 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -26,6 +26,9 @@ jobs: with: submodules: recursive + - name: Install FlatBuffers + run: brew install flatbuffers + # Creating sample files needed to build, but not needed for CodeQL. # .plist files need a sample structure to avoid error: "unable to read input file as a property list" - name: Create sample files diff --git a/CryptoLib/CryptoLib.xcodeproj/project.pbxproj b/CryptoLib/CryptoLib.xcodeproj/project.pbxproj index 53f584122..dd62d9e99 100644 --- a/CryptoLib/CryptoLib.xcodeproj/project.pbxproj +++ b/CryptoLib/CryptoLib.xcodeproj/project.pbxproj @@ -9,28 +9,24 @@ /* Begin PBXBuildFile section */ 39231FAF20AB1C6C00E1E2B4 /* CryptoLib.h in Headers */ = {isa = PBXBuildFile; fileRef = 39231FAD20AB1C6C00E1E2B4 /* CryptoLib.h */; settings = {ATTRIBUTES = (Public, ); }; }; 39266A5120CFBDF8002E3F23 /* SmartCardTokenWrapper.mm in Sources */ = {isa = PBXBuildFile; fileRef = 39266A5020CFBDF8002E3F23 /* SmartCardTokenWrapper.mm */; }; - 39266A5D20CFDC59002E3F23 /* CdocParser.m in Sources */ = {isa = PBXBuildFile; fileRef = 39266A5C20CFDC59002E3F23 /* CdocParser.m */; }; - 39266A5F20CFDCB9002E3F23 /* CdocInfo.m in Sources */ = {isa = PBXBuildFile; fileRef = 39266A5E20CFDCB9002E3F23 /* CdocInfo.m */; }; - 39266A6320CFE3D4002E3F23 /* CdocParserDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 39266A6220CFE3D4002E3F23 /* CdocParserDelegate.m */; }; - 39266A6420CFE63D002E3F23 /* CdocParser.h in Headers */ = {isa = PBXBuildFile; fileRef = 39266A5B20CFDC41002E3F23 /* CdocParser.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 39266A6520CFE643002E3F23 /* CdocInfo.h in Headers */ = {isa = PBXBuildFile; fileRef = 39266A6020CFDCDF002E3F23 /* CdocInfo.h */; settings = {ATTRIBUTES = (Public, ); }; }; 393B66E020DB94B4001DC89B /* cdoc.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 393B66DF20DB94B4001DC89B /* cdoc.framework */; }; - 3960E50520C02E5900D4D2FC /* CryptoDataFile.m in Sources */ = {isa = PBXBuildFile; fileRef = 3960E50420C02E5900D4D2FC /* CryptoDataFile.m */; }; - 3960E50620C044EE00D4D2FC /* CryptoDataFile.h in Headers */ = {isa = PBXBuildFile; fileRef = 3960E50320C02DA400D4D2FC /* CryptoDataFile.h */; settings = {ATTRIBUTES = (Public, ); }; }; 39852A4B20AB2418004CB100 /* Decrypt.h in Headers */ = {isa = PBXBuildFile; fileRef = 39852A4120AB2418004CB100 /* Decrypt.h */; settings = {ATTRIBUTES = (Public, ); }; }; 39852A4C20AB2418004CB100 /* Encrypt.h in Headers */ = {isa = PBXBuildFile; fileRef = 39852A4220AB2418004CB100 /* Encrypt.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 39852A5020AB2418004CB100 /* DdocParserDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 39852A4620AB2418004CB100 /* DdocParserDelegate.m */; }; 39852A5120AB2418004CB100 /* SmartCardTokenWrapper.h in Headers */ = {isa = PBXBuildFile; fileRef = 39852A4720AB2418004CB100 /* SmartCardTokenWrapper.h */; }; 39852A5220AB2418004CB100 /* Decrypt.mm in Sources */ = {isa = PBXBuildFile; fileRef = 39852A4820AB2418004CB100 /* Decrypt.mm */; }; 39852A5320AB2418004CB100 /* Encrypt.mm in Sources */ = {isa = PBXBuildFile; fileRef = 39852A4920AB2418004CB100 /* Encrypt.mm */; }; - 39852A5420AB2418004CB100 /* DdocParserDelegate.h in Headers */ = {isa = PBXBuildFile; fileRef = 39852A4A20AB2418004CB100 /* DdocParserDelegate.h */; }; - 39E2B4D920AD7A3400CA74A8 /* Addressee.m in Sources */ = {isa = PBXBuildFile; fileRef = 39E2B4CF20AD7A3400CA74A8 /* Addressee.m */; }; - 39E2B4DF20AD7A3400CA74A8 /* Addressee.h in Headers */ = {isa = PBXBuildFile; fileRef = 39E2B4D520AD7A3400CA74A8 /* Addressee.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 4E0454632D3BE73D0013DF23 /* CryptoDataFile.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E0454622D3BE73D0013DF23 /* CryptoDataFile.swift */; }; + 4E0454652D3BE76C0013DF23 /* CdocParserDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E0454642D3BE76C0013DF23 /* CdocParserDelegate.swift */; }; + 4E17B8322D6486040063C5BF /* libz.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = 4E17B8302D6485750063C5BF /* libz.tbd */; }; 4E17B8352D64A1080063C5BF /* X509CertificateType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E17B8342D64A0FD0063C5BF /* X509CertificateType.swift */; }; + 4E276E042D81A61000D78F40 /* Extensions.h in Headers */ = {isa = PBXBuildFile; fileRef = 4E276E032D81A60600D78F40 /* Extensions.h */; }; 4E3681D92D40EAAD00D76DAB /* OpenLdap.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E3681D72D40EAAD00D76DAB /* OpenLdap.swift */; }; 4E3681DB2D40EAE800D76DAB /* MoppLdapConfiguration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E3681DA2D40EAE800D76DAB /* MoppLdapConfiguration.swift */; }; + 4E70AB162D7F0FB700ED97A3 /* CDoc2Settings.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E70AB152D7F0FB100ED97A3 /* CDoc2Settings.swift */; }; 4E8990862D710DC50010CA1F /* libxml2.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = 4E8990852D710DBC0010CA1F /* libxml2.tbd */; }; 4EAC69122D481D1C00A53079 /* ASN1Decoder in Frameworks */ = {isa = PBXBuildFile; productRef = 4EAC69112D481D1C00A53079 /* ASN1Decoder */; }; + 4EB03C7D2D3BE4FB00D5F9AC /* Addressee.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4EB03C7C2D3BE4FB00D5F9AC /* Addressee.swift */; }; + 4EB03C7F2D3BE6F700D5F9AC /* CdocInfo.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4EB03C7E2D3BE6F700D5F9AC /* CdocInfo.swift */; }; 4EEE43222D7CF3C9003D0112 /* AbstractSmartToken.swift in Sources */ = {isa = PBXBuildFile; fileRef = 39266A5920CFD93E002E3F23 /* AbstractSmartToken.swift */; }; DFA40D2F2ADF635F003EF945 /* 3513523f.0 in Resources */ = {isa = PBXBuildFile; fileRef = DFA40D2E2ADF635F003EF945 /* 3513523f.0 */; }; DFC7CA452AE010C9009D85FF /* 9f4c149e.0 in Resources */ = {isa = PBXBuildFile; fileRef = DFC7CA442AE010C9009D85FF /* 9f4c149e.0 */; }; @@ -58,30 +54,25 @@ 39231FAD20AB1C6C00E1E2B4 /* CryptoLib.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = CryptoLib.h; sourceTree = ""; }; 39266A5020CFBDF8002E3F23 /* SmartCardTokenWrapper.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = SmartCardTokenWrapper.mm; sourceTree = ""; }; 39266A5920CFD93E002E3F23 /* AbstractSmartToken.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AbstractSmartToken.swift; sourceTree = ""; }; - 39266A5B20CFDC41002E3F23 /* CdocParser.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = CdocParser.h; sourceTree = ""; }; - 39266A5C20CFDC59002E3F23 /* CdocParser.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = CdocParser.m; sourceTree = ""; }; - 39266A5E20CFDCB9002E3F23 /* CdocInfo.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = CdocInfo.m; sourceTree = ""; }; - 39266A6020CFDCDF002E3F23 /* CdocInfo.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = CdocInfo.h; sourceTree = ""; }; - 39266A6120CFE36A002E3F23 /* CdocParserDelegate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = CdocParserDelegate.h; sourceTree = ""; }; - 39266A6220CFE3D4002E3F23 /* CdocParserDelegate.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = CdocParserDelegate.m; sourceTree = ""; }; 393B66DF20DB94B4001DC89B /* cdoc.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; path = cdoc.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 3960E50320C02DA400D4D2FC /* CryptoDataFile.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = CryptoDataFile.h; sourceTree = ""; }; - 3960E50420C02E5900D4D2FC /* CryptoDataFile.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = CryptoDataFile.m; sourceTree = ""; }; 39852A4120AB2418004CB100 /* Decrypt.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Decrypt.h; sourceTree = ""; }; 39852A4220AB2418004CB100 /* Encrypt.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Encrypt.h; sourceTree = ""; }; - 39852A4620AB2418004CB100 /* DdocParserDelegate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = DdocParserDelegate.m; sourceTree = ""; }; 39852A4720AB2418004CB100 /* SmartCardTokenWrapper.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SmartCardTokenWrapper.h; sourceTree = ""; }; 39852A4820AB2418004CB100 /* Decrypt.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = Decrypt.mm; sourceTree = ""; }; 39852A4920AB2418004CB100 /* Encrypt.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = Encrypt.mm; sourceTree = ""; }; - 39852A4A20AB2418004CB100 /* DdocParserDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = DdocParserDelegate.h; sourceTree = ""; }; - 39E2B4CF20AD7A3400CA74A8 /* Addressee.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = Addressee.m; sourceTree = ""; }; - 39E2B4D520AD7A3400CA74A8 /* Addressee.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Addressee.h; sourceTree = ""; }; 4E01B4A62AEFDD3B00941723 /* build-cdoc.sh */ = {isa = PBXFileReference; lastKnownFileType = text.script.sh; path = "build-cdoc.sh"; sourceTree = ""; }; + 4E0454622D3BE73D0013DF23 /* CryptoDataFile.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CryptoDataFile.swift; sourceTree = ""; }; + 4E0454642D3BE76C0013DF23 /* CdocParserDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CdocParserDelegate.swift; sourceTree = ""; }; + 4E17B8302D6485750063C5BF /* libz.tbd */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.text-based-dylib-definition"; name = libz.tbd; path = usr/lib/libz.tbd; sourceTree = SDKROOT; }; 4E17B8342D64A0FD0063C5BF /* X509CertificateType.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = X509CertificateType.swift; sourceTree = ""; }; + 4E276E032D81A60600D78F40 /* Extensions.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = Extensions.h; sourceTree = ""; }; 4E3681D72D40EAAD00D76DAB /* OpenLdap.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OpenLdap.swift; sourceTree = ""; }; 4E3681DA2D40EAE800D76DAB /* MoppLdapConfiguration.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MoppLdapConfiguration.swift; sourceTree = ""; }; 4E3AFF7D2D67D45800666AC7 /* openldap.modulemap */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.module-map"; path = openldap.modulemap; sourceTree = ""; }; + 4E70AB152D7F0FB100ED97A3 /* CDoc2Settings.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CDoc2Settings.swift; sourceTree = ""; }; 4E8990852D710DBC0010CA1F /* libxml2.tbd */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.text-based-dylib-definition"; name = libxml2.tbd; path = usr/lib/libxml2.tbd; sourceTree = SDKROOT; }; + 4EB03C7C2D3BE4FB00D5F9AC /* Addressee.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Addressee.swift; sourceTree = ""; }; + 4EB03C7E2D3BE6F700D5F9AC /* CdocInfo.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CdocInfo.swift; sourceTree = ""; }; 4ED24ECB2D4F799800855FC3 /* build-openldap.sh */ = {isa = PBXFileReference; lastKnownFileType = text.script.sh; path = "build-openldap.sh"; sourceTree = ""; }; DFA40D2E2ADF635F003EF945 /* 3513523f.0 */ = {isa = PBXFileReference; lastKnownFileType = text; path = 3513523f.0; sourceTree = ""; }; DFC7CA442AE010C9009D85FF /* 9f4c149e.0 */ = {isa = PBXFileReference; lastKnownFileType = text; path = 9f4c149e.0; sourceTree = ""; }; @@ -93,6 +84,7 @@ buildActionMask = 2147483647; files = ( 4E8990862D710DC50010CA1F /* libxml2.tbd in Frameworks */, + 4E17B8322D6486040063C5BF /* libz.tbd in Frameworks */, 4EAC69122D481D1C00A53079 /* ASN1Decoder in Frameworks */, 393B66E020DB94B4001DC89B /* cdoc.framework in Frameworks */, ); @@ -126,24 +118,21 @@ 39231FAC20AB1C6C00E1E2B4 /* CryptoLib */ = { isa = PBXGroup; children = ( + 39231FAD20AB1C6C00E1E2B4 /* CryptoLib.h */, 39E2B4CB20AD7A3400CA74A8 /* Ldap */, 39E414E020AC5C9300141574 /* XmlParser */, + 4E276E032D81A60600D78F40 /* Extensions.h */, 39852A4120AB2418004CB100 /* Decrypt.h */, 39852A4820AB2418004CB100 /* Decrypt.mm */, 39852A4220AB2418004CB100 /* Encrypt.h */, 39852A4920AB2418004CB100 /* Encrypt.mm */, 39852A4720AB2418004CB100 /* SmartCardTokenWrapper.h */, 39266A5020CFBDF8002E3F23 /* SmartCardTokenWrapper.mm */, - 39266A5B20CFDC41002E3F23 /* CdocParser.h */, - 39266A5C20CFDC59002E3F23 /* CdocParser.m */, - 39231FAD20AB1C6C00E1E2B4 /* CryptoLib.h */, 39266A5920CFD93E002E3F23 /* AbstractSmartToken.swift */, - 39E2B4D520AD7A3400CA74A8 /* Addressee.h */, - 39E2B4CF20AD7A3400CA74A8 /* Addressee.m */, - 3960E50320C02DA400D4D2FC /* CryptoDataFile.h */, - 3960E50420C02E5900D4D2FC /* CryptoDataFile.m */, - 39266A5E20CFDCB9002E3F23 /* CdocInfo.m */, - 39266A6020CFDCDF002E3F23 /* CdocInfo.h */, + 4E70AB152D7F0FB100ED97A3 /* CDoc2Settings.swift */, + 4E0454622D3BE73D0013DF23 /* CryptoDataFile.swift */, + 4EB03C7C2D3BE4FB00D5F9AC /* Addressee.swift */, + 4EB03C7E2D3BE6F700D5F9AC /* CdocInfo.swift */, 4E17B8342D64A0FD0063C5BF /* X509CertificateType.swift */, ); path = CryptoLib; @@ -162,10 +151,7 @@ 39E414E020AC5C9300141574 /* XmlParser */ = { isa = PBXGroup; children = ( - 39852A4A20AB2418004CB100 /* DdocParserDelegate.h */, - 39852A4620AB2418004CB100 /* DdocParserDelegate.m */, - 39266A6120CFE36A002E3F23 /* CdocParserDelegate.h */, - 39266A6220CFE3D4002E3F23 /* CdocParserDelegate.m */, + 4E0454642D3BE76C0013DF23 /* CdocParserDelegate.swift */, ); path = XmlParser; sourceTree = ""; @@ -174,6 +160,7 @@ isa = PBXGroup; children = ( 4E8990852D710DBC0010CA1F /* libxml2.tbd */, + 4E17B8302D6485750063C5BF /* libz.tbd */, 393B66DF20DB94B4001DC89B /* cdoc.framework */, ); name = Frameworks; @@ -186,15 +173,11 @@ isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( + 39231FAF20AB1C6C00E1E2B4 /* CryptoLib.h in Headers */, 39852A4B20AB2418004CB100 /* Decrypt.h in Headers */, 39852A4C20AB2418004CB100 /* Encrypt.h in Headers */, - 39852A5420AB2418004CB100 /* DdocParserDelegate.h in Headers */, 39852A5120AB2418004CB100 /* SmartCardTokenWrapper.h in Headers */, - 39E2B4DF20AD7A3400CA74A8 /* Addressee.h in Headers */, - 3960E50620C044EE00D4D2FC /* CryptoDataFile.h in Headers */, - 39266A6520CFE643002E3F23 /* CdocInfo.h in Headers */, - 39266A6420CFE63D002E3F23 /* CdocParser.h in Headers */, - 39231FAF20AB1C6C00E1E2B4 /* CryptoLib.h in Headers */, + 4E276E042D81A61000D78F40 /* Extensions.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -311,15 +294,14 @@ buildActionMask = 2147483647; files = ( 4EEE43222D7CF3C9003D0112 /* AbstractSmartToken.swift in Sources */, - 39266A5F20CFDCB9002E3F23 /* CdocInfo.m in Sources */, - 39266A6320CFE3D4002E3F23 /* CdocParserDelegate.m in Sources */, - 39266A5D20CFDC59002E3F23 /* CdocParser.m in Sources */, - 3960E50520C02E5900D4D2FC /* CryptoDataFile.m in Sources */, - 39852A5020AB2418004CB100 /* DdocParserDelegate.m in Sources */, + 4EB03C7D2D3BE4FB00D5F9AC /* Addressee.swift in Sources */, + 4E70AB162D7F0FB700ED97A3 /* CDoc2Settings.swift in Sources */, 4E17B8352D64A1080063C5BF /* X509CertificateType.swift in Sources */, + 4EB03C7F2D3BE6F700D5F9AC /* CdocInfo.swift in Sources */, 39852A5220AB2418004CB100 /* Decrypt.mm in Sources */, - 39E2B4D920AD7A3400CA74A8 /* Addressee.m in Sources */, + 4E0454632D3BE73D0013DF23 /* CryptoDataFile.swift in Sources */, 39852A5320AB2418004CB100 /* Encrypt.mm in Sources */, + 4E0454652D3BE76C0013DF23 /* CdocParserDelegate.swift in Sources */, 39266A5120CFBDF8002E3F23 /* SmartCardTokenWrapper.mm in Sources */, 4E3681D92D40EAAD00D76DAB /* OpenLdap.swift in Sources */, 4E3681DB2D40EAE800D76DAB /* MoppLdapConfiguration.swift in Sources */, @@ -392,6 +374,8 @@ GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 15.0; + MODULE_VERIFIER_SUPPORTED_LANGUAGES = "objective-c objective-c++"; + MODULE_VERIFIER_SUPPORTED_LANGUAGE_STANDARDS = "gnu17 gnu++20"; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = iphoneos; @@ -446,6 +430,8 @@ GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 15.0; + MODULE_VERIFIER_SUPPORTED_LANGUAGES = "objective-c objective-c++"; + MODULE_VERIFIER_SUPPORTED_LANGUAGE_STANDARDS = "gnu17 gnu++20"; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; VALIDATE_PRODUCT = YES; diff --git a/CryptoLib/CryptoLib/AbstractSmartToken.swift b/CryptoLib/CryptoLib/AbstractSmartToken.swift index 3b686f013..a6bb170e9 100644 --- a/CryptoLib/CryptoLib/AbstractSmartToken.swift +++ b/CryptoLib/CryptoLib/AbstractSmartToken.swift @@ -26,4 +26,5 @@ import Foundation func getCertificate() throws -> Data func decrypt(_ data: Data, pin1: String) throws -> Data func derive(_ data: Data, pin1: String) throws -> Data + func authenticate(_ data: Data, pin1: String) throws -> Data } diff --git a/CryptoLib/CryptoLib/Addressee.h b/CryptoLib/CryptoLib/Addressee.h deleted file mode 100644 index a352a22e7..000000000 --- a/CryptoLib/CryptoLib/Addressee.h +++ /dev/null @@ -1,32 +0,0 @@ -// -// Addressee.h -// CryptoLib -/* - * Copyright 2017 - 2024 Riigi Infosüsteemi Amet - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - -#import - -@interface Addressee : NSObject -@property (nonatomic, strong) NSString *givenName; -@property (nonatomic, strong) NSString *surname; -@property (nonatomic, strong) NSString *identifier; -@property (nonatomic, strong) NSData *cert; -@property (nonatomic, strong) NSDate *validTo; - -@end diff --git a/CryptoLib/CryptoLib/Addressee.m b/CryptoLib/CryptoLib/Addressee.m deleted file mode 100644 index 7d56299aa..000000000 --- a/CryptoLib/CryptoLib/Addressee.m +++ /dev/null @@ -1,28 +0,0 @@ -// -// Addressee.m -// CryptoLib -/* - * Copyright 2017 - 2024 Riigi Infosüsteemi Amet - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - -#import -#import "Addressee.h" - -@implementation Addressee - -@end diff --git a/CryptoLib/CryptoLib/Addressee.swift b/CryptoLib/CryptoLib/Addressee.swift new file mode 100644 index 000000000..3e10f96f1 --- /dev/null +++ b/CryptoLib/CryptoLib/Addressee.swift @@ -0,0 +1,69 @@ +// +// Addressee.swift +// CryptoLib +/* + * Copyright 2017 - 2024 Riigi Infosüsteemi Amet + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +import Foundation +import ASN1Decoder + +public class Addressee: NSObject { + @objc public var data: Data + public let identifier: String + public let givenName: String? + public let surname: String? + public let certType: CertType + public var validTo: Date? + + @objc public init(cn: String, certType: CertType, validTo: Date?, data: Data) { + let split = cn.split(separator: ",").map { String($0) } + if split.count > 1 { + surname = split[0] + givenName = split[1] + identifier = split[2] + } else { + surname = nil + givenName = nil + identifier = cn + } + self.certType = certType + self.validTo = validTo + self.data = data + } + + @objc convenience public init(cn: String, pub: Data) { + self.init(cn: cn, certType: .UnknownType, validTo: nil, data: pub) + } + + convenience init(cert: Data) { + let x509 = try? X509Certificate(der: cert) + self.init(cn: x509?.subject(oid: OID.commonName)?.joined(separator: ",") ?? "", certType: x509?.certType() ?? .UnknownType, validTo: x509?.notAfter, data: cert) + } + + public override func isEqual(_ object: Any?) -> Bool { + guard let other = object as? Addressee else { return false } + return + data == other.data && + identifier == other.identifier && + givenName == other.givenName && + surname == other.surname && + certType == other.certType && + validTo == other.validTo + } +} diff --git a/CryptoLib/CryptoLib/CDoc2Settings.swift b/CryptoLib/CryptoLib/CDoc2Settings.swift new file mode 100644 index 000000000..00ffba4e0 --- /dev/null +++ b/CryptoLib/CryptoLib/CDoc2Settings.swift @@ -0,0 +1,102 @@ +// +// CryptoDataFile.swift +// CryptoLib +/* + * Copyright 2017 - 2024 Riigi Infosüsteemi Amet + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +import Foundation + +public class CDoc2Settings: NSObject { + public static let kUseCDoc2Encryption = "kUseCDoc2Encryption" + public static let kUseCDoc2OnlineEncryption = "kUseCDoc2OnlineEncryption" + public static let kUseCDoc2SelectedService = "kUseCDoc2SelectedService" + public static let kUseCDoc2UUID = "kUseCDoc2UUID" + public static let kUseCDoc2PostURL = "kUseCDoc2PostURL" + public static let kUseCDoc2FetchURL = "kUseCDoc2FetchURL" + + private static func set(_ key: String, value: Bool) { + UserDefaults.standard.set(value, forKey: key) + } + + private static func get(_ key: String) -> Bool { + return UserDefaults.standard.bool(forKey: key) + } + + private static func setString(_ key: String, value: String?) { + UserDefaults.standard.set(value, forKey: key) + } + + private static func getString(_ key: String) -> String? { + return UserDefaults.standard.string(forKey: key) + } + + public class var useEncryption: Bool { + get { get(kUseCDoc2Encryption) } + set { set(kUseCDoc2Encryption, value: newValue) } + } + + public class var useOnlineEncryption: Bool { + get { get(kUseCDoc2OnlineEncryption) } + set { set(kUseCDoc2OnlineEncryption, value: newValue) } + } + + public class var cdoc2SelectedService: String? { + get { getString(kUseCDoc2SelectedService) } + set { setString(kUseCDoc2SelectedService, value: newValue) } + } + + public class var cdoc2UUID: String? { + get { getString(kUseCDoc2UUID) } + set { setString(kUseCDoc2UUID, value: newValue) } + } + + public class var cdoc2PostURL: String? { + get { getString(kUseCDoc2PostURL) } + set { setString(kUseCDoc2PostURL, value: newValue) } + } + + public class var cdoc2FetchURL: String? { + get { getString(kUseCDoc2FetchURL) } + set { setString(kUseCDoc2FetchURL, value: newValue) } + } + + @objc public class func isEncryptionEnabled() -> Bool { + return get(kUseCDoc2Encryption) + } + + @objc public class func isOnlineEncryptionEnabled() -> Bool { + return get(kUseCDoc2OnlineEncryption) + } + + @objc public class func getSelectedService() -> String? { + return getString(kUseCDoc2SelectedService) + } + + @objc public class func getUUID() -> String? { + return getString(kUseCDoc2UUID) + } + + @objc public class func getPostURL() -> String? { + return getString(kUseCDoc2PostURL) + } + + @objc public class func getFetchURL() -> String? { + return getString(kUseCDoc2FetchURL) + } +} diff --git a/CryptoLib/CryptoLib/CdocInfo.h b/CryptoLib/CryptoLib/CdocInfo.h deleted file mode 100644 index 9e3dae7be..000000000 --- a/CryptoLib/CryptoLib/CdocInfo.h +++ /dev/null @@ -1,31 +0,0 @@ -// -// CdocInfo.h -// CryptoLib -/* - * Copyright 2017 - 2024 Riigi Infosüsteemi Amet - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - -#import -#import "CryptoDataFile.h" -#import "Addressee.h" - -@interface CdocInfo : NSObject -@property (nonatomic, strong) NSMutableArray *addressees; -@property (nonatomic, strong) NSMutableArray *dataFiles; - -@end diff --git a/CryptoLib/CryptoLib/CdocInfo.m b/CryptoLib/CryptoLib/CdocInfo.m deleted file mode 100644 index 5febffa03..000000000 --- a/CryptoLib/CryptoLib/CdocInfo.m +++ /dev/null @@ -1,27 +0,0 @@ -// -// CdocInfo.m -// CryptoLib -/* - * Copyright 2017 - 2024 Riigi Infosüsteemi Amet - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - -#import -#import "CdocInfo.h" - -@implementation CdocInfo -@end diff --git a/CryptoLib/CryptoLib/CdocParser.h b/CryptoLib/CryptoLib/CdocInfo.swift similarity index 64% rename from CryptoLib/CryptoLib/CdocParser.h rename to CryptoLib/CryptoLib/CdocInfo.swift index b48fdc011..f72e3e378 100644 --- a/CryptoLib/CryptoLib/CdocParser.h +++ b/CryptoLib/CryptoLib/CdocInfo.swift @@ -1,5 +1,5 @@ // -// CdocParser.h +// CdocInfo.swift // CryptoLib /* * Copyright 2017 - 2024 Riigi Infosüsteemi Amet @@ -20,11 +20,19 @@ * */ -#import -#import "CdocInfo.h" +import Foundation -@interface CdocParser : NSObject -- (CdocInfo*)parseCdocInfo:(NSString*)fullpath; -@end +public class CdocInfo: NSObject { + public let addressees: [Addressee] + public let dataFiles: [CryptoDataFile] + @objc public init(addressees: [Addressee] = []) { + self.addressees = addressees + self.dataFiles = [] + } + @objc public init(addressees: [Addressee] = [], dataFiles: [CryptoDataFile] = []) { + self.addressees = addressees + self.dataFiles = dataFiles + } +} diff --git a/CryptoLib/CryptoLib/CdocParser.m b/CryptoLib/CryptoLib/CdocParser.m deleted file mode 100644 index fcb865861..000000000 --- a/CryptoLib/CryptoLib/CdocParser.m +++ /dev/null @@ -1,39 +0,0 @@ -// -// CdocParser.m -// CryptoLib -/* - * Copyright 2017 - 2024 Riigi Infosüsteemi Amet - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ -#import "CdocParser.h" -#import "CdocInfo.h" -#import "CdocParserDelegate.h" - -@implementation CdocParser - -- (CdocInfo*)parseCdocInfo:(NSString*)fullpath { - NSData *data = [[NSData alloc] initWithContentsOfFile:fullpath]; - NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data]; - CdocParserDelegate *parserDelegate = [CdocParserDelegate new]; - [parser setDelegate:(id)parserDelegate]; - [parser parse]; - CdocInfo *response = [CdocInfo new]; - response.addressees = parserDelegate.addressees; - response.dataFiles = parserDelegate.dataFiles; - return response; -} -@end diff --git a/CryptoLib/CryptoLib/CryptoDataFile.h b/CryptoLib/CryptoLib/CryptoDataFile.h deleted file mode 100644 index ca4b1428f..000000000 --- a/CryptoLib/CryptoLib/CryptoDataFile.h +++ /dev/null @@ -1,29 +0,0 @@ -// -// CryptoDataFile.h -// CryptoLib -/* - * Copyright 2017 - 2024 Riigi Infosüsteemi Amet - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - -#import - -@interface CryptoDataFile : NSObject -@property (nonatomic, strong) NSString *filename; -@property (nonatomic, strong) NSString *filePath; - -@end diff --git a/CryptoLib/CryptoLib/CryptoDataFile.m b/CryptoLib/CryptoLib/CryptoDataFile.m deleted file mode 100644 index f4edfd1d4..000000000 --- a/CryptoLib/CryptoLib/CryptoDataFile.m +++ /dev/null @@ -1,28 +0,0 @@ -// -// DataFile.m -// CryptoLib -/* - * Copyright 2017 - 2024 Riigi Infosüsteemi Amet - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - -#import -#import "CryptoDataFile.h" - -@implementation CryptoDataFile - -@end diff --git a/CryptoLib/CryptoLib/XmlParser/DdocParserDelegate.h b/CryptoLib/CryptoLib/CryptoDataFile.swift similarity index 73% rename from CryptoLib/CryptoLib/XmlParser/DdocParserDelegate.h rename to CryptoLib/CryptoLib/CryptoDataFile.swift index b68d4ca8b..3646ba6fd 100644 --- a/CryptoLib/CryptoLib/XmlParser/DdocParserDelegate.h +++ b/CryptoLib/CryptoLib/CryptoDataFile.swift @@ -1,5 +1,5 @@ // -// DdocParserDelegate.h +// CryptoDataFile.swift // CryptoLib /* * Copyright 2017 - 2024 Riigi Infosüsteemi Amet @@ -20,12 +20,14 @@ * */ -#import +import Foundation -@interface DdocParserDelegate : NSObject -{ +public class CryptoDataFile: NSObject { + @objc public let filename: String + @objc public let filePath: String? + + public init(filename: String, filePath: String? = nil) { + self.filename = filename + self.filePath = filePath + } } -@property (nonatomic, retain) NSMutableDictionary *dictionary; -@property (nonatomic, retain) NSString *lastKey; -@property (nonatomic, retain) NSString *currentElement; -@end diff --git a/CryptoLib/CryptoLib/CryptoLib.h b/CryptoLib/CryptoLib/CryptoLib.h index 0b0c0f54e..514a81497 100644 --- a/CryptoLib/CryptoLib/CryptoLib.h +++ b/CryptoLib/CryptoLib/CryptoLib.h @@ -30,8 +30,5 @@ FOUNDATION_EXPORT const unsigned char CryptoLibVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import -#import -#import #import #import -#import diff --git a/CryptoLib/CryptoLib/Decrypt.h b/CryptoLib/CryptoLib/Decrypt.h index 6a8956c33..66fb469b5 100644 --- a/CryptoLib/CryptoLib/Decrypt.h +++ b/CryptoLib/CryptoLib/Decrypt.h @@ -23,7 +23,9 @@ #import @protocol AbstractSmartToken; +@class CdocInfo; @interface Decrypt : NSObject -- (NSMutableDictionary *)decryptFile:(NSString *)fullPath withPin:(NSString *)pin withToken:(id)smartToken error:(NSError**)error; ++ (void)parseCdocInfoWithFullPath:(NSString *)fullPath success:(void (^)(CdocInfo *))success; ++ (NSDictionary *)decryptFile:(NSString *)fullPath withPin:(NSString *)pin withToken:(id)smartToken error:(NSError**)error; @end diff --git a/CryptoLib/CryptoLib/Decrypt.mm b/CryptoLib/CryptoLib/Decrypt.mm index f2b233f07..fadc6e6c8 100644 --- a/CryptoLib/CryptoLib/Decrypt.mm +++ b/CryptoLib/CryptoLib/Decrypt.mm @@ -21,48 +21,151 @@ */ #import "Decrypt.h" +#import "Extensions.h" #import "SmartCardTokenWrapper.h" -#import "DdocParserDelegate.h" +#import -#import -#import +#include +#include +#include +#include +#include + +@implementation Addressee (label) + +- (instancetype)initWithLabel:(const std::string &)label pub:(NSData*)pub { + std::map info = libcdoc::Recipient::parseLabel(label); + id cn = info.contains("cn") ? [NSString stringWithStdString:info["cn"]] : nil; + id type = info.contains("last_name") ? [NSString stringWithStdString:info["type"]] : nil; + CertType certType = CertTypeUnknownType; + if ([type isEqualToString:@"ID-card"]) { + certType = CertTypeIDCardType; + } else if ([type isEqualToString:@"Digi-ID"]) { + certType = CertTypeDigiIDType; + } else if ([type isEqualToString:@"Digi-ID E-RESIDENT"]) { + certType = CertTypeEResidentType; + } + id validTo = nil; + if (info.contains("server_exp")) { + long long epochTime = [[NSString stringWithStdString:info["server_exp"]] longLongValue]; + validTo = [NSDate dateWithTimeIntervalSince1970:epochTime]; + } + if (self = [self initWithCn:cn certType:certType validTo:validTo data:pub]) { + } + return self; +} + +@end + +struct Settings: public libcdoc::Configuration { + std::string getValue(std::string_view domain, std::string_view param) const final { + if(param == KEYSERVER_FETCH_URL) + return [CDoc2Settings.getFetchURL toString]; + if(param == KEYSERVER_SEND_URL) + return [CDoc2Settings.getPostURL toString]; + return {}; + } +}; + +struct Network: public libcdoc::NetworkBackend +{ + std::vector cert; + SmartCardTokenWrapper *token = nullptr; + + libcdoc::result_t getClientTLSCertificate(std::vector &dst) final { + dst = cert; + return libcdoc::OK; + } + + libcdoc::result_t signTLS(std::vector &dst, libcdoc::CryptoBackend::HashAlgorithm algorithm, const std::vector &digest) final { + return token->sign(dst, algorithm, digest, 0); + } +}; @implementation Decrypt -- (NSMutableDictionary *)decryptFile:(NSString *)fullPath withPin:(NSString *)pin withToken:(id)smartToken error:(NSError**)error { ++ (void)parseCdocInfoWithFullPath:(NSString *)fullPath success:(void (^)(CdocInfo *))success { + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ + if([fullPath.pathExtension caseInsensitiveCompare:@"cdoc"] == NSOrderedSame) { + CdocInfo *result = [CdocParser parseWithPath:fullPath]; + return dispatch_async(dispatch_get_main_queue(), ^{ success(result); }); + } - std::string encodedFullPath = std::string([fullPath UTF8String]); - std::string encodedPin = std::string([pin UTF8String]); - CDOCReader cdocReader(encodedFullPath); - SmartCardTokenWrapper token(encodedPin, smartToken); + std::unique_ptr reader(libcdoc::CDocReader::createReader(fullPath.UTF8String, nullptr, nullptr, nullptr)); + if(!reader) + return dispatch_async(dispatch_get_main_queue(), ^{ success(nil); }); + NSMutableArray *addressees = [[NSMutableArray alloc] init]; + for(const libcdoc::Lock &lock: reader->getLocks()) + { + if(lock.isCertificate()) { + [addressees addObject:[[Addressee alloc] initWithLabel:lock.label pub:[NSData dataFromVector:lock.getBytes(libcdoc::Lock::CERT)]]]; + } else if(lock.isPKI()) { + [addressees addObject:[[Addressee alloc] initWithLabel:lock.label pub:[NSData dataFromVector:lock.getBytes(libcdoc::Lock::RCPT_KEY)]]]; + } else { + [addressees addObject:[[Addressee alloc] initWithCn:@"Unknown capsule" pub:[NSData data]]]; + } + } - NSMutableDictionary *response = [NSMutableDictionary new]; - std::vector decryptedData = cdocReader.decryptData(&token); - *error = token.lastError(); - if (decryptedData.empty()){ - return response; + CdocInfo *result = [[CdocInfo alloc] initWithAddressees:addressees]; + return dispatch_async(dispatch_get_main_queue(), ^{ success(result); }); + }); +} + ++ (NSDictionary *)decryptFile:(NSString *)fullPath withPin:(NSString *)pin withToken:(id)smartToken error:(NSError**)error { + SmartCardTokenWrapper token(pin.UTF8String, smartToken); + Settings conf; + Network network; + network.token = &token; + network.cert = token.cert(); + if(network.cert.empty()) { + if (error != nil) { + *error = token.lastError(); + } + return nil; } - NSData *decrypted = [NSData dataWithBytes:decryptedData.data() length:decryptedData.size()]; - std::string filename = cdocReader.fileName(); - std::string mimetype = cdocReader.mimeType(); - - NSString *nsFilename = [NSString stringWithCString:filename.c_str() encoding: NSUTF8StringEncoding]; - if ([[nsFilename pathExtension] isEqualToString: @"ddoc"]){ - NSXMLParser *parser = [[NSXMLParser alloc] initWithData:decrypted]; - DdocParserDelegate *parserDelegate = [[DdocParserDelegate alloc] init]; - [parser setDelegate:(id)parserDelegate]; - [parser parse]; - NSMutableDictionary *fileDictionary; - fileDictionary = parserDelegate.dictionary; - for (id key in fileDictionary){ - NSString *value = [fileDictionary objectForKey:key]; - NSData *nsdataFromBase64String = [[NSData alloc] initWithBase64EncodedString: value options:NSDataBase64DecodingIgnoreUnknownCharacters]; - [response setObject:nsdataFromBase64String forKey:key]; - + + std::unique_ptr reader(libcdoc::CDocReader::createReader(fullPath.UTF8String, &conf, &token, &network)); + + auto idx = reader->getLockForCert(network.cert); + if(idx < 0) + return nil; + std::vector fmk; + if(reader->getFMK(fmk, unsigned(idx)) != 0 || fmk.empty()) { + if (error != nil) { + *error = token.lastError(); + } + return nil; + } + if(reader->beginDecryption(fmk) != 0) + return nil; + + NSMutableDictionary *response = [NSMutableDictionary new]; + std::string name; + int64_t size{}; + while((reader->nextFile(name, size)) == 0) + { + NSMutableData *data = [[NSMutableData alloc] initWithLength:16 * 1024]; + NSUInteger currentLength = 0; + + uint64_t bytesRead = 0; + while (true) { + bytesRead = reader->readData(reinterpret_cast(data.mutableBytes) + currentLength, 16 * 1024); + if (bytesRead < 0) { + NSLog(@"Error reading data from file: %s", name.c_str()); + break; + } + + currentLength += bytesRead; + [data setLength:currentLength]; + if (bytesRead == 0) { + break; + } + [data increaseLengthBy:16 * 1024]; } - } else { - [response setObject:decrypted forKey:nsFilename]; + [response setObject:data forKey:[NSString stringWithStdString:name]]; } + if (reader->finishDecryption() != 0) + return nil; return response; } diff --git a/CryptoLib/CryptoLib/Encrypt.h b/CryptoLib/CryptoLib/Encrypt.h index dfb58a6c2..eebc65eff 100644 --- a/CryptoLib/CryptoLib/Encrypt.h +++ b/CryptoLib/CryptoLib/Encrypt.h @@ -22,6 +22,12 @@ #import -@interface Encrypt : NSObject -- (BOOL)encryptFile: (NSString *)fullPath withDataFiles :(NSArray *) dataFiles withAddressees: (NSArray *) addressees; +@class Addressee; +@class CryptoDataFile; + +@interface Encrypt: NSObject + ++ (void)encryptFile:(NSString *)fullPath withDataFiles:(NSArray *)dataFiles + withAddressees:(NSArray *)addressees success:(void (^)(void))success failure:(void (^)(void))failure; + @end diff --git a/CryptoLib/CryptoLib/Encrypt.mm b/CryptoLib/CryptoLib/Encrypt.mm index 66fcc06b9..d955bb42f 100644 --- a/CryptoLib/CryptoLib/Encrypt.mm +++ b/CryptoLib/CryptoLib/Encrypt.mm @@ -20,35 +20,83 @@ * */ - #import "Encrypt.h" -#import "Addressee.h" -#import "CryptoDataFile.h" +#import "Extensions.h" + +#import -#import +#include +#include +#include +#include + +struct Settings: public libcdoc::Configuration { + std::string getValue(std::string_view domain, std::string_view param) const final { + if(param == KEYSERVER_FETCH_URL) + return [CDoc2Settings.getFetchURL toString]; + if(param == KEYSERVER_SEND_URL) + return [CDoc2Settings.getPostURL toString]; + return {}; + } +}; @implementation Encrypt -- (BOOL)encryptFile: (NSString *)fullPath withDataFiles :(NSArray *) dataFiles withAddressees: (NSArray *) addressees { ++ (void)encryptFile:(NSString *)fullPath withDataFiles:(NSArray *)dataFiles withAddressees:(NSArray *)addressees + success:(void (^)(void))success failure:(void (^)(void))failure { + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ + int version = [fullPath.pathExtension caseInsensitiveCompare:@"cdoc2"] == NSOrderedSame ? 2 : 1; + Settings conf; + libcdoc::NetworkBackend network; + std::unique_ptr writer(libcdoc::CDocWriter::createWriter(version, fullPath.UTF8String, &conf, nullptr, &network)); - std::string encodedFullPath = std::string([fullPath UTF8String]); + if (!writer) { + return dispatch_async(dispatch_get_main_queue(), failure); + } - CDOCWriter cdocWriter(encodedFullPath, "http://www.w3.org/2009/xmlenc11#aes256-gcm"); + if (version == 2 && CDoc2Settings.isOnlineEncryptionEnabled) { + NSString *server_id = CDoc2Settings.getSelectedService; + for (Addressee *addressee in addressees) { + if (writer->addRecipient(libcdoc::Recipient::makeEIDServer([addressee.data toVector], [server_id toString])) != 0) { + return dispatch_async(dispatch_get_main_queue(), failure); + } + } + } else { + for (Addressee *addressee in addressees) { + if (writer->addRecipient(libcdoc::Recipient::makeEID([addressee.data toVector])) != 0) { + return dispatch_async(dispatch_get_main_queue(), failure); + } + } + } - for (CryptoDataFile *dataFile in dataFiles) { - std::string encodedDataFilePath = std::string([dataFile.filePath UTF8String]); - std::string encodedFilename = std::string([dataFile.filename UTF8String]); - cdocWriter.addFile(encodedFilename, "application/octet-stream", encodedDataFilePath); - } - for (Addressee *addressee in addressees) { - NSData *cert = addressee.cert; - unsigned char *buffer = reinterpret_cast(const_cast(cert.bytes)); - std::vector result = std::vector(buffer, buffer + cert.length); - - cdocWriter.addRecipient(std::move(result)); - } + if (writer->beginEncryption() != 0) { + return dispatch_async(dispatch_get_main_queue(), failure); + } + + for (CryptoDataFile *dataFile in dataFiles) { + NSFileHandle *fileHandle = [NSFileHandle fileHandleForReadingAtPath:dataFile.filePath]; + if (!fileHandle) { + NSLog(@"Failed to open file at path: %@", dataFile.filePath); + return dispatch_async(dispatch_get_main_queue(), failure); + } + + if (writer->addFile(dataFile.filename.UTF8String, [fileHandle seekToEndOfFile]) != 0) { + return dispatch_async(dispatch_get_main_queue(), failure); + } + [fileHandle seekToFileOffset:0]; - return cdocWriter.encrypt(); + NSUInteger blockSize = 1024 * 16; + NSData *data; + while ((data = [fileHandle readDataOfLength:blockSize]) && data.length > 0) { + if (writer->writeData(reinterpret_cast(data.bytes), data.length) != 0) { + return dispatch_async(dispatch_get_main_queue(), failure); + } + } + [fileHandle closeFile]; + } + bool result = writer->finishEncryption() == 0; + dispatch_async(dispatch_get_main_queue(), result ? success : failure); + }); } @end diff --git a/CryptoLib/CryptoLib/Extensions.h b/CryptoLib/CryptoLib/Extensions.h new file mode 100644 index 000000000..532ece33e --- /dev/null +++ b/CryptoLib/CryptoLib/Extensions.h @@ -0,0 +1,59 @@ +// +// Decrypt.h +// CryptoLib +/* + * Copyright 2017 - 2024 Riigi Infosüsteemi Amet + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#import + +#include +#include + +@interface NSString (std_string) +- (std::string)toString; +@end + +@interface NSData (std_vector) +- (std::vector)toVector; +@end + +@implementation NSString (std_string) ++ (instancetype)stringWithStdString:(const std::string&)data { + return data.empty() ? nil : [NSString stringWithUTF8String:data.c_str()]; +} + +- (std::string)toString { + return {self.UTF8String}; +} +@end + +@implementation NSData (std_vector) ++ (instancetype)dataFromVector:(const std::vector&)data { + return data.empty() ? nil : [NSData dataWithBytes:(void *)data.data() length:data.size()]; +} + ++ (instancetype)dataFromVectorNoCopy:(const std::vector&)data { + return data.empty() ? nil : [NSData dataWithBytesNoCopy:(void *)data.data() length:data.size() freeWhenDone:0]; +} + +- (std::vector)toVector { + const auto *p = reinterpret_cast(self.bytes); + return {p, std::next(p, self.length)}; +} +@end diff --git a/CryptoLib/CryptoLib/Ldap/OpenLdap.swift b/CryptoLib/CryptoLib/Ldap/OpenLdap.swift index 1be20f239..791c7463c 100644 --- a/CryptoLib/CryptoLib/Ldap/OpenLdap.swift +++ b/CryptoLib/CryptoLib/Ldap/OpenLdap.swift @@ -179,19 +179,7 @@ public class OpenLdap { !x509.extendedKeyUsage.contains(OID.serverAuth.rawValue), type != .ESealType || !x509.extendedKeyUsage.contains(OID.clientAuth.rawValue), type != .MobileIDType && type != .UnknownType { - let cn = x509.subject(oid: OID.commonName)?.joined(separator: ",") ?? "" - let split = cn.split(separator: ",").map { String($0) } - let addressee = Addressee() - if split.count == 3 { - addressee.surname = split[0] - addressee.givenName = split[1] - addressee.identifier = split[2] - } else { - addressee.identifier = cn - } - addressee.cert = data - addressee.validTo = x509.notAfter ?? Date() - result.append(addressee) + result.append(Addressee(cert: data)) } } return result diff --git a/CryptoLib/CryptoLib/SmartCardTokenWrapper.h b/CryptoLib/CryptoLib/SmartCardTokenWrapper.h index 7814c4ad9..db72e4287 100644 --- a/CryptoLib/CryptoLib/SmartCardTokenWrapper.h +++ b/CryptoLib/CryptoLib/SmartCardTokenWrapper.h @@ -22,29 +22,27 @@ #if __cplusplus -#import "cdoc/Token.h" - +#import #import - #include @protocol AbstractSmartToken; -class SmartCardTokenWrapper: public Token +class SmartCardTokenWrapper: public libcdoc::CryptoBackend { public: SmartCardTokenWrapper(const std::string &password, id smartToken); ~SmartCardTokenWrapper() noexcept; - std::vector cert() const final; - std::vector decrypt(const std::vector &data) const final; - std::vector derive(const std::vector &publicKey) const final; + std::vector cert() const; + libcdoc::result_t deriveECDH1(std::vector &dst, const std::vector &public_key, unsigned int idx) final; + libcdoc::result_t decryptRSA(std::vector &dst, const std::vector &data, bool oaep, unsigned int idx) final; + libcdoc::result_t sign(std::vector &dst, HashAlgorithm algorithm, const std::vector &digest, unsigned int idx) final; NSError* lastError() const; private: class Private; std::unique_ptr token; - static std::vector encodeData(const NSData *dataBlock); }; #endif diff --git a/CryptoLib/CryptoLib/SmartCardTokenWrapper.mm b/CryptoLib/CryptoLib/SmartCardTokenWrapper.mm index 37f8a1e72..7bed78a6b 100644 --- a/CryptoLib/CryptoLib/SmartCardTokenWrapper.mm +++ b/CryptoLib/CryptoLib/SmartCardTokenWrapper.mm @@ -21,11 +21,12 @@ * */ -#include "SmartCardTokenWrapper.h" +#import "SmartCardTokenWrapper.h" +#import "Extensions.h" #import -class SmartCardTokenWrapper::Private{ +class SmartCardTokenWrapper::Private { public: id smartTokenClass; NSString *pin1; @@ -35,40 +36,44 @@ SmartCardTokenWrapper::SmartCardTokenWrapper(const std::string &password, id smartToken) : token(new Private) { - token->pin1 = [NSString stringWithUTF8String:password.c_str()]; + token->pin1 = [NSString stringWithStdString:password]; token->smartTokenClass = smartToken; } SmartCardTokenWrapper::~SmartCardTokenWrapper() noexcept = default; -NSError* SmartCardTokenWrapper::lastError() const { +NSError* SmartCardTokenWrapper::lastError() const +{ return token->error; } -std::vector SmartCardTokenWrapper::cert() const { - NSError *error; - auto result = encodeData([token->smartTokenClass getCertificateAndReturnError:&error]); +std::vector SmartCardTokenWrapper::cert() const { + NSError *error = nil; + auto result = [[token->smartTokenClass getCertificateAndReturnError:&error] toVector]; token->error = error; return result; } -std::vector SmartCardTokenWrapper::decrypt(const std::vector &data) const { - NSMutableData *nsdata = [NSMutableData dataWithBytesNoCopy:(void *)data.data() length:data.size() freeWhenDone:0]; - NSError *error; - auto result = encodeData([token->smartTokenClass decrypt:nsdata pin1:token->pin1 error:&error]); +libcdoc::result_t SmartCardTokenWrapper::deriveECDH1(std::vector& dst, const std::vector &public_key, unsigned int idx) +{ + NSError *error = nil; + dst = [[token->smartTokenClass derive:[NSData dataFromVectorNoCopy:public_key] pin1:token->pin1 error:&error] toVector]; token->error = error; - return result; + return dst.empty() ? libcdoc::CRYPTO_ERROR : libcdoc::OK; } -std::vector SmartCardTokenWrapper::derive(const std::vector &publicKey) const { - NSMutableData *nsdata = [NSMutableData dataWithBytesNoCopy:(void *)publicKey.data() length:publicKey.size() freeWhenDone:0]; - NSError *error; - auto result = encodeData([token->smartTokenClass derive:nsdata pin1:token->pin1 error:&error]); +libcdoc::result_t SmartCardTokenWrapper::decryptRSA(std::vector& dst, const std::vector& data, bool oaep, unsigned int idx) +{ + NSError *error = nil; + dst = [[token->smartTokenClass decrypt:[NSData dataFromVectorNoCopy:data] pin1:token->pin1 error:&error] toVector]; token->error = error; - return result; + return dst.empty() ? libcdoc::CRYPTO_ERROR : libcdoc::OK; } -std::vector SmartCardTokenWrapper::encodeData(const NSData *dataBlock) { - const unsigned char *buffer = reinterpret_cast(dataBlock.bytes); - return {buffer, std::next(buffer, dataBlock.length)}; +libcdoc::result_t SmartCardTokenWrapper::sign(std::vector &dst, HashAlgorithm algorithm, const std::vector &digest, unsigned int idx) +{ + NSError *error = nil; + dst = [[token->smartTokenClass authenticate:[NSData dataFromVectorNoCopy:digest] pin1:token->pin1 error:&error] toVector]; + token->error = error; + return dst.empty() ? libcdoc::CRYPTO_ERROR : libcdoc::OK; } diff --git a/CryptoLib/CryptoLib/X509CertificateType.swift b/CryptoLib/CryptoLib/X509CertificateType.swift index 7560551de..791084fe2 100644 --- a/CryptoLib/CryptoLib/X509CertificateType.swift +++ b/CryptoLib/CryptoLib/X509CertificateType.swift @@ -22,17 +22,17 @@ import ASN1Decoder -extension X509Certificate { - public enum CertType { - case UnknownType - case IDCardType - case DigiIDType - case EResidentType - case MobileIDType - case SmartIDType - case ESealType - } +@objc public enum CertType: UInt { + case UnknownType + case IDCardType + case DigiIDType + case EResidentType + case MobileIDType + case SmartIDType + case ESealType +} +extension X509Certificate { public func certType() -> CertType { if let ext = extensionObject(oid: OID.certificatePolicies) as? X509Certificate.CertificatePoliciesExtension { for policy in ext.policies ?? [] { diff --git a/CryptoLib/CryptoLib/XmlParser/CdocParserDelegate.h b/CryptoLib/CryptoLib/XmlParser/CdocParserDelegate.h deleted file mode 100644 index 5d04f947d..000000000 --- a/CryptoLib/CryptoLib/XmlParser/CdocParserDelegate.h +++ /dev/null @@ -1,35 +0,0 @@ -// -// CdocParserDelegate.h -// CryptoLib -/* - * Copyright 2017 - 2024 Riigi Infosüsteemi Amet - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - -#import -#import "Addressee.h" -#import "CryptoDataFile.h" -@interface CdocParserDelegate : NSObject -{ -} -@property (nonatomic, strong) NSMutableArray *addressees; -@property (nonatomic, strong) NSMutableArray *dataFiles; -@property (nonatomic, retain) NSString *currentFilenameNode; -@property (nonatomic) BOOL isNextCharactersFilename; -@property (nonatomic) BOOL isNextCharactersCertificate; -@property (nonatomic, strong) Addressee *lastAddressee; -@end diff --git a/CryptoLib/CryptoLib/XmlParser/CdocParserDelegate.m b/CryptoLib/CryptoLib/XmlParser/CdocParserDelegate.m deleted file mode 100644 index 4331f9c38..000000000 --- a/CryptoLib/CryptoLib/XmlParser/CdocParserDelegate.m +++ /dev/null @@ -1,89 +0,0 @@ -// -// CdocParserDelegate.m -// CryptoLib -/* - * Copyright 2017 - 2024 Riigi Infosüsteemi Amet - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - -#import "CdocParserDelegate.h" -@interface CdocParserDelegate () -@end - -@implementation CdocParserDelegate { -} - -- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict { - if ([elementName isEqualToString:@"denc:EncryptedKey"]) { - if (_addressees == nil){ - _addressees = [NSMutableArray new]; - } - if (_lastAddressee == nil){ - _lastAddressee = [Addressee new]; - } - NSString *attribute = attributeDict[@"Recipient"]; - NSArray *cn = [attribute componentsSeparatedByString:@","]; - Addressee *addressee = [Addressee new]; - if (cn.count > 1) { - addressee.surname = cn[0]; - addressee.givenName = cn[1]; - addressee.identifier = cn[2]; - } else { - addressee.identifier = cn[0]; - } - [_addressees addObject:addressee]; - _lastAddressee = addressee; - } - if ([elementName isEqualToString:@"ds:X509Certificate"]) { - _isNextCharactersCertificate = YES; - } - if ([elementName isEqualToString:@"denc:EncryptionProperty"] && [[attributeDict valueForKey: @"Name"] isEqual: @"orig_file"]) { - _isNextCharactersFilename = YES; - } -} - --(void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { - if (_isNextCharactersFilename) { - if (_currentFilenameNode) { - _currentFilenameNode = [_currentFilenameNode stringByAppendingString:string]; - } else { - _currentFilenameNode = string; - } - } - - if (_isNextCharactersCertificate) { - _lastAddressee.cert = [[NSData alloc] initWithBase64EncodedString:string options:NSDataBase64DecodingIgnoreUnknownCharacters]; - } -} - -- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(nullable NSString *)namespaceURI qualifiedName:(nullable NSString *)qName { - if (_isNextCharactersFilename) { - if (_dataFiles == nil){ - _dataFiles = [NSMutableArray new]; - } - NSArray *filenameWithBytesLength = [_currentFilenameNode componentsSeparatedByString:@"|"]; - NSString *filename = filenameWithBytesLength[0]; - CryptoDataFile *dataFile = [CryptoDataFile new]; - dataFile.filename = filename; - [_dataFiles addObject:dataFile]; - } - _currentFilenameNode = nil; - _isNextCharactersFilename = NO; - _isNextCharactersCertificate = NO; -} - -@end diff --git a/CryptoLib/CryptoLib/XmlParser/CdocParserDelegate.swift b/CryptoLib/CryptoLib/XmlParser/CdocParserDelegate.swift new file mode 100644 index 000000000..e4d0e3465 --- /dev/null +++ b/CryptoLib/CryptoLib/XmlParser/CdocParserDelegate.swift @@ -0,0 +1,77 @@ +// +// CdocParserDelegate.swift +// CryptoLib +/* + * Copyright 2017 - 2024 Riigi Infosüsteemi Amet + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +import Foundation + +public class CdocParser: NSObject { + @objc static public func parse(path: String) -> CdocInfo? { + guard let parser = XMLParser(contentsOf: URL(fileURLWithPath: path)) else { + NSLog("Error: Unable to read file at \(path)") + return nil + } + let delegate = CdocParserDelegate() + parser.delegate = delegate; + guard parser.parse() else { + NSLog("Error: Failed to parse XML") + return nil + } + return CdocInfo(addressees: delegate.addressees, dataFiles: delegate.dataFiles) + } +} + +class CdocParserDelegate: NSObject, XMLParserDelegate { + public var addressees: [Addressee] = [] + public var dataFiles: [CryptoDataFile] = [] + var data: String? = nil + + func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String: String]) { + switch elementName { + case "ds:X509Certificate": + data = String() + case "denc:EncryptionProperty" where attributeDict["Name"] == "orig_file": + data = String() + default: break + } + } + + func parser(_ parser: XMLParser, foundCharacters string: String) { + if data != nil { + data! += string + } + } + + func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { + guard data != nil else { return } + switch elementName { + case "ds:X509Certificate": + if let data = Data(base64Encoded: data!, options: .ignoreUnknownCharacters) { + addressees.append(Addressee(cert: data)) + } + case "denc:EncryptionProperty": + if let filename = data!.split(separator: "|").first { + dataFiles.append(CryptoDataFile(filename: String(filename))) + } + default: break + } + data = nil + } +} diff --git a/CryptoLib/CryptoLib/XmlParser/DdocParserDelegate.m b/CryptoLib/CryptoLib/XmlParser/DdocParserDelegate.m deleted file mode 100644 index fb314e146..000000000 --- a/CryptoLib/CryptoLib/XmlParser/DdocParserDelegate.m +++ /dev/null @@ -1,79 +0,0 @@ -// -// DdocParserDelegate.m -// CryptoLib -/* - * Copyright 2017 - 2024 Riigi Infosüsteemi Amet - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - -#if DEBUG -#define printLog(...) NSLog(__VA_ARGS__) -#else -#define printLog(...) -#endif - -#import "DdocParserDelegate.h" -@interface DdocParserDelegate () -@end - -@implementation DdocParserDelegate { - -} - -- (void) parserDidStartDocument:(NSXMLParser *)parser { - printLog(@"parserDidStartDocument"); -} - -- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict { - printLog(@"didStartElement --> %@", elementName); - - if ([elementName isEqualToString:@"DataFile"]) { - if (_dictionary == nil){ - _dictionary = [NSMutableDictionary new]; - } - NSString *attribute = attributeDict[@"Filename"]; - [_dictionary setObject:@"" forKey:attribute]; - _lastKey = attribute; - printLog(@"didStartElement --> %@", attributeDict[@"Filename"]); - } -} - --(void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { - - // If parsing ddoc original filenames, sometimes filename may contain new line symbols - if (string != nil && [string length] != 0 && ![string isEqualToString:@"\n "] && ![string isEqualToString:@"\n"]){ - string = [string stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]]; - if (_currentElement == nil ) { - _currentElement = [NSString new]; - } - _currentElement = [NSString stringWithFormat:@"%@%@", _currentElement, string]; - } - printLog(@"foundCharacters --> %@", string); -} - -- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName { - if ([_currentElement length] != 0) { - [_dictionary setValue:_currentElement forKey:_lastKey]; - _currentElement = @""; - } - printLog(@"didEndElement --> %@", elementName); -} - -- (void) parserDidEndDocument:(NSXMLParser *)parser { - printLog(@"parserDidEndDocument"); -} -@end diff --git a/CryptoLib/build-cdoc.sh b/CryptoLib/build-cdoc.sh index 004965c83..2628634e1 100755 --- a/CryptoLib/build-cdoc.sh +++ b/CryptoLib/build-cdoc.sh @@ -3,19 +3,21 @@ export PATH=$PATH:/usr/local/bin:/opt/homebrew/bin SOURCE_DIR=${DERIVED_SOURCES_DIR}/cdoc if [ ! -d ${SOURCE_DIR} ]; then - git clone -b mopp https://github.com/metsma/cdoc.git ${SOURCE_DIR}; + git clone -b expire https://github.com/open-eid/libcdoc.git ${SOURCE_DIR}; fi cmake \ - -DINSTALL_FRAMEWORKDIR=${BUILT_PRODUCTS_DIR} \ + -DFRAMEWORK_DESTINATION=${BUILT_PRODUCTS_DIR} \ -DCMAKE_INSTALL_PREFIX=${BUILT_PRODUCTS_DIR} \ -DCMAKE_BUILD_TYPE=${CONFIGURATION} \ -DCMAKE_OSX_SYSROOT=${PLATFORM_NAME} \ -DCMAKE_OSX_ARCHITECTURES="${ARCHS// /;}" \ -DCMAKE_OSX_DEPLOYMENT_TARGET=${IPHONEOS_DEPLOYMENT_TARGET} \ -DBUILD_SHARED_LIBS=NO \ + -DBUILD_TOOLS=NO \ -DOPENSSL_ROOT_DIR=${PROJECT_DIR}/../MoppLib/MoppLib/libdigidocpp/libdigidocpp.${PLATFORM_NAME} \ -DCMAKE_DISABLE_FIND_PACKAGE_SWIG=YES \ -DCMAKE_DISABLE_FIND_PACKAGE_Doxygen=YES \ + -DCMAKE_DISABLE_FIND_PACKAGE_Boost=YES \ -S ${SOURCE_DIR} -B ${TARGET_TEMP_DIR} cmake --build ${TARGET_TEMP_DIR} cmake --install ${TARGET_TEMP_DIR} diff --git a/MoppApp/MoppApp.xcodeproj/project.pbxproj b/MoppApp/MoppApp.xcodeproj/project.pbxproj index 248e4f809..12afb5eaf 100644 --- a/MoppApp/MoppApp.xcodeproj/project.pbxproj +++ b/MoppApp/MoppApp.xcodeproj/project.pbxproj @@ -30,12 +30,15 @@ 4E0F09ED2D76F6C0003F24B9 /* MoppLib.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = DF15038F2AC5CFFA007222B2 /* MoppLib.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; 4E0F09EE2D76F6C4003F24B9 /* SkSigningLib.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = DF1503A02AC5D01A007222B2 /* SkSigningLib.framework */; }; 4E0F09EF2D76F6C4003F24B9 /* SkSigningLib.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = DF1503A02AC5D01A007222B2 /* SkSigningLib.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; + 4E0F0A1C2D76F87D003F24B9 /* SettingsEncryptingView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E0F0A192D76F87D003F24B9 /* SettingsEncryptingView.swift */; }; + 4E0F0A1D2D76F87D003F24B9 /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E0F0A1A2D76F87D003F24B9 /* ViewController.swift */; }; 4E167D872B6D346F001B74A1 /* digidocpp.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4E167D862B6D346F001B74A1 /* digidocpp.framework */; }; 4E167D882B6D346F001B74A1 /* digidocpp.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 4E167D862B6D346F001B74A1 /* digidocpp.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; 4E59080024B0F914001B23A6 /* SmartIDEditViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E5907FF24B0F914001B23A6 /* SmartIDEditViewController.swift */; }; 4E59080224B258C7001B23A6 /* SmartIDChallengeViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E59080124B258C6001B23A6 /* SmartIDChallengeViewController.swift */; }; 4E59080424B2E295001B23A6 /* SmartIDSignature.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E59080324B2E295001B23A6 /* SmartIDSignature.swift */; }; 4E6E1D9B2AAB493A008B3E74 /* NFCEditViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E6E1D9A2AAB493A008B3E74 /* NFCEditViewController.swift */; }; + 4EE43A752D515048002773BB /* libMoppUI.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 4EE43A652D514E3C002773BB /* libMoppUI.a */; }; 4EE56D232AB0561C002648EE /* NFCSignature.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4EE56D222AB0561C002648EE /* NFCSignature.swift */; }; 4EE56D272AB058A6002648EE /* SwiftECC in Frameworks */ = {isa = PBXBuildFile; productRef = 4EE56D262AB058A6002648EE /* SwiftECC */; }; 540786E91E1A76640016ABA7 /* UITextView+Additions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 540786E81E1A76640016ABA7 /* UITextView+Additions.swift */; }; @@ -44,7 +47,7 @@ 54825EF81E1D270F00253FF0 /* String+Additions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 54825EF71E1D270F00253FF0 /* String+Additions.swift */; }; 54825EFB1E1D28E900253FF0 /* UIColor+Additions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 54825EFA1E1D28E900253FF0 /* UIColor+Additions.swift */; }; 54A4182B1E83FAD200559E2B /* MainInterface.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 54A418291E83FAD200559E2B /* MainInterface.storyboard */; }; - 54A4182F1E83FAD200559E2B /* shareExtension.appex in Embed App Extensions */ = {isa = PBXBuildFile; fileRef = 54A418241E83FAD200559E2B /* shareExtension.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; }; + 54A4182F1E83FAD200559E2B /* shareExtension.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = 54A418241E83FAD200559E2B /* shareExtension.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; }; 54A5729F1E82AC760099BFAF /* AppStore.plist in Resources */ = {isa = PBXBuildFile; fileRef = 54A5729E1E82AC760099BFAF /* AppStore.plist */; }; 54DC0DBF1E0BC0CD00C62B3D /* Landing.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 54DC0DBE1E0BC0CD00C62B3D /* Landing.storyboard */; }; C506EC7C1FB9CBFD00E07226 /* Constants.swift in Sources */ = {isa = PBXBuildFile; fileRef = C506EC7B1FB9CBFD00E07226 /* Constants.swift */; }; @@ -283,6 +286,13 @@ /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ + 4EE43A762D515048002773BB /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = E4250CBB1E0968D200530370 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 4EE43A642D514E3C002773BB; + remoteInfo = MoppUI; + }; 54A4182D1E83FAD200559E2B /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = E4250CBB1E0968D200530370 /* Project object */; @@ -321,15 +331,15 @@ /* End PBXContainerItemProxy section */ /* Begin PBXCopyFilesBuildPhase section */ - 54A418331E83FAD200559E2B /* Embed App Extensions */ = { + 54A418331E83FAD200559E2B /* Embed Foundation Extensions */ = { isa = PBXCopyFilesBuildPhase; buildActionMask = 2147483647; dstPath = ""; dstSubfolderSpec = 13; files = ( - 54A4182F1E83FAD200559E2B /* shareExtension.appex in Embed App Extensions */, + 54A4182F1E83FAD200559E2B /* shareExtension.appex in Embed Foundation Extensions */, ); - name = "Embed App Extensions"; + name = "Embed Foundation Extensions"; runOnlyForDeploymentPostprocessing = 0; }; E4250D081E0A911100530370 /* Embed Frameworks */ = { @@ -367,11 +377,14 @@ 39CDA7E920ADBCEB006E2E9F /* Crypto.storyboard */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; path = Crypto.storyboard; sourceTree = ""; }; 39CDA7ED20ADBE93006E2E9F /* CryptoViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CryptoViewController.swift; sourceTree = ""; }; 39F8EFE620D263B5001BCF73 /* TokenFlow.storyboard */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; path = TokenFlow.storyboard; sourceTree = ""; }; + 4E0F0A192D76F87D003F24B9 /* SettingsEncryptingView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsEncryptingView.swift; sourceTree = ""; }; + 4E0F0A1A2D76F87D003F24B9 /* ViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ViewController.swift; sourceTree = ""; }; 4E167D862B6D346F001B74A1 /* digidocpp.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = digidocpp.framework; path = "${DIGIDOCPP_PATH}/lib/digidocpp.framework"; sourceTree = ""; }; 4E5907FF24B0F914001B23A6 /* SmartIDEditViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SmartIDEditViewController.swift; sourceTree = ""; }; 4E59080124B258C6001B23A6 /* SmartIDChallengeViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SmartIDChallengeViewController.swift; sourceTree = ""; }; 4E59080324B2E295001B23A6 /* SmartIDSignature.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SmartIDSignature.swift; sourceTree = ""; }; 4E6E1D9A2AAB493A008B3E74 /* NFCEditViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NFCEditViewController.swift; sourceTree = ""; }; + 4EE43A652D514E3C002773BB /* libMoppUI.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libMoppUI.a; sourceTree = BUILT_PRODUCTS_DIR; }; 4EE56D222AB0561C002648EE /* NFCSignature.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NFCSignature.swift; sourceTree = ""; }; 540786E81E1A76640016ABA7 /* UITextView+Additions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "UITextView+Additions.swift"; sourceTree = ""; }; 54825EF41E1CFE9600253FF0 /* Date+Additions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Date+Additions.swift"; sourceTree = ""; }; @@ -649,6 +662,7 @@ 4E0F09EE2D76F6C4003F24B9 /* SkSigningLib.framework in Frameworks */, DF1503AB2AC5D1E5007222B2 /* ZIPFoundation in Frameworks */, 4EE56D272AB058A6002648EE /* SwiftECC in Frameworks */, + 4EE43A752D515048002773BB /* libMoppUI.a in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -696,6 +710,22 @@ name = "Token flow"; sourceTree = ""; }; + 4E0F0A1B2D76F87D003F24B9 /* MoppUI */ = { + isa = PBXGroup; + children = ( + 4E0F0A192D76F87D003F24B9 /* SettingsEncryptingView.swift */, + 4E0F0A1A2D76F87D003F24B9 /* ViewController.swift */, + ); + path = MoppUI; + sourceTree = ""; + }; + 4E8483B42D4F672B00C31A75 /* Encrypting */ = { + isa = PBXGroup; + children = ( + ); + path = Encrypting; + sourceTree = ""; + }; 540786E61E1A76280016ABA7 /* Extensions */ = { isa = PBXGroup; children = ( @@ -933,6 +963,7 @@ C593D9E6208F1972000B3BF6 /* Settings */ = { isa = PBXGroup; children = ( + 4E8483B42D4F672B00C31A75 /* Encrypting */, DF716E932B45CFD60004DCB6 /* Signing */, C55BB1C82090BF4A00618AC4 /* About */, DFC2ADBF29437778008A1CD2 /* Accessibility */, @@ -1108,6 +1139,7 @@ E4250CC51E0968D200530370 /* MoppApp */, 54A418251E83FAD200559E2B /* shareExtension */, DFF6A54E27E14C180055F8D5 /* MoppAppTests */, + 4E0F0A1B2D76F87D003F24B9 /* MoppUI */, E4250CC41E0968D200530370 /* Products */, F9074FEF4DC2DB83A60B75B9 /* Frameworks */, ); @@ -1118,6 +1150,7 @@ children = ( E4250CC31E0968D200530370 /* MoppApp.app */, 54A418241E83FAD200559E2B /* shareExtension.appex */, + 4EE43A652D514E3C002773BB /* libMoppUI.a */, ); name = Products; sourceTree = ""; @@ -1266,6 +1299,23 @@ /* End PBXGroup section */ /* Begin PBXNativeTarget section */ + 4EE43A642D514E3C002773BB /* MoppUI */ = { + isa = PBXNativeTarget; + buildConfigurationList = 4EE43A712D514E3C002773BB /* Build configuration list for PBXNativeTarget "MoppUI" */; + buildPhases = ( + 4EE43A612D514E3C002773BB /* Sources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = MoppUI; + packageProductDependencies = ( + ); + productName = MoppUI; + productReference = 4EE43A652D514E3C002773BB /* libMoppUI.a */; + productType = "com.apple.product-type.library.static"; + }; 54A418231E83FAD200559E2B /* shareExtension */ = { isa = PBXNativeTarget; buildConfigurationList = 54A418321E83FAD200559E2B /* Build configuration list for PBXNativeTarget "shareExtension" */; @@ -1294,13 +1344,14 @@ E4250CC01E0968D200530370 /* Frameworks */, E4250CC11E0968D200530370 /* Resources */, E4250D081E0A911100530370 /* Embed Frameworks */, - 54A418331E83FAD200559E2B /* Embed App Extensions */, + 54A418331E83FAD200559E2B /* Embed Foundation Extensions */, DF4FC5552AC5D3EE00910E4B /* Setup Firebase Crashlytics */, ); buildRules = ( ); dependencies = ( 54A4182E1E83FAD200559E2B /* PBXTargetDependency */, + 4EE43A772D515048002773BB /* PBXTargetDependency */, ); name = MoppApp; packageProductDependencies = ( @@ -1320,10 +1371,14 @@ E4250CBB1E0968D200530370 /* Project object */ = { isa = PBXProject; attributes = { - LastSwiftUpdateCheck = 1340; - LastUpgradeCheck = 1250; + BuildIndependentTargetsInParallel = YES; + LastSwiftUpdateCheck = 1620; + LastUpgradeCheck = 1620; ORGANIZATIONNAME = "Riigi Infosüsteemi Amet"; TargetAttributes = { + 4EE43A642D514E3C002773BB = { + CreatedOnToolsVersion = 16.2; + }; 54A418231E83FAD200559E2B = { CreatedOnToolsVersion = 8.2.1; LastSwiftMigration = 0900; @@ -1346,10 +1401,9 @@ }; buildConfigurationList = E4250CBE1E0968D200530370 /* Build configuration list for PBXProject "MoppApp" */; compatibilityVersion = "Xcode 15.0"; - developmentRegion = English; + developmentRegion = en; hasScannedForEncodings = 0; knownRegions = ( - English, en, Base, et, @@ -1383,6 +1437,7 @@ targets = ( E4250CC21E0968D200530370 /* MoppApp */, 54A418231E83FAD200559E2B /* shareExtension */, + 4EE43A642D514E3C002773BB /* MoppUI */, ); }; /* End PBXProject section */ @@ -1575,6 +1630,15 @@ /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ + 4EE43A612D514E3C002773BB /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 4E0F0A1C2D76F87D003F24B9 /* SettingsEncryptingView.swift in Sources */, + 4E0F0A1D2D76F87D003F24B9 /* ViewController.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; 54A418201E83FAD200559E2B /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; @@ -1788,6 +1852,11 @@ /* End PBXSourcesBuildPhase section */ /* Begin PBXTargetDependency section */ + 4EE43A772D515048002773BB /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 4EE43A642D514E3C002773BB /* MoppUI */; + targetProxy = 4EE43A762D515048002773BB /* PBXContainerItemProxy */; + }; 54A4182E1E83FAD200559E2B /* PBXTargetDependency */ = { isa = PBXTargetDependency; target = 54A418231E83FAD200559E2B /* shareExtension */; @@ -1817,6 +1886,46 @@ /* End PBXVariantGroup section */ /* Begin XCBuildConfiguration section */ + 4EE43A692D514E3C002773BB /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + LOCALIZATION_PREFERS_STRING_CATALOGS = YES; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + OTHER_LDFLAGS = "-ObjC"; + PRODUCT_NAME = "$(TARGET_NAME)"; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 4EE43A6A2D514E3C002773BB /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + LOCALIZATION_PREFERS_STRING_CATALOGS = YES; + MTL_FAST_MATH = YES; + OTHER_LDFLAGS = "-ObjC"; + PRODUCT_NAME = "$(TARGET_NAME)"; + SKIP_INSTALL = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; 54A418301E83FAD200559E2B /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { @@ -1877,11 +1986,10 @@ E4250CD81E0968D200530370 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { - ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; ALWAYS_SEARCH_USER_PATHS = NO; CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; CLANG_ANALYZER_NONNULL = YES; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; @@ -1912,9 +2020,10 @@ CURRENT_PROJECT_VERSION = 0; DEBUG_INFORMATION_FORMAT = dwarf; DEFINES_MODULE = YES; + ENABLE_MODULE_VERIFIER = YES; ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_TESTABILITY = YES; - GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_C_LANGUAGE_STANDARD = gnu17; GCC_DYNAMIC_NO_PIC = NO; GCC_NO_COMMON_BLOCKS = YES; GCC_OPTIMIZATION_LEVEL = 0; @@ -1930,6 +2039,7 @@ GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 15.0; MARKETING_VERSION = 2.8.0; + MODULE_VERIFIER_SUPPORTED_LANGUAGE_STANDARDS = "gnu17 gnu++20"; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = iphoneos; @@ -1939,11 +2049,10 @@ E4250CD91E0968D200530370 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { - ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; ALWAYS_SEARCH_USER_PATHS = NO; CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; CLANG_ANALYZER_NONNULL = YES; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; @@ -1974,9 +2083,10 @@ CURRENT_PROJECT_VERSION = 0; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; DEFINES_MODULE = YES; + ENABLE_MODULE_VERIFIER = YES; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_C_LANGUAGE_STANDARD = gnu17; GCC_NO_COMMON_BLOCKS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; @@ -1986,6 +2096,7 @@ GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 15.0; MARKETING_VERSION = 2.8.0; + MODULE_VERIFIER_SUPPORTED_LANGUAGE_STANDARDS = "gnu17 gnu++20"; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; SWIFT_COMPILATION_MODE = wholemodule; @@ -2010,6 +2121,7 @@ DEVELOPMENT_TEAM = ET847QJV9F; DIGIDOCPP_PATH = "$(SRCROOT)/../MoppLib/MoppLib/libdigidocpp/libdigidocpp.iphoneos"; "DIGIDOCPP_PATH[sdk=iphonesimulator*]" = "$(SRCROOT)/../MoppLib/MoppLib/libdigidocpp/libdigidocpp.iphonesimulator"; + ENABLE_MODULE_VERIFIER = YES; FRAMEWORK_SEARCH_PATHS = ( "$(inherited)", "$(DIGIDOCPP_PATH)/lib", @@ -2021,17 +2133,16 @@ "DEFAULT_CENTRAL_CONFIGURATION_UPDATE_INTERVAL=$(DEFAULT_CENTRAL_CONFIGURATION_UPDATE_INTERVAL)", ); GOOGLE_CONF_REQUIRED = YES; - HEADER_SEARCH_PATHS = "$(inherited)"; INFOPLIST_FILE = MoppApp/Info.plist; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", ); + MODULE_VERIFIER_SUPPORTED_LANGUAGE_STANDARDS = "gnu17 gnu++20"; OTHER_LDFLAGS = ( "$(inherited)", "-ObjC", ); - OTHER_SWIFT_FLAGS = "$(inherited)"; PRODUCT_BUNDLE_IDENTIFIER = ee.ria.digidoc; PRODUCT_NAME = "$(TARGET_NAME)"; PROVISIONING_PROFILE = $APP_PROVISIONING_PROFILE; @@ -2059,6 +2170,7 @@ DEVELOPMENT_TEAM = ET847QJV9F; DIGIDOCPP_PATH = "$(SRCROOT)/../MoppLib/MoppLib/libdigidocpp/libdigidocpp.iphoneos"; "DIGIDOCPP_PATH[sdk=iphonesimulator*]" = "$(SRCROOT)/../MoppLib/MoppLib/libdigidocpp/libdigidocpp.iphonesimulator"; + ENABLE_MODULE_VERIFIER = YES; FRAMEWORK_SEARCH_PATHS = ( "$(inherited)", "$(DIGIDOCPP_PATH)/lib", @@ -2070,17 +2182,16 @@ "DEFAULT_CENTRAL_CONFIGURATION_UPDATE_INTERVAL=$(DEFAULT_CENTRAL_CONFIGURATION_UPDATE_INTERVAL)", ); GOOGLE_CONF_REQUIRED = YES; - HEADER_SEARCH_PATHS = "$(inherited)"; INFOPLIST_FILE = MoppApp/Info.plist; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", ); + MODULE_VERIFIER_SUPPORTED_LANGUAGE_STANDARDS = "gnu17 gnu++20"; OTHER_LDFLAGS = ( "$(inherited)", "-ObjC", ); - OTHER_SWIFT_FLAGS = "$(inherited)"; PRODUCT_BUNDLE_IDENTIFIER = ee.ria.digidoc; PRODUCT_NAME = "$(TARGET_NAME)"; PROVISIONING_PROFILE = $APP_PROVISIONING_PROFILE; @@ -2094,6 +2205,15 @@ /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ + 4EE43A712D514E3C002773BB /* Build configuration list for PBXNativeTarget "MoppUI" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 4EE43A692D514E3C002773BB /* Debug */, + 4EE43A6A2D514E3C002773BB /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; 54A418321E83FAD200559E2B /* Build configuration list for PBXNativeTarget "shareExtension" */ = { isa = XCConfigurationList; buildConfigurations = ( diff --git a/MoppApp/MoppApp.xcodeproj/xcshareddata/xcschemes/MoppApp.xcscheme b/MoppApp/MoppApp.xcodeproj/xcshareddata/xcschemes/MoppApp.xcscheme index a7d45afaa..ffe1614c1 100755 --- a/MoppApp/MoppApp.xcodeproj/xcshareddata/xcschemes/MoppApp.xcscheme +++ b/MoppApp/MoppApp.xcodeproj/xcshareddata/xcschemes/MoppApp.xcscheme @@ -1,6 +1,6 @@ String - func determineName(addressee: Addressee) -> String } extension AddresseeActions { @@ -35,18 +32,17 @@ extension AddresseeActions { if addressee.givenName == nil { return addressee.identifier } else { - return "\(addressee.surname.uppercased()), \(addressee.givenName.uppercased()), \(addressee.identifier.uppercased())" + return "\(addressee.surname?.uppercased() ?? ""), \(addressee.givenName?.uppercased() ?? ""), \(addressee.identifier.uppercased())" } } func determineInfo(addressee: Addressee) -> String { - let x509 = try? X509Certificate(der: addressee.cert) - let addresseeType = displayAddresseeType(x509?.certType()) - let validTo = "\(L(LocKey.cryptoValidTo)) \(MoppDateFormatter.shared.ddMMYYYY(toString: x509?.notAfter ?? Date()))" + let addresseeType = displayAddresseeType(addressee.certType) + let validTo = addressee.validTo != nil ? "\(L(LocKey.cryptoValidTo)) \(MoppDateFormatter.shared.ddMMYYYY(toString: addressee.validTo!))" : "" return "\(addresseeType) (\(validTo))" } - func displayAddresseeType(_ type: X509Certificate.CertType?) -> String { + func displayAddresseeType(_ type: CertType?) -> String { switch type { case .IDCardType: return L(.cryptoTypeIdCard) diff --git a/MoppApp/MoppApp/AddresseeViewController.swift b/MoppApp/MoppApp/AddresseeViewController.swift index 7354fdf61..2a0173844 100644 --- a/MoppApp/MoppApp/AddresseeViewController.swift +++ b/MoppApp/MoppApp/AddresseeViewController.swift @@ -22,7 +22,6 @@ */ import Foundation -import CryptoLib protocol AddresseeViewControllerDelegate: AnyObject { func addAddresseeToContainer(selectedAddressees: [Addressee]) @@ -93,7 +92,7 @@ class AddresseeViewController : MoppViewController { selectedIndexes = [] showLoading(show: true) - if (!MoppLibManager.sharedInstance().isConnected()) { + if (!MoppLibManager.shared.isConnected) { self.infoAlert(message: L(.noConnectionMessage)) self.showLoading(show: false) return @@ -252,13 +251,7 @@ extension AddresseeViewController : UITableViewDataSource { cell.accessibilityLabel = "" cell.accessibilityUserInputLabels = [""] } - let isSelected = selectedAddressees.contains { element in - if ((element as Addressee).cert == (foundAddressees[row] as Addressee).cert) { - return true - } - return false - } - let isAddButtonDisabled = selectedIndexes.contains(row) || isSelected + let isAddButtonDisabled = selectedIndexes.contains(row) || selectedAddressees.contains(foundAddressees[row]) cell.populate(addressee: foundAddressees[row] as Addressee, index: row, isAddButtonDisabled: isAddButtonDisabled) if indexPath.row == 0 { UIAccessibility.post(notification: .layoutChanged, argument: cell) @@ -405,14 +398,9 @@ extension AddresseeViewController : ContainerFoundAddresseeCellDelegate { } func addAddresseeToSelectedArea(addressee: Addressee) { - if !selectedAddressees.contains(where: {( - ($0.givenName != nil && $0.givenName == addressee.givenName && - $0.surname != nil && $0.surname == addressee.surname) || - $0.identifier == addressee.identifier) && $0.cert == addressee.cert && $0.validTo == addressee.validTo - }) { + if !selectedAddressees.contains(addressee) { selectedAddressees.insert(addressee, at: 0) } - self.tableView.reloadData() } diff --git a/MoppApp/MoppApp/Configuration.swift b/MoppApp/MoppApp/Configuration.swift index 8d0037531..246360276 100644 --- a/MoppApp/MoppApp/Configuration.swift +++ b/MoppApp/MoppApp/Configuration.swift @@ -24,7 +24,6 @@ import Foundation import ASN1Decoder -import CryptoLib internal struct MOPPConfiguration: Codable { var TSLURL: String @@ -124,15 +123,15 @@ internal struct DefaultMoppConfiguration: Codable { public class MoppConfiguration { static var sivaUrl: String? static var tslUrl: String? - static var tslCerts: Array? - static var ldapCerts: Array? + static var tslCerts: [String]? + static var ldapCerts: [String]? static var tsaUrl: String? static var ocspIssuers: [String: String]? - static var certBundle: Array? + static var certBundle: [String]? static var tsaCert: String? static func getMoppLibConfiguration() -> MoppLibConfiguration { - return MoppLibConfiguration(configuration: sivaUrl, tslurl: tslUrl, tslcerts: tslCerts, ldapcerts: ldapCerts, tsaurl: tsaUrl, ocspissuers: ocspIssuers, certbundle: certBundle, tsacert: tsaCert) + return MoppLibConfiguration(sivaURL: sivaUrl ?? "", tslURL: tslUrl ?? "", tslCerts: tslCerts ?? [], ldapCerts: ldapCerts ?? [], tsaURL: tsaUrl ?? "", ocspIssuers: ocspIssuers ?? [:], certBundle: certBundle ?? [], tsaCert: tsaCert ?? "") } } diff --git a/MoppApp/MoppApp/ContainerActions.swift b/MoppApp/MoppApp/ContainerActions.swift index bab5a5230..bf5cc4c3c 100644 --- a/MoppApp/MoppApp/ContainerActions.swift +++ b/MoppApp/MoppApp/ContainerActions.swift @@ -21,9 +21,7 @@ * */ -import Foundation import SkSigningLib -import CryptoLib protocol ContainerActions { func openExistingContainer(with url: URL, cleanup: Bool, isEmptyFileImported: Bool, isSendingToSivaAgreed: Bool) @@ -79,7 +77,7 @@ extension ContainerActions where Self: UIViewController { let ext = urls.first!.pathExtension if landingViewController.containerType == nil { - if ext.isCdocContainerExtension { + if ext.isCryptoContainerExtension { landingViewController.containerType = .cdoc } else { landingViewController.containerType = .asic @@ -88,7 +86,7 @@ extension ContainerActions where Self: UIViewController { let isAsicOrPadesContainer = (ext.isAsicContainerExtension || (ext == ContainerFormatPDF && SiVaUtil.isSignedPDF(url: urls.first! as CFURL))) && landingViewController.containerType == .asic - let isCdocContainer = ext.isCdocContainerExtension && landingViewController.containerType == .cdoc + let isCdocContainer = ext.isCryptoContainerExtension && landingViewController.containerType == .cdoc if (isAsicOrPadesContainer || isCdocContainer) && urls.count == 1 { SiVaUtil.setIsSentToSiva(isSent: false) @@ -143,13 +141,13 @@ extension ContainerActions where Self: UIViewController { return } - if err?.code == 10018 && (url.lastPathComponent.hasSuffix(ContainerFormatDdoc) || url.lastPathComponent.hasSuffix(ContainerFormatPDF)) { - + if err?.code == MoppLibErrorCode.moppLibErrorNoInternetConnection.rawValue && (url.lastPathComponent.hasSuffix(ContainerFormatDdoc) || url.lastPathComponent.hasSuffix(ContainerFormatPDF)) { + let alert = AlertUtil.messageAlert(message: L(.noConnectionMessage), alertAction: nil) navController?.viewControllers.last!.present(alert, animated: true) return - } else if err?.code == 10027 { + } else if err?.code == MoppLibErrorCode.moppLibErrorSslHandshakeFailed.rawValue { let alert = AlertUtil.messageAlert(message: L(.sslHandshakeMessage), alertAction: nil) navController?.viewControllers.last!.present(alert, animated: true) @@ -181,29 +179,17 @@ extension ContainerActions where Self: UIViewController { printLog("Unable to delete contents of Documents/Inbox directory: \(error.localizedDescription)") } } else { - let containerViewController = CryptoContainerViewController.instantiate() - let container = CryptoContainer(filename: fileName as NSString, filePath: newFilePath as NSString) - - MoppLibCryptoActions.sharedInstance().parseCdocInfo( - newFilePath as String?, - success: {(_ cdocInfo: CdocInfo?) -> Void in - guard let strongCdocInfo = cdocInfo else { return } - container.addressees = strongCdocInfo.addressees as? [Addressee] ?? [] - container.dataFiles = strongCdocInfo.dataFiles - containerViewController.containerPath = newFilePath - containerViewController.state = .opened - containerViewController.container = container - containerViewController.isContainerEncrypted = true - landingViewController.importProgressViewController.dismissRecursively(animated: false, completion: { - navController?.pushViewController(containerViewController, animated: true) - }) - }, - failure: { _ in - DispatchQueue.main.async { - failure(nil) - } - } - ) + Decrypt.parseCdocInfo(withFullPath: newFilePath) { cdocInfo in + guard let strongCdocInfo = cdocInfo else { return failure(nil) } + let containerViewController = CryptoContainerViewController.instantiate() + containerViewController.containerPath = newFilePath + containerViewController.state = .opened + containerViewController.container = CryptoContainer(filename: fileName, filePath: newFilePath, cdocInfo: strongCdocInfo) + containerViewController.isContainerEncrypted = true + landingViewController.importProgressViewController.dismissRecursively(animated: false, completion: { + navController?.pushViewController(containerViewController, animated: true) + }) + } } url.stopAccessingSecurityScopedResource() } @@ -274,7 +260,7 @@ extension ContainerActions where Self: UIViewController { failure: { error in landingViewController.importProgressViewController.dismissRecursively(animated: false, completion: { [weak self] in guard let nsError = error as NSError? else { return } - if nsError.code == Int(MoppLibErrorCode.moppLibErrorDuplicatedFilename.rawValue) { + if nsError.code == MoppLibErrorCode.moppLibErrorDuplicatedFilename.rawValue { DispatchQueue.main.async { self?.infoAlert(message: L(.containerDetailsFileAlreadyExists)) } @@ -288,18 +274,14 @@ extension ContainerActions where Self: UIViewController { } else { let containerViewController = topSigningViewController as? CryptoContainerViewController dataFilePaths.forEach { - let filename = ($0 as NSString).lastPathComponent as NSString + let filename = ($0 as NSString).lastPathComponent if isDuplicatedFilename(container: (containerViewController?.container)!, filename: filename) { DispatchQueue.main.async { self.infoAlert(message: L(.containerDetailsFileAlreadyExists)) } return } - let dataFile = CryptoDataFile.init() - dataFile.filename = filename as String? - dataFile.filePath = $0 - - containerViewController?.container.dataFiles.add(dataFile) + containerViewController?.container.dataFiles.append(CryptoDataFile(filename: filename, filePath: $0)) } landingViewController.importProgressViewController.dismissRecursively(animated: false, completion: { @@ -323,15 +305,10 @@ extension ContainerActions where Self: UIViewController { } } - private func isDuplicatedFilename(container: CryptoContainer, filename: NSString) -> Bool { - for dataFile in container.dataFiles { - if let strongDataFile = dataFile as? CryptoDataFile { - if strongDataFile.filename as NSString == filename { - return true - } - } + private func isDuplicatedFilename(container: CryptoContainer, filename: String) -> Bool { + return container.dataFiles.contains { dataFile in + return dataFile.filename == filename } - return false } func createNewContainer(with url: URL, dataFilePaths: [String], isEmptyFileImported: Bool, startSigningWhenCreated: Bool = false, cleanUpDataFilesInDocumentsFolder: Bool = true) { @@ -347,7 +324,7 @@ extension ContainerActions where Self: UIViewController { if landingViewController.containerType == .asic { containerFilename = FileUtil.getFileName(currentFileName: filename) + "." + DefaultContainerFormat } else { - containerFilename = FileUtil.getFileName(currentFileName: filename) + "." + ContainerFormatCdoc + containerFilename = FileUtil.getFileName(currentFileName: filename) + "." + (DefaultsHelper.useCDoc2Encryption ? ContainerFormatCdoc2 : ContainerFormatCdoc) } var containerPath = MoppFileManager.shared.filePath(withFileName: containerFilename) @@ -418,14 +395,12 @@ extension ContainerActions where Self: UIViewController { ) } else { let containerViewController = CryptoContainerViewController.instantiate() - let container = CryptoContainer(filename: containerFilename as NSString, filePath: containerPath as NSString) + let container = CryptoContainer(filename: containerFilename , filePath: containerPath) containerViewController.containerPath = containerPath for dataFilePath in containerFilePaths { - let dataFile = CryptoDataFile.init() - dataFile.filename = FileUtil.getFileName(currentFileName: (dataFilePath as NSString).lastPathComponent) - dataFile.filePath = dataFilePath - container.dataFiles.add(dataFile) + container.dataFiles.append(CryptoDataFile( + filename: FileUtil.getFileName(currentFileName: (dataFilePath as NSString).lastPathComponent), filePath: dataFilePath)) } containerViewController.container = container diff --git a/MoppApp/MoppApp/ContainerAddAllButtonCell.swift b/MoppApp/MoppApp/ContainerAddAllButtonCell.swift index 957563394..e62dad4f7 100644 --- a/MoppApp/MoppApp/ContainerAddAllButtonCell.swift +++ b/MoppApp/MoppApp/ContainerAddAllButtonCell.swift @@ -22,7 +22,6 @@ */ import Foundation -import CryptoLib class ContainerAddAllButtonCell: UITableViewCell { diff --git a/MoppApp/MoppApp/ContainerAddresseeCell.swift b/MoppApp/MoppApp/ContainerAddresseeCell.swift index d21accfa7..53e0df30d 100644 --- a/MoppApp/MoppApp/ContainerAddresseeCell.swift +++ b/MoppApp/MoppApp/ContainerAddresseeCell.swift @@ -22,8 +22,6 @@ */ import Foundation -import UIKit -import CryptoLib protocol ContainerAddresseeCellDelegate : AnyObject { func removeAddressee(index: Int) diff --git a/MoppApp/MoppApp/ContainerFoundAddresseeCell.swift b/MoppApp/MoppApp/ContainerFoundAddresseeCell.swift index 4050b4e0a..cf896b2f9 100644 --- a/MoppApp/MoppApp/ContainerFoundAddresseeCell.swift +++ b/MoppApp/MoppApp/ContainerFoundAddresseeCell.swift @@ -22,7 +22,6 @@ */ import Foundation -import CryptoLib protocol ContainerFoundAddresseeCellDelegate : AnyObject { func addAddresseeToSelectedArea(index: Int, completionHandler: @escaping () -> Void) diff --git a/MoppApp/MoppApp/ContainerRemovalActions.swift b/MoppApp/MoppApp/ContainerRemovalActions.swift index a165da6e5..2105f0c9b 100644 --- a/MoppApp/MoppApp/ContainerRemovalActions.swift +++ b/MoppApp/MoppApp/ContainerRemovalActions.swift @@ -46,7 +46,7 @@ class ContainerRemovalActions { return false } - cryptoContainer.dataFiles.removeObject(at: 0) + cryptoContainer.dataFiles.remove(at: 0) return cryptoContainer.dataFiles.count == 0 } diff --git a/MoppApp/MoppApp/ContainerSignatureCell.swift b/MoppApp/MoppApp/ContainerSignatureCell.swift index b690e1703..4382282b2 100644 --- a/MoppApp/MoppApp/ContainerSignatureCell.swift +++ b/MoppApp/MoppApp/ContainerSignatureCell.swift @@ -44,13 +44,7 @@ class ContainerSignatureCell: UITableViewCell { weak var delegate: ContainerSignatureDelegate? = nil var signatureStatus: MoppLibSignatureStatus? - - #if USE_TEST_DDS - let useTestDDS = true - #else - let useTestDDS = false - #endif - + enum ColorTheme { case neutral case showInvalid @@ -137,16 +131,9 @@ class ContainerSignatureCell: UITableViewCell { } func setRoleText(signature: MoppLibSignature) { - let rolesData = signature.roleAndAddressData.roles - if let roles = rolesData, !roles.isEmpty { - roleInfo.text = roles.joined(separator: " / ") - roleInfo.isHidden = false - setNeedsUpdateConstraints() - } else { - roleInfo.text = "" - roleInfo.isHidden = true - setNeedsUpdateConstraints() - } + roleInfo.isHidden = signature.roleAndAddressData.roles.isEmpty + roleInfo.text = signature.roleAndAddressData.roles.joined(separator: " / ") + setNeedsUpdateConstraints() roleInfo.resetLabelProperties() } diff --git a/MoppApp/MoppApp/ContainerViewController.swift b/MoppApp/MoppApp/ContainerViewController.swift index c20c0d3d7..9860f2a91 100644 --- a/MoppApp/MoppApp/ContainerViewController.swift +++ b/MoppApp/MoppApp/ContainerViewController.swift @@ -22,8 +22,6 @@ */ import Foundation -import MoppLib -import CryptoLib protocol ContainerViewControllerDelegate: AnyObject { func getDataFileCount() -> Int @@ -42,8 +40,8 @@ protocol SigningContainerViewControllerDelegate: AnyObject { func startSigning() func getSignaturesCount() -> Int func getTimestampTokensCount() -> Int - func getSignature(index: Int) -> Any - func getTimestampToken(index: Int) -> Any + func getSignature(index: Int) -> MoppLibSignature? + func getTimestampToken(index: Int) -> MoppLibSignature? func removeSignature(index: Int) func isContainerSignable() -> Bool func isCades() -> Bool @@ -51,7 +49,7 @@ protocol SigningContainerViewControllerDelegate: AnyObject { protocol CryptoContainerViewControllerDelegate: AnyObject { func addAddressees() - func getAddressee(index: Int) -> Any + func getAddressee(index: Int) -> Addressee func getAddresseeCount() -> Int func removeSelectedAddressee(index: Int) func getContainer() -> CryptoContainer @@ -192,7 +190,7 @@ class ContainerViewController : MoppViewController, ContainerActions, PreviewAct let containerExtension = URL(fileURLWithPath: containerPath).pathExtension - LandingViewController.shared.containerType = containerExtension.isCdocContainerExtension ? .cdoc : .asic + LandingViewController.shared.containerType = containerExtension.isCryptoContainerExtension ? .cdoc : .asic landingViewController.tabButtonsDelegate = self @@ -337,8 +335,7 @@ class ContainerViewController : MoppViewController, ContainerActions, PreviewAct if let dataFiles = asicContainer?.dataFiles, !isEmptyFileWarningSet { var isEmptyFileInContainer = false for dataFile in dataFiles { - guard let dataFile = dataFile as? MoppLibDataFile, - dataFile.fileSize == 0 else { continue } + guard dataFile.fileSize == 0 else { continue } isEmptyFileInContainer = true break } @@ -376,12 +373,9 @@ class ContainerViewController : MoppViewController, ContainerActions, PreviewAct } } - static func isXades(signatures: [Any]) -> Bool { + static func isXades(signatures: [MoppLibSignature]) -> Bool { return signatures.contains { signature in - if let sig = signature as? MoppLibSignature { - return sig.signatureFormat.lowercased().contains("bes") - } - return false + return signature.signatureFormat.lowercased().contains("bes") } } @@ -506,10 +500,8 @@ extension ContainerViewController : UITableViewDataSource { guard let calendarDate = calendar.date(from: dateComponents) else { printLog("Unable to get date from calendar components"); DefaultsHelper.isTimestampedDdoc = false; return } if signingContainer.isAsics(), signingContainer.dataFiles.count == 1, signingContainer.signatures.count == 1, - let singleFile: MoppLibDataFile = signingContainer.dataFiles[0] as? MoppLibDataFile, - singleFile.fileName.hasSuffix(ContainerFormatDdoc), - let singleSignature: MoppLibSignature = signingContainer.signatures[0] as? MoppLibSignature, - let timestamp = ISO8601DateFormatter().date(from: singleSignature.timestamp) { + signingContainer.dataFiles[0].fileName.hasSuffix(ContainerFormatDdoc), + let timestamp = ISO8601DateFormatter().date(from: signingContainer.signatures[0].timestamp) { DefaultsHelper.isTimestampedDdoc = !timestamp.isAfter(anotherDate: calendarDate) return } else if signingContainer.isDdoc(), state != .preview { @@ -540,7 +532,7 @@ extension ContainerViewController : UITableViewDataSource { let cell = tableView.dequeueReusableCell(withType: ContainerSignatureCell.self, for: indexPath)! cell.delegate = self cell.accessibilityUserInputLabels = ["\(L(.voiceControlSignature)) \(row + 1)"] - var signature = asicsSignatures.isEmpty ? (signingContainerViewDelegate.getSignature(index: indexPath.row) as? MoppLibSignature) : asicsSignatures[indexPath.row] + var signature = asicsSignatures.isEmpty ? signingContainerViewDelegate.getSignature(index: indexPath.row) : asicsSignatures[indexPath.row] if isAsicsContainer() && !asicsSignatures.isEmpty && signingContainerViewDelegate.getTimestampTokensCount() > 0 && asicsSignatures.count >= indexPath.row { signature = asicsSignatures[indexPath.row] let containerExtension: String = URL(fileURLWithPath: containerPath).pathExtension @@ -592,7 +584,7 @@ extension ContainerViewController : UITableViewDataSource { var tapGesture: UITapGestureRecognizer? if isAsicsContainer() && !asicsDataFiles.isEmpty && asicsDataFiles.count >= indexPath.row { - dataFileName = asicsDataFiles[indexPath.row].fileName ?? unnamedDataFile + dataFileName = asicsDataFiles[indexPath.row].fileName tapGesture = getPreviewTapGesture(dataFile: dataFileName, containerPath: asicsNestedContainerPath, isShareButtonNeeded: isDecrypted) } else { dataFileName = containerViewDelegate.getDataFileDisplayName(index: indexPath.row) ?? unnamedDataFile @@ -674,7 +666,7 @@ extension ContainerViewController : UITableViewDataSource { cell.delegate = self let isStatePreviewOrOpened = state == .opened || state == .preview let isRemoveButtonHidden = !isAsicContainer && isStatePreviewOrOpened - cell.populate(addressee: cryptoContainerViewDelegate.getAddressee(index: indexPath.row) as! Addressee, + cell.populate(addressee: cryptoContainerViewDelegate.getAddressee(index: indexPath.row), index: row, showRemoveButton: !isRemoveButtonHidden) cell.accessibilityUserInputLabels = [""] @@ -690,9 +682,9 @@ extension ContainerViewController : UITableViewDataSource { case .containerTimestamps: let cell = tableView.dequeueReusableCell(withType: ContainerSignatureCell.self, for: indexPath)! cell.accessibilityUserInputLabels = ["\(L(.voiceControlContainerTimestamp)) \(row + 1)"] - var timestampToken: MoppLibSignature = MoppLibSignature() + var timestampToken = MoppLibSignature() if signingContainerViewDelegate.getTimestampTokensCount() >= indexPath.row { - timestampToken = signingContainerViewDelegate.getTimestampToken(index: indexPath.row) as? MoppLibSignature ?? MoppLibSignature() + timestampToken = signingContainerViewDelegate.getTimestampToken(index: indexPath.row) ?? MoppLibSignature() if (containerViewDelegate.getDataFileCount() == 1 && isSendingToSivaAgreed && !isLoadingNestedAsicsDone && !MimeTypeExtractor.isCadesContainer(filePath: URL(fileURLWithPath: containerViewDelegate.getContainerPath()))) { @@ -700,7 +692,7 @@ extension ContainerViewController : UITableViewDataSource { let dataFile = containerViewDelegate.getDataFileDisplayName(index: 0) ?? "" let containerFilePath = containerViewDelegate.getContainerPath() let destinationPath = MoppFileManager.shared.tempFilePath(withFileName: dataFile) - self.openNestedContainer(containerFilePath: containerFilePath, dataFile: dataFile, destinationPath: destinationPath) + self.openNestedContainer(containerFilePath: containerFilePath, dataFile: dataFile, destinationPath: destinationPath ?? "") } else if (!isLoadingNestedAsicsDone) { cell.populate( with: timestampToken, @@ -746,22 +738,18 @@ extension ContainerViewController : UITableViewDataSource { tableView.scrollToRow(at: indexPath, at: .bottom, animated: true) } - private func openNestedContainer(containerFilePath: String, dataFile: String, destinationPath: String?) { + private func openNestedContainer(containerFilePath: String, dataFile: String, destinationPath: String) { MoppLibContainerActions.sharedInstance().container(containerFilePath, saveDataFile: dataFile, to: destinationPath) { MoppLibContainerActions.sharedInstance().openContainer(withPath: destinationPath) { container in - if let signatures = container?.signatures { - for signature in signatures { - self.asicsSignatures.append(signature as? MoppLibSignature ?? MoppLibSignature()) - } + for signature in container.signatures { + self.asicsSignatures.append(signature) } - if let dataFiles = container?.dataFiles { - for dataFile in dataFiles { - self.asicsDataFiles.append(dataFile as? MoppLibDataFile ?? MoppLibDataFile()) - } + for dataFile in container.dataFiles { + self.asicsDataFiles.append(dataFile) } - self.asicsNestedContainerPath = destinationPath ?? "" + self.asicsNestedContainerPath = destinationPath self.isLoadingNestedAsicsDone = true @@ -772,7 +760,7 @@ extension ContainerViewController : UITableViewDataSource { return } - if nsError.code == 10027 { + if nsError.code == MoppLibErrorCode.moppLibErrorSslHandshakeFailed.rawValue { let alert = AlertUtil.messageAlert(message: L(.sslHandshakeMessage), alertAction: nil) self.navigationController?.popViewController(animated: true) self.navigationController?.viewControllers.last!.present(alert, animated: true) @@ -786,9 +774,9 @@ extension ContainerViewController : UITableViewDataSource { } } failure: { error in - printLog("Unable to get file from container \(error?.localizedDescription ?? "Unable to get error description")") + printLog("Unable to get file from container \(error.localizedDescription)") let nserror = error as NSError? - if nserror != nil && nserror?.code == Int(MoppLibErrorCode.moppLibErrorNoInternetConnection.rawValue) { + if nserror != nil && nserror?.code == MoppLibErrorCode.moppLibErrorNoInternetConnection.rawValue { let pathExtension = URL(string: containerFilePath)?.pathExtension let asicContainer: MoppLibContainer? = self.containerViewDelegate?.getContainer() if (pathExtension == "asics" || pathExtension == "scs") && !ContainerViewController.isXades(signatures: asicContainer?.signatures ?? []) { @@ -813,8 +801,10 @@ extension ContainerViewController : UITableViewDataSource { } func isRoleDetailsEmpty(signatureIndex: Int) -> Bool { - let roleDetails = getRoleDetails(signatureIndex: signatureIndex) - return roleDetails?.roles.isEmpty ?? true && roleDetails?.city.isNilOrEmpty ?? true && roleDetails?.state.isNilOrEmpty ?? true && roleDetails?.country.isNilOrEmpty ?? true && roleDetails?.zip.isNilOrEmpty ?? true + if let roleDetails = getRoleDetails(signatureIndex: signatureIndex) { + return roleDetails.roles.isEmpty && roleDetails.city.isEmpty && roleDetails.state.isEmpty && roleDetails.country.isEmpty && roleDetails.zip.isEmpty + } + return true } @objc private func openPreview(_ sender: PreviewFileTapGestureRecognizer) { @@ -858,10 +848,9 @@ extension ContainerViewController : ContainerFileDelegate { extension ContainerViewController : ContainerHeaderDelegate { private func asicContainerExists(container: MoppLibContainer?) -> Bool { - guard let signingContainer: MoppLibContainer = container, - let signingContainerFilePath = signingContainer.filePath, - !(signingContainerFilePath as String).isEmpty, - URL(fileURLWithPath: signingContainerFilePath).pathExtension != ContainerFormatCdoc else { + guard let signingContainer = container, + !signingContainer.filePath.isEmpty, + !URL(fileURLWithPath: signingContainer.filePath).pathExtension.isCryptoContainerExtension else { return false } @@ -869,10 +858,9 @@ extension ContainerViewController : ContainerHeaderDelegate { } private func cdocContainerExists(container: CryptoContainer?) -> Bool { - guard let cryptoContainer: CryptoContainer = container, - let cryptoContainerFilePath = cryptoContainer.filePath, - !(cryptoContainerFilePath as String).isEmpty, - URL(fileURLWithPath: cryptoContainerFilePath as String).pathExtension == ContainerFormatCdoc else { + guard let cryptoContainer = container, + !cryptoContainer.filePath.isEmpty, + URL(fileURLWithPath: cryptoContainer.filePath).pathExtension.isCryptoContainerExtension else { return false } @@ -931,7 +919,7 @@ extension ContainerViewController : ContainerHeaderDelegate { return } - let isContainerCdoc: Bool = containerExtension == ContainerFormatCdoc + let isContainerCdoc: Bool = containerExtension.isCryptoContainerExtension guard let newContainerPath: URL = self.getNewContainerUrlPath(isContainerCdoc: isContainerCdoc, asicContainer: asicContainer, cdocContainer: cdocContainer, newContainerName: textFieldText, containerExtension: containerExtension), newContainerPath.isFileURL else { printLog("Failed to get container path") @@ -961,8 +949,8 @@ extension ContainerViewController : ContainerHeaderDelegate { self.infoAlert(message: L(.containerErrorMessageFailedContainerNameChange)) return } - cryptoContainer.filename = newContainerPath.lastPathComponent as NSString - cryptoContainer.filePath = newContainerPath.path as NSString + cryptoContainer.filename = newContainerPath.lastPathComponent + cryptoContainer.filePath = newContainerPath.path } printLog("File renaming successful") @@ -1169,11 +1157,11 @@ extension ContainerViewController : UITableViewDelegate { if !asicsSignatures.isEmpty && asicsSignatures.indices.contains(indexPathRow) { return asicsSignatures[indexPathRow] } - return signingContainerViewDelegate.getSignature(index: indexPathRow) as? MoppLibSignature + return signingContainerViewDelegate.getSignature(index: indexPathRow) } private func getTimestampToken(indexPathRow: Int) -> MoppLibSignature? { - return signingContainerViewDelegate.getTimestampToken(index: indexPathRow) as? MoppLibSignature + return signingContainerViewDelegate.getTimestampToken(index: indexPathRow) } private func isCades() -> Bool { diff --git a/MoppApp/MoppApp/CryptoActions.swift b/MoppApp/MoppApp/CryptoActions.swift index dd535ceb9..93199c80e 100644 --- a/MoppApp/MoppApp/CryptoActions.swift +++ b/MoppApp/MoppApp/CryptoActions.swift @@ -20,8 +20,8 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ + import Foundation -import CryptoLib protocol CryptoActions { func startEncryptingProcess() @@ -31,36 +31,31 @@ protocol CryptoActions { extension CryptoActions where Self: CryptoContainerViewController { func startEncryptingProcess() { - if container.addressees.count > 0 { - MoppLibCryptoActions.sharedInstance().encryptData( - container.filePath as String?, - withDataFiles: container.dataFiles as? [Any], - withAddressees: container.addressees, - success: { - self.isCreated = false - self.isForPreview = false - self.isContainerEncrypted = true - self.state = .loading - self.containerViewDelegate.openContainer(afterSignatureCreated: true) - UIAccessibility.post(notification: UIAccessibility.Notification.screenChanged, argument: L(.cryptoEncryptionSuccess)) - let encryptionSuccess = NotificationMessage(isSuccess: true, text: L(.cryptoEncryptionSuccess)) - if !self.notifications.contains(where: { $0 == encryptionSuccess }) { - self.notifications.append(encryptionSuccess) - } - self.reloadCryptoData() + guard container.addressees.count > 0 else { + return self.infoAlert(message: L(.cryptoNoAddresseesWarning)) + } + Encrypt.encryptFile(container.filePath, + with: container.dataFiles, + with: container.addressees, + success: { + self.isCreated = false + self.isForPreview = false + self.isContainerEncrypted = true + self.state = .loading + self.containerViewDelegate.openContainer(afterSignatureCreated: true) + UIAccessibility.post(notification: UIAccessibility.Notification.screenChanged, argument: L(.cryptoEncryptionSuccess)) + let encryptionSuccess = NotificationMessage(isSuccess: true, text: L(.cryptoEncryptionSuccess)) + if !self.notifications.contains(where: { $0 == encryptionSuccess }) { + self.notifications.append(encryptionSuccess) + } + self.reloadCryptoData() - MoppFileManager.removeFiles() - + MoppFileManager.removeFiles() }, - failure: { _ in - DispatchQueue.main.async { - self.infoAlert(message: L(.cryptoEncryptionErrorText)) - } - } - ) - } else { - self.infoAlert(message: L(.cryptoNoAddresseesWarning)) - } + failure: { + self.infoAlert(message: L(.cryptoEncryptionErrorText)) + } + ) } func startDecryptingProcess() { let decryptSelectionVC = UIStoryboard.tokenFlow.instantiateViewController(of: TokenFlowSelectionViewController.self) @@ -75,21 +70,18 @@ extension CryptoActions where Self: CryptoContainerViewController { extension CryptoContainerViewController : IdCardDecryptViewControllerDelegate { - func idCardDecryptDidFinished(cancelled: Bool, success: Bool, dataFiles: NSMutableDictionary, error: Error?) { + func idCardDecryptDidFinished(cancelled: Bool, success: Bool, dataFiles: [String: Data], error: Error?) { if !cancelled { if success { - container.dataFiles.removeAllObjects() + container.dataFiles.removeAll() for dataFile in dataFiles { - let cryptoDataFile = CryptoDataFile() - cryptoDataFile.filename = dataFile.key as? String - guard let destinationPath = MoppFileManager.shared.tempFilePath(withFileName: cryptoDataFile.filename) else { + guard let destinationPath = MoppFileManager.shared.tempFilePath(withFileName: dataFile.key) else { dismiss(animated: false) infoAlert(message: L(.decryptionErrorMessage)) return } - cryptoDataFile.filePath = destinationPath - container.dataFiles.add(cryptoDataFile) - MoppFileManager.shared.createFile(atPath: destinationPath, contents: dataFile.value as! Data) + container.dataFiles.append(CryptoDataFile(filename: dataFile.key, filePath: destinationPath)) + MoppFileManager.shared.createFile(atPath: destinationPath, contents: dataFile.value) } self.isCreated = false @@ -108,7 +100,7 @@ extension CryptoContainerViewController : IdCardDecryptViewControllerDelegate { } else { self.dismiss(animated: false) guard let nsError = error as NSError? else { return } - if nsError.code == Int(MoppLibErrorCode.moppLibErrorPinBlocked.rawValue) { + if nsError.code == MoppLibErrorCode.moppLibErrorPinBlocked.rawValue { errorAlertWithLink(message: L(.pin1BlockedAlert)) } else { infoAlert(message: L(.decryptionErrorMessage)) diff --git a/MoppApp/MoppApp/CryptoContainer.swift b/MoppApp/MoppApp/CryptoContainer.swift index 067be9355..7770f8c94 100644 --- a/MoppApp/MoppApp/CryptoContainer.swift +++ b/MoppApp/MoppApp/CryptoContainer.swift @@ -21,20 +21,18 @@ * */ -import Foundation -import CryptoLib - class CryptoContainer { - - var filename: NSString! - var filePath: NSString! - var dataFiles: NSMutableArray = [] - var addressees: [Addressee] = [] - - init(filename: NSString, filePath: NSString){ + + var filename: String + var filePath: String + var dataFiles: [CryptoDataFile] + var addressees: [Addressee] + + init(filename: String, filePath: String, cdocInfo: CdocInfo? = nil) { self.filename = filename self.filePath = filePath + self.dataFiles = cdocInfo?.dataFiles ?? [] + self.addressees = cdocInfo?.addressees ?? [] } - } diff --git a/MoppApp/MoppApp/CryptoContainerViewController.swift b/MoppApp/MoppApp/CryptoContainerViewController.swift index 5c6d40cb0..e44cc11d7 100644 --- a/MoppApp/MoppApp/CryptoContainerViewController.swift +++ b/MoppApp/MoppApp/CryptoContainerViewController.swift @@ -21,9 +21,6 @@ * */ -import UIKit -import CryptoLib - class CryptoContainerViewController : ContainerViewController, CryptoActions { var container: CryptoContainer! @@ -84,7 +81,7 @@ extension CryptoContainerViewController : CryptoContainerViewControllerDelegate reloadCryptoData() } - func getAddressee(index: Int) -> Any { + func getAddressee(index: Int) -> Addressee { return container.addressees[index] } @@ -113,7 +110,7 @@ extension CryptoContainerViewController : AddresseeViewControllerDelegate { extension CryptoContainerViewController : ContainerViewControllerDelegate { func removeDataFile(index: Int) { - let containerFileCount: Int = self.getContainer().dataFiles.count + let containerFileCount: Int = (self.getContainer() as CryptoContainer).dataFiles.count guard containerFileCount > 0 else { printLog("No files in container") self.infoAlert(message: "File not found in container") @@ -151,7 +148,7 @@ extension CryptoContainerViewController : ContainerViewControllerDelegate { strongSelf.updateState(.loading) strongSelf.updateState((self?.isCreated)! ? .created : .opened) if strongSelf.container.dataFiles.count > index { - strongSelf.container.dataFiles.removeObject(at: index) + strongSelf.container.dataFiles.remove(at: index) } else { self?.infoAlert(message: L(.dataFileRemovalFailed)) return @@ -188,13 +185,11 @@ extension CryptoContainerViewController : ContainerViewControllerDelegate { } func getDataFileDisplayName(index: Int) -> String? { - guard let dataFile = (container.dataFiles[index] as? CryptoDataFile) else { - return nil - } + let dataFile = container.dataFiles[index] if dataFile.filePath == nil { return dataFile.filename } - return (dataFile.filePath as NSString).lastPathComponent + return (dataFile.filePath! as NSString).lastPathComponent } func getContainer() -> MoppLibContainer { @@ -214,28 +209,14 @@ extension CryptoContainerViewController : ContainerViewControllerDelegate { if state != .loading { return } if container == nil { let filePath = containerPath as NSString - let container = CryptoContainer(filename: filePath.lastPathComponent as NSString, filePath: filePath) - MoppLibCryptoActions.sharedInstance().parseCdocInfo( - filePath as String?, - success: {(_ cdocInfo: CdocInfo?) -> Void in - guard let strongCdocInfo = cdocInfo else { return } - - container.addressees = strongCdocInfo.addressees as? [Addressee] ?? [] - container.dataFiles = strongCdocInfo.dataFiles - self.containerPath = filePath as String? - self.state = .opened - - self.container = container - self.isDecrypted = false - self.reloadCryptoData() - }, - failure: { _ in - DispatchQueue.main.async { - self.infoAlert(message: L(.fileImportOpenExistingFailedAlertMessage, [filePath.lastPathComponent])) - } - } - ) - + Decrypt.parseCdocInfo(withFullPath: filePath as String) { cdocInfo in + guard let strongCdocInfo = cdocInfo else { return self.infoAlert(message: L(.fileImportOpenExistingFailedAlertMessage, [filePath.lastPathComponent])) } + self.containerPath = filePath as String + self.state = .opened + self.container = CryptoContainer(filename: filePath.lastPathComponent, filePath: filePath as String, cdocInfo: strongCdocInfo) + self.isDecrypted = false + self.reloadCryptoData() + } } self.notifications = [] self.updateState(self.isCreated ? .created : .opened) @@ -246,7 +227,7 @@ extension CryptoContainerViewController : ContainerViewControllerDelegate { } func getDataFileRelativePath(index: Int) -> String { - return (container.dataFiles[index] as! CryptoDataFile).filename! as String + return container.dataFiles[index].filename } func isContainerEmpty() -> Bool { diff --git a/MoppApp/MoppApp/DefaultsHelper.swift b/MoppApp/MoppApp/DefaultsHelper.swift index fdcd7fcb8..5d30b92b8 100644 --- a/MoppApp/MoppApp/DefaultsHelper.swift +++ b/MoppApp/MoppApp/DefaultsHelper.swift @@ -23,6 +23,7 @@ import Foundation import SkSigningLib +import MoppUI let ContainerFormatAdoc = "adoc" let ContainerFormatBdoc = "bdoc" @@ -34,6 +35,7 @@ let ContainerFormatAsics = "asics" let ContainerFormatAsicsShort = "scs" let ContainerFormatPDF = "pdf" let ContainerFormatCdoc = "cdoc" +let ContainerFormatCdoc2 = "cdoc2" let ContainerFormatP12d = "p12d" let FileFormatXml = "xml" @@ -390,4 +392,13 @@ class DefaultsHelper return UserDefaults.standard.bool(forKey: kNfcShowCanMessage) } } + + class var useCDoc2Encryption: Bool { + set { + UserDefaults.standard.set(newValue, forKey: kUseCDoc2Encryption) + } + get { + return UserDefaults.standard.bool(forKey: kUseCDoc2Encryption) + } + } } diff --git a/MoppApp/MoppApp/DiagnosticsViewController.swift b/MoppApp/MoppApp/DiagnosticsViewController.swift index bd87a182f..4a4796a6e 100644 --- a/MoppApp/MoppApp/DiagnosticsViewController.swift +++ b/MoppApp/MoppApp/DiagnosticsViewController.swift @@ -142,7 +142,7 @@ class DiagnosticsViewController: MoppViewController, UIDocumentPickerDelegate { appVersionLabel.text = "\(L(.diagnosticsAppVersion)): \(MoppApp.versionString)" opSysVersionLabel.text = "\(L(.diagnosticsIosVersion)): iOS \(MoppApp.iosVersion)" librariesTitleLabel.text = L(.diagnosticsLibrariesLabel) - let libdigidocppVersion = MoppLibManager.sharedInstance().libdigidocppVersion() ?? String() + let libdigidocppVersion = MoppLibContainerActions.libdigidocppVersion() ?? String() librariesLabel.text = "libdigidocpp \(libdigidocppVersion)" tslCacheLabel.text = L(.diagnosticsTslCacheLabel) centralConfigurationLabel.text = L(.centralConfigurationLabel) diff --git a/MoppApp/MoppApp/Extensions/String+Additions.swift b/MoppApp/MoppApp/Extensions/String+Additions.swift index 070d080b4..a0c9a0803 100644 --- a/MoppApp/MoppApp/Extensions/String+Additions.swift +++ b/MoppApp/MoppApp/Extensions/String+Additions.swift @@ -77,11 +77,12 @@ extension String { var isPdfContainerExtension: Bool { return self.lowercased() == ContainerFormatPDF } - - var isCdocContainerExtension: Bool { - return self.lowercased() == ContainerFormatCdoc + + var isCryptoContainerExtension: Bool { + return caseInsensitiveCompare(ContainerFormatCdoc) == .orderedSame || + caseInsensitiveCompare(ContainerFormatCdoc2) == .orderedSame } - + var isXmlFileExtension: Bool { return self.lowercased() == FileFormatXml } @@ -219,9 +220,25 @@ extension String { } func sanitize() -> String { - let normalizedName = FileUtil.getFileName(currentFileName: self) - return MoppLibManager.sanitize(normalizedName) + var normalizedName = FileUtil.getFileName(currentFileName: self) .removeForbiddenCharacters().trimWhitespacesAndNewlines() + + var characterSet = CharacterSet.illegalCharacters + characterSet.insert(charactersIn: "@%:^?[]'\"”’{}#&`\\~«»/´") + let rtlChars = ["\u{200E}", "\u{200F}", "\u{202E}", "\u{202A}", "\u{202B}"] + for rtlChar in rtlChars { + characterSet.insert(charactersIn: rtlChar) + } + + while normalizedName.hasPrefix(".") { + if normalizedName.count > 1 { + normalizedName.removeFirst() + } else { + normalizedName = normalizedName.replacingOccurrences(of: ".", with: "_") + } + } + + return normalizedName.components(separatedBy: characterSet).joined() } func lowercasedStart() -> String { @@ -234,9 +251,6 @@ extension String { extension Optional where Wrapped == String { var isNilOrEmpty:Bool { - if let value = self, !value.isEmpty { - return false - } - return true + return self?.isEmpty ?? true } } diff --git a/MoppApp/MoppApp/FileManager.swift b/MoppApp/MoppApp/FileManager.swift index 274eff456..87e6ed736 100644 --- a/MoppApp/MoppApp/FileManager.swift +++ b/MoppApp/MoppApp/FileManager.swift @@ -276,7 +276,7 @@ class MoppFileManager { completionHandler(true, saveTempFileToLocation) return }, failure: { (error) in - printLog("Failed to save file. Error: \(error?.localizedDescription ?? "No error to display")") + printLog("Failed to save file. Error: \(error.localizedDescription)") completionHandler(false, nil) return }) diff --git a/MoppApp/MoppApp/IDCardSignature.swift b/MoppApp/MoppApp/IDCardSignature.swift index 10a9be002..0e296cb54 100644 --- a/MoppApp/MoppApp/IDCardSignature.swift +++ b/MoppApp/MoppApp/IDCardSignature.swift @@ -29,7 +29,7 @@ class IDCardSignature { func createIDCardSignature(idCardParameters: IDCardParameters?, completionHandler: @escaping (Result) -> Void) { MoppLibContainerActions.sharedInstance().addSignature(idCardParameters?.containerPath, withPin2:idCardParameters?.pin2, roleData: idCardParameters?.roleData, success: { container in - completionHandler(.success(container!)) + completionHandler(.success(container)) }, failure: { error in guard let nsError = error as NSError? else { return } completionHandler(.failure(nsError)) diff --git a/MoppApp/MoppApp/IdCardViewController.swift b/MoppApp/MoppApp/IdCardViewController.swift index 206f7a5b6..bb59dbef1 100644 --- a/MoppApp/MoppApp/IdCardViewController.swift +++ b/MoppApp/MoppApp/IdCardViewController.swift @@ -34,7 +34,7 @@ protocol IdCardSignViewControllerDelegate : AnyObject { } protocol IdCardDecryptViewControllerDelegate : AnyObject { - func idCardDecryptDidFinished(cancelled: Bool, success: Bool, dataFiles: NSMutableDictionary, error: Error?) + func idCardDecryptDidFinished(cancelled: Bool, success: Bool, dataFiles: [String: Data], error: Error?) } class IdCardViewController : MoppViewController, TokenFlowSigning { @@ -291,7 +291,7 @@ class IdCardViewController : MoppViewController, TokenFlowSigning { case .readyForTokenAction: // Give VoiceOver time to announce "ID-card found" DispatchQueue.main.asyncAfter(deadline: .now() + 2.5) { - let fullname = self.idCardPersonalData?.fullName() ?? String() + let fullname = self.idCardPersonalData?.fullName ?? String() let personalCode = self.idCardPersonalData?.personalIdentificationCode ?? String() if self.isActionDecryption { self.titleLabel.text = L(.cardReaderStateReadyForPin1, [fullname, personalCode]) @@ -340,7 +340,7 @@ class IdCardViewController : MoppViewController, TokenFlowSigning { UIAccessibility.post(notification: UIAccessibility.Notification.layoutChanged, argument: titleLabel) } case .wrongPin: - let fullname = idCardPersonalData?.fullName() ?? String() + let fullname = idCardPersonalData?.fullName ?? String() let personalCode = idCardPersonalData?.personalIdentificationCode ?? String() if isActionDecryption { titleLabel.text = L(.cardReaderStateReadyForPin1, [fullname, personalCode]) @@ -437,47 +437,39 @@ class IdCardViewController : MoppViewController, TokenFlowSigning { state = .tokenActionInProcess if isActionDecryption { - MoppLibCryptoActions.sharedInstance().decryptData(containerPath, withPin1: pin, - success: {(_ decryptedData: NSMutableDictionary?) -> Void in - guard let strongDecryptedData = decryptedData else { return } - self.decryptDelegate?.idCardDecryptDidFinished(cancelled: false, success: true, dataFiles: strongDecryptedData, error: nil) - }, - failure: { [weak self] error in - guard let nsError = error as NSError? else { return } - if nsError.code == Int(MoppLibErrorCode.moppLibErrorWrongPin.rawValue) { // Wrong PIN1 error - DispatchQueue.main.async { - self?.pinAttemptsLeft = (nsError.userInfo[kMoppLibUserInfoRetryCount] as? NSNumber)?.uintValue ?? 0 - self?.state = .wrongPin - } + Task { + do { + let decryptedData = try await MoppLibCryptoActions.decryptData(fullPath: containerPath, pin1: pin) + self.decryptDelegate?.idCardDecryptDidFinished(cancelled: false, success: true, dataFiles: decryptedData, error: nil) + } catch { + if let nsError = error as NSError?, + nsError.code == MoppLibErrorCode.moppLibErrorWrongPin.rawValue { // Wrong PIN1 error + self.pinAttemptsLeft = (nsError.userInfo[MoppLibError.kMoppLibUserInfoRetryCount] as? NSNumber)?.uintValue ?? 0 + self.state = .wrongPin } else { - DispatchQueue.main.async { - self?.dismiss(animated: false, completion: { - self?.decryptDelegate?.idCardDecryptDidFinished(cancelled: false, success: false, dataFiles: NSMutableDictionary(), error: error) - }) - } + self.dismiss(animated: false, completion: { + self.decryptDelegate?.idCardDecryptDidFinished(cancelled: false, success: false, dataFiles: [:], error: error) + }) } } - ) - + } + } else if DefaultsHelper.isRoleAndAddressEnabled { + let roleAndAddressView = UIStoryboard.tokenFlow.instantiateViewController(of: RoleAndAddressViewController.self) + roleAndAddressView.modalPresentationStyle = .overCurrentContext + roleAndAddressView.modalTransitionStyle = .crossDissolve + roleAndAddressView.viewController = self + if !savePin(pin: pin) { + showPinSaveError() + return + } + present(roleAndAddressView, animated: true) } else { - if DefaultsHelper.isRoleAndAddressEnabled { - let roleAndAddressView = UIStoryboard.tokenFlow.instantiateViewController(of: RoleAndAddressViewController.self) - roleAndAddressView.modalPresentationStyle = .overCurrentContext - roleAndAddressView.modalTransitionStyle = .crossDissolve - roleAndAddressView.viewController = self - if !savePin(pin: pin) { - showPinSaveError() - return - } - present(roleAndAddressView, animated: true) - } else { - if !savePin(pin: pin) { - showPinSaveError() - return - } - - self.sign(pin) + if !savePin(pin: pin) { + showPinSaveError() + return } + + self.sign(pin) } } @@ -506,9 +498,9 @@ class IdCardViewController : MoppViewController, TokenFlowSigning { }) } case .failure(let error): - if error.code == Int(MoppLibErrorCode.moppLibErrorWrongPin.rawValue) { // Wrong PIN2 error + if error.code == MoppLibErrorCode.moppLibErrorWrongPin.rawValue { DispatchQueue.main.async { - self?.pinAttemptsLeft = (error.userInfo[kMoppLibUserInfoRetryCount] as? NSNumber)?.uintValue ?? 0 + self?.pinAttemptsLeft = (error.userInfo[MoppLibError.kMoppLibUserInfoRetryCount] as? NSNumber)?.uintValue ?? 0 self?.state = .wrongPin } } else { @@ -579,7 +571,7 @@ extension IdCardViewController : MoppLibCardReaderManagerDelegate { }, failure: { [weak self] error in DispatchQueue.main.async { guard let error = error as NSError? else { self?.state = .readerProcessFailed; return } - if error.code == 10026 { + if error.code == MoppLibErrorCode.moppLibErrorReaderProcessFailed.rawValue { self?.state = .readerProcessFailed return } diff --git a/MoppApp/MoppApp/Info.plist b/MoppApp/MoppApp/Info.plist index 7fc47a80f..4e9e42c54 100644 --- a/MoppApp/MoppApp/Info.plist +++ b/MoppApp/MoppApp/Info.plist @@ -3,7 +3,7 @@ CFBundleDevelopmentRegion - en + $(DEVELOPMENT_LANGUAGE) CFBundleDisplayName RIA DigiDoc CFBundleDocumentTypes @@ -83,6 +83,21 @@ ee.ria.digidoc-cdoc + + CFBundleIconFiles + + digidoc_76.png + digidoc_1024.png + + CFBundleTypeName + DigiDoc file cdoc2 + LSHandlerRank + Owner + LSItemContentTypes + + ee.ria.digidoc-cdoc2 + + CFBundleIconFiles @@ -183,6 +198,21 @@ public.data + + CFBundleIconFiles + + digidoc_76.png + digidoc_1024.png + + CFBundleTypeName + DigiDoc file cdoc2 + LSHandlerRank + Owner + LSItemContentTypes + + ee.ria.digidoc-cdoc2 + + CFBundleExecutable $(EXECUTABLE_NAME) @@ -219,8 +249,6 @@ LSSupportsOpeningDocumentsInPlace - NFCReaderUsageDescription - This app uses NFC to scan ID-cards NSAppTransportSecurity NSExceptionDomains @@ -237,6 +265,8 @@ + NFCReaderUsageDescription + This app uses NFC to scan ID-cards NSBluetoothAlwaysUsageDescription Bluetooth card reader is used to read data from ID card NSBluetoothPeripheralUsageDescription @@ -271,7 +301,7 @@ LaunchScreen UIRequiredDeviceCapabilities - armv7 + arm64 UIStatusBarStyle UIStatusBarStyleDarkContent @@ -439,6 +469,35 @@ + + CFBundleIconFiles + + digidoc_76.png + digidoc_1024.png + + UTTypeConformsTo + + public.data + + UTTypeDescription + DigiDoc Container cdoc2 + UTTypeIconFiles + + UTTypeIdentifier + ee.ria.digidoc-cdoc2 + UTTypeTagSpecification + + public.filename-extension + + cdoc2 + CDOC2 + + public.mime-type + + application/x-cdoc2 + + + CFBundleIconFiles @@ -669,6 +728,35 @@ + + CFBundleIconFiles + + digidoc_76.png + digidoc_1024.png + + UTTypeConformsTo + + public.data + + UTTypeDescription + DigiDoc Container cdoc2 + UTTypeIconFiles + + UTTypeIdentifier + ee.ria.digidoc-cdoc2 + UTTypeTagSpecification + + public.filename-extension + + cdoc2 + CDOC2 + + public.mime-type + + application/x-cdoc2 + + + UTImportedTypeDeclarations @@ -768,6 +856,36 @@ + + CFBundleIconFiles + + digidoc_76.png + digidoc_1024.png + + UTTypeConformsTo + + public.data + public.cdoc2 + + UTTypeDescription + Digidoc Container cdoc2 + UTTypeIconFiles + + UTTypeIdentifier + ee.ria.digidoc + UTTypeTagSpecification + + public.filename-extension + + cdoc2 + CDOC2 + + public.mime-type + + application/x-cdoc2 + + + CFBundleIconFiles @@ -1021,6 +1139,36 @@ + + CFBundleIconFiles + + digidoc_76.png + digidoc_1024.png + + UTTypeConformsTo + + public.data + public.cdoc2 + + UTTypeDescription + Digidoc Container cdoc2 + UTTypeIconFiles + + UTTypeIdentifier + ee.ria.digidoc + UTTypeTagSpecification + + public.filename-extension + + cdoc2 + CDOC2 + + public.mime-type + + application/x-cdoc2 + + + com.apple.developer.nfc.readersession.iso7816.select-identifiers diff --git a/MoppApp/MoppApp/InitializationViewController.swift b/MoppApp/MoppApp/InitializationViewController.swift index e17e9010b..5d2207c88 100644 --- a/MoppApp/MoppApp/InitializationViewController.swift +++ b/MoppApp/MoppApp/InitializationViewController.swift @@ -32,14 +32,7 @@ class InitializationViewController : UIViewController { override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) - -#if USE_TEST_DDS - let useTestDDS = true -#else - let useTestDDS = false -#endif - - MoppLibManager.sharedInstance().setup(success: { + MoppLibContainerActions.setup(success: { DispatchQueue.main.async { MoppApp.instance.setupTabController() } @@ -49,8 +42,7 @@ class InitializationViewController : UIViewController { MoppApp.instance.setupTabController() } }, - usingTestDigiDocService: useTestDDS, - andTSUrl: DefaultsHelper.timestampUrl ?? MoppConfiguration.getMoppLibConfiguration().tsaurl, + andTSUrl: DefaultsHelper.timestampUrl ?? MoppConfiguration.getMoppLibConfiguration().tsaURL, withMoppConfiguration: MoppConfiguration.getMoppLibConfiguration(), andProxyConfiguration: ManualProxy.getMoppLibProxyConfiguration() ) diff --git a/MoppApp/MoppApp/ManualProxy.swift b/MoppApp/MoppApp/ManualProxy.swift index b38dd78b4..1d5205673 100644 --- a/MoppApp/MoppApp/ManualProxy.swift +++ b/MoppApp/MoppApp/ManualProxy.swift @@ -40,8 +40,8 @@ public class ManualProxy { let manualProxy = ManualProxy.getManualProxyConfiguration() if manualProxy.setting == .systemProxy { let systemProxySettings = ProxyUtil.getSystemProxySettings() - return MoppLibProxyConfiguration(configuration: systemProxySettings.setting.rawValue, host: systemProxySettings.host, port: NSNumber(value: systemProxySettings.port), username: systemProxySettings.username, password: systemProxySettings.password) + return MoppLibProxyConfiguration(username: systemProxySettings.username, password: systemProxySettings.password) } - return MoppLibProxyConfiguration(configuration: manualProxy.setting.rawValue, host: manualProxy.host, port: NSNumber(value: manualProxy.port), username: manualProxy.username, password: manualProxy.password) + return MoppLibProxyConfiguration(username: manualProxy.username, password: manualProxy.password) } } diff --git a/MoppApp/MoppApp/MimeTypeExtractor.swift b/MoppApp/MoppApp/MimeTypeExtractor.swift index 7e93b7659..3b2403ed7 100644 --- a/MoppApp/MoppApp/MimeTypeExtractor.swift +++ b/MoppApp/MoppApp/MimeTypeExtractor.swift @@ -255,7 +255,7 @@ class MimeTypeExtractor { var isCdoc: Bool = false MimeTypeDecoder().getMimeType(fileString: fileDataAscii ?? "") { (containerExtension) in - if containerExtension == ContainerFormatCdoc { + if containerExtension.isCryptoContainerExtension { isCdoc = true } } diff --git a/MoppApp/MoppApp/MobileIDSignature.swift b/MoppApp/MoppApp/MobileIDSignature.swift index 3f24c8ca7..d3cad0a70 100644 --- a/MoppApp/MoppApp/MobileIDSignature.swift +++ b/MoppApp/MoppApp/MobileIDSignature.swift @@ -236,7 +236,7 @@ class MobileIDSignature { "\tCert: \(cert)\n" + "\tSignature value: \(signatureValue)\n" ) - MoppLibManager.isSignatureValid(cert, signatureValue: signatureValue, success: { (_) in + MoppLibContainerActions.isSignatureValid(cert, signatureValue: signatureValue, success: { printLog("\nRIA.MobileID - Successfully validated signature!\n") DispatchQueue.main.async { NotificationCenter.default.post( @@ -287,7 +287,7 @@ class MobileIDSignature { // MARK: Get hash private func getHash(cert: Data, containerPath: String, roleData: MoppLibRoleAddressData?) -> Data? { - guard let hash = MoppLibManager.prepareSignature(cert, containerPath: containerPath, roleData: roleData) else { + guard let hash = MoppLibContainerActions.prepareSignature(cert, containerPath: containerPath, roleData: roleData) else { printLog("RIA.MobileID - Failed to get hash:\n" + "\tCert: \(cert)\n" + "\tContainer path: \(containerPath)\n" diff --git a/MoppApp/MoppApp/MoppApp-Bridging-Header.h b/MoppApp/MoppApp/MoppApp-Bridging-Header.h index 236d6c23c..5f03c912b 100644 --- a/MoppApp/MoppApp/MoppApp-Bridging-Header.h +++ b/MoppApp/MoppApp/MoppApp-Bridging-Header.h @@ -3,5 +3,5 @@ // #import -#import +#import #import diff --git a/MoppApp/MoppApp/MoppApp.swift b/MoppApp/MoppApp/MoppApp.swift index 80757fed0..bdfdf0af1 100644 --- a/MoppApp/MoppApp/MoppApp.swift +++ b/MoppApp/MoppApp/MoppApp.swift @@ -383,7 +383,7 @@ class MoppApp: UIApplication, URLSessionDelegate, URLSessionDownloadDelegate { } } - if newUrl.pathExtension.isCdocContainerExtension && urls.count == 1 { + if newUrl.pathExtension.isCryptoContainerExtension && urls.count == 1 { landingViewController?.containerType = .cdoc } else { landingViewController?.containerType = .asic diff --git a/MoppApp/MoppApp/MyeIDChangeCodesViewController.swift b/MoppApp/MoppApp/MyeIDChangeCodesViewController.swift index f6017493f..07becf733 100644 --- a/MoppApp/MoppApp/MyeIDChangeCodesViewController.swift +++ b/MoppApp/MoppApp/MyeIDChangeCodesViewController.swift @@ -78,24 +78,13 @@ extension MyeIDChangeCodesViewController: MyeIDChangeCodesViewControllerUIDelega var errorMessage = L(.genericErrorMessage) if let nsError = error as NSError? { let actionType = strongSelf.model.actionType - var errorCode = nsError.code - - let retryCount = (nsError.userInfo[kMoppLibUserInfoRetryCount] as? NSNumber)?.intValue ?? 0 - if errorCode == MoppLibErrorCode.moppLibErrorWrongPin.rawValue && retryCount == 0 { - errorCode = MoppLibErrorCode.moppLibErrorPinBlocked.rawValue - } - + let errorCode = nsError.code + if errorCode == MoppLibErrorCode.moppLibErrorWrongPin.rawValue { - let retryCount = (nsError.userInfo[kMoppLibUserInfoRetryCount] as? NSNumber)?.intValue ?? 0 + let retryCount = (nsError.userInfo[MoppLibError.kMoppLibUserInfoRetryCount] as? NSNumber)?.intValue ?? 0 strongSelf.infoManager.retryCounts.setRetryCount(for: actionType, with: retryCount) - if retryCount == 1 { - errorMessage = L(.myEidWrongCodeMessageSingular, [actionType.codeDisplayNameForWrongOrBlocked]) - showErrorInline = true - } - else { - errorMessage = L(.myEidWrongCodeMessage, [actionType.codeDisplayNameForWrongOrBlocked]) - showErrorInline = true - } + errorMessage = L(retryCount == 1 ? .myEidWrongCodeMessageSingular : .myEidWrongCodeMessage, [actionType.codeDisplayNameForWrongOrBlocked]) + showErrorInline = true ui.setViewBorder(view: ui.firstCodeTextField) } else if errorCode == MoppLibErrorCode.moppLibErrorPinBlocked.rawValue { diff --git a/MoppApp/MoppApp/MyeIDInfoManager.swift b/MoppApp/MoppApp/MyeIDInfoManager.swift index 68429f0f8..ee24f237d 100644 --- a/MoppApp/MoppApp/MyeIDInfoManager.swift +++ b/MoppApp/MoppApp/MyeIDInfoManager.swift @@ -226,7 +226,7 @@ class MyeIDInfoManager { UIAccessibility.post(notification: UIAccessibility.Notification.screenChanged, argument: "") } - func organizationDisplayString(_ certOrganization: X509Certificate.CertType?) -> String { + func organizationDisplayString(_ certOrganization: CertType?) -> String { switch certOrganization { case .IDCardType: return L(.myEidInfoMyEidIdCard) diff --git a/MoppApp/MoppApp/MyeIDViewController.swift b/MoppApp/MoppApp/MyeIDViewController.swift index e3ce8f387..f155d8ad5 100644 --- a/MoppApp/MoppApp/MyeIDViewController.swift +++ b/MoppApp/MoppApp/MyeIDViewController.swift @@ -126,57 +126,24 @@ class MyeIDViewController : MoppViewController { extension MyeIDViewController: MoppLibCardReaderManagerDelegate { func moppLibCardReaderStatusDidChange(_ readerStatus: MoppLibCardReaderStatus) { + popChangeCodesViewControllerIfPushed() + var statusVC = children.first as? MyeIDStatusViewController + if statusVC == nil { + statusVC = showViewController(createStatusViewController()) as? MyeIDStatusViewController + } switch readerStatus { - case .Initial: - popChangeCodesViewControllerIfPushed() - var statusVC = children.first as? MyeIDStatusViewController - if statusVC == nil { - statusVC = showViewController(createStatusViewController()) as? MyeIDStatusViewController - } - statusVC?.state = .initial - case .ReaderNotConnected: - popChangeCodesViewControllerIfPushed() - var statusVC = children.first as? MyeIDStatusViewController - if statusVC == nil { - statusVC = showViewController(createStatusViewController()) as? MyeIDStatusViewController - } - statusVC?.state = .readerNotFound - case .ReaderRestarted: - popChangeCodesViewControllerIfPushed() - var statusVC = children.first as? MyeIDStatusViewController - if statusVC == nil { - statusVC = showViewController(createStatusViewController()) as? MyeIDStatusViewController - } - statusVC?.state = .readerRestarted - case .ReaderConnected: - popChangeCodesViewControllerIfPushed() - var statusVC = children.first as? MyeIDStatusViewController - if statusVC == nil { - statusVC = showViewController(createStatusViewController()) as? MyeIDStatusViewController - } - statusVC?.state = .idCardNotFound + case .Initial: statusVC?.state = .initial + case .ReaderNotConnected: statusVC?.state = .readerNotFound + case .ReaderRestarted: statusVC?.state = .readerRestarted + case .ReaderConnected: statusVC?.state = .idCardNotFound case .CardConnected: - popChangeCodesViewControllerIfPushed() - var statusVC = children.first as? MyeIDStatusViewController - if statusVC == nil { - statusVC = showViewController(createStatusViewController()) as? MyeIDStatusViewController - } statusVC?.state = .requestingData - // Give some time for status textfield to update before executing data requests DispatchQueue.main.asyncAfter(deadline: .now() + 0.1, execute: { [weak self] in guard let strongSelf = self else { return } strongSelf.infoManager.requestInformation(with: strongSelf) }) - case .ReaderProcessFailed: - popChangeCodesViewControllerIfPushed() - var statusVC = children.first as? MyeIDStatusViewController - if statusVC == nil { - statusVC = showViewController(createStatusViewController()) as? MyeIDStatusViewController - } - statusVC?.state = .readerProcessFailed - @unknown default: - break + case .ReaderProcessFailed: statusVC?.state = .readerProcessFailed } } } diff --git a/MoppApp/MoppApp/NFCSignature.swift b/MoppApp/MoppApp/NFCSignature.swift index 8cf7f108c..9d46315f6 100644 --- a/MoppApp/MoppApp/NFCSignature.swift +++ b/MoppApp/MoppApp/NFCSignature.swift @@ -169,7 +169,7 @@ class NFCSignature : NSObject, NFCTagReaderSessionDelegate { } printLog("Cert reading done") - guard let hash = MoppLibManager.prepareSignature(cert, containerPath: containerPath, roleData: roleInfo) else { + guard let hash = MoppLibContainerActions.prepareSignature(cert, containerPath: containerPath, roleData: roleInfo) else { return setSessionMessage(L(.nfcSignFailed), invalidate: true) } roleInfo = nil @@ -180,7 +180,7 @@ class NFCSignature : NSObject, NFCTagReaderSessionDelegate { _ = try await sendWrapped(tag: tag, cls: 0x00, ins: 0x20, p1: 0x00, p2: 0x85, data: pin) let signatureValue = try await sendWrapped(tag: tag, cls:0x00, ins: 0x2A, p1: 0x9E, p2: 0x9A, data: Bytes(hash), le: 256); printLog("\nRIA.NFC - Validating signature...\n") - MoppLibManager.isSignatureValid(cert, signatureValue: signatureValue, success: { _ in + MoppLibContainerActions.isSignatureValid(cert, signatureValue: signatureValue, success: { printLog("\nRIA.NFC - Successfully validated signature!\n") DispatchQueue.main.asyncAfter(deadline: .now() + 1) { NotificationCenter.default.post( diff --git a/MoppApp/MoppApp/PreviewActions.swift b/MoppApp/MoppApp/PreviewActions.swift index 883bacc34..f06cad38f 100644 --- a/MoppApp/MoppApp/PreviewActions.swift +++ b/MoppApp/MoppApp/PreviewActions.swift @@ -163,14 +163,14 @@ extension PreviewActions where Self: ContainerViewController { } else { openAsicContainerPreview(isPDF) } - } else if dataFileExt.isCdocContainerExtension { + } else if dataFileExt.isCryptoContainerExtension { openCdocContainerPreview() } else { openContentPreview(destinationPath) } }, failure: { [weak self] error in - self?.infoAlert(message: error?.localizedDescription) + self?.infoAlert(message: error.localizedDescription) }) } else { self.notifications = [] @@ -186,7 +186,7 @@ extension PreviewActions where Self: ContainerViewController { } else { openAsicContainerPreview(isPDF) } - } else if dataFileExt.isCdocContainerExtension { + } else if dataFileExt.isCryptoContainerExtension { openCdocContainerPreview() } else { openContentPreview(destinationPath) diff --git a/MoppApp/MoppApp/ProxyViewController.swift b/MoppApp/MoppApp/ProxyViewController.swift index 34cefcb91..bebfcdf2f 100644 --- a/MoppApp/MoppApp/ProxyViewController.swift +++ b/MoppApp/MoppApp/ProxyViewController.swift @@ -200,7 +200,7 @@ class ProxyViewController: MoppViewController, URLSessionDelegate { let manualProxyConf = ManualProxy.getManualProxyConfiguration() - let userAgent = MoppLibManager.sharedInstance().userAgent() + let userAgent = MoppLibManager.userAgent() var request = URLRequest(url: url) request.httpMethod = "GET" request.setValue(userAgent, forHTTPHeaderField: "User-Agent") diff --git a/MoppApp/MoppApp/RecentContainersViewController.swift b/MoppApp/MoppApp/RecentContainersViewController.swift index b0b4106a0..9c117a08c 100644 --- a/MoppApp/MoppApp/RecentContainersViewController.swift +++ b/MoppApp/MoppApp/RecentContainersViewController.swift @@ -21,8 +21,6 @@ * */ -import UIKit -import CryptoLib class RecentContainersViewController : MoppModalViewController { var requestCloseSearch: (() -> Void) = {} @IBOutlet weak var tableView: UITableView! @@ -121,7 +119,7 @@ class RecentContainersViewController : MoppModalViewController { let fileURL = URL(fileURLWithPath: fileName) let pathExtension = fileURL.pathExtension if !pathExtension.isEmpty { - return pathExtension.isAsicContainerExtension || pathExtension.isCdocContainerExtension || pathExtension.isPdfContainerExtension + return pathExtension.isAsicContainerExtension || pathExtension.isCryptoContainerExtension || pathExtension.isPdfContainerExtension } return false @@ -225,33 +223,17 @@ extension RecentContainersViewController : UITableViewDelegate { self.openContainer(containerPath: path.path, navController: navController, isSendingToSivaAgreed: true) } } else { - var containerViewController: ContainerViewController LandingViewController.shared.containerType = .cdoc - containerViewController = CryptoContainerViewController.instantiate() - containerViewController.containerPath = path.path - - let container = CryptoContainer(filename: path.lastPathComponent as NSString, filePath: path.path as NSString) - - MoppLibCryptoActions.sharedInstance().parseCdocInfo( - path.path as String?, - success: {(_ cdocInfo: CdocInfo?) -> Void in - guard let strongCdocInfo = cdocInfo else { return } - let cryptoContainer = (containerViewController as! CryptoContainerViewController) - container.addressees = strongCdocInfo.addressees as? [Addressee] ?? [] - container.dataFiles = strongCdocInfo.dataFiles - cryptoContainer.containerPath = path.path as String? - cryptoContainer.state = .opened - - cryptoContainer.container = container - cryptoContainer.isContainerEncrypted = true - - navController = (LandingViewController.shared.viewController(for: .cryptoTab) as? UINavigationController)! - navController.pushViewController(cryptoContainer, animated: true) - }, - failure: { _ in - failure() - } - ) + Decrypt.parseCdocInfo(withFullPath: path.path) { cdocInfo in + guard let strongCdocInfo = cdocInfo else { return failure() } + let cryptoContainer = CryptoContainerViewController.instantiate() + cryptoContainer.containerPath = path.path + cryptoContainer.container = CryptoContainer(filename: path.lastPathComponent, filePath: path.path, cdocInfo: strongCdocInfo) + cryptoContainer.state = .opened + cryptoContainer.isContainerEncrypted = true + navController = (LandingViewController.shared.viewController(for: .cryptoTab) as? UINavigationController)! + navController.pushViewController(cryptoContainer, animated: true) + } } }) diff --git a/MoppApp/MoppApp/Settings.storyboard b/MoppApp/MoppApp/Settings.storyboard index ae77e9833..95c368586 100644 --- a/MoppApp/MoppApp/Settings.storyboard +++ b/MoppApp/MoppApp/Settings.storyboard @@ -1,9 +1,9 @@ - + - + @@ -189,21 +189,109 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + - + @@ -253,7 +341,7 @@ - + @@ -291,7 +379,7 @@ - + @@ -426,7 +514,7 @@