Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions CryptoLib/CryptoLib/CdocInfo.h
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,11 @@
*/

#import <Foundation/Foundation.h>
#import "CryptoDataFile.h"
#import "Addressee.h"

@interface CdocInfo : NSObject
@property (nonatomic, strong) NSMutableArray<Addressee *> *addressees;
@property (nonatomic, strong) NSMutableArray<CryptoDataFile *> *dataFiles;
@class Addressee;
@class CryptoDataFile;

@interface CdocInfo : NSObject
@property (nonatomic, strong) NSArray<Addressee *> *addressees;
@property (nonatomic, strong) NSArray<CryptoDataFile *> *dataFiles;
@end
3 changes: 2 additions & 1 deletion CryptoLib/CryptoLib/CryptoLib.h
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,9 @@ FOUNDATION_EXPORT const unsigned char CryptoLibVersionString[];

// In this header, you should import all the public headers of your framework using statements like #import <CryptoLib/PublicHeader.h>

#import <CryptoLib/Addressee.h>
#import <CryptoLib/CryptoDataFile.h>
#import <CryptoLib/CdocInfo.h>
#import <CryptoLib/CdocParser.h>
#import <CryptoLib/Encrypt.h>
#import <CryptoLib/Decrypt.h>
#import <CryptoLib/CdocParser.h>
2 changes: 1 addition & 1 deletion CryptoLib/CryptoLib/Decrypt.h
Original file line number Diff line number Diff line change
Expand Up @@ -25,5 +25,5 @@
@protocol AbstractSmartToken;

@interface Decrypt : NSObject
+ (NSMutableDictionary *)decryptFile:(NSString *)fullPath withToken:(id<AbstractSmartToken>)smartToken error:(NSError**)error;
+ (NSDictionary<NSString*,NSData*> * _Nullable)decryptFile:(NSString * _Nonnull)fullPath withToken:(id<AbstractSmartToken> _Nonnull)smartToken error:(NSError * _Nullable * _Nullable)error;
@end
8 changes: 4 additions & 4 deletions CryptoLib/CryptoLib/Decrypt.mm
Original file line number Diff line number Diff line change
Expand Up @@ -29,22 +29,22 @@

@implementation Decrypt

+ (NSMutableDictionary *)decryptFile:(NSString *)fullPath withToken:(id<AbstractSmartToken>)smartToken error:(NSError**)error {
+ (NSDictionary<NSString*,NSData*> *)decryptFile:(NSString *)fullPath withToken:(id<AbstractSmartToken>)smartToken error:(NSError**)error {

std::string encodedFullPath = std::string([fullPath UTF8String]);
CDOCReader cdocReader(encodedFullPath);
SmartCardTokenWrapper token(smartToken);

NSMutableDictionary *response = [NSMutableDictionary new];
std::vector<unsigned char> decryptedData = cdocReader.decryptData(&token);
*error = token.lastError();
if (decryptedData.empty()){
return response;
if (*error != nil){
return nil;
}
NSData *decrypted = [NSData dataWithBytes:decryptedData.data() length:decryptedData.size()];
std::string filename = cdocReader.fileName();
std::string mimetype = cdocReader.mimeType();

NSMutableDictionary<NSString*,NSData*> *response = [NSMutableDictionary new];
NSString *nsFilename = [NSString stringWithCString:filename.c_str() encoding: NSUTF8StringEncoding];
if ([[nsFilename pathExtension] isEqualToString: @"ddoc"]){
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:decrypted];
Expand Down
5 changes: 4 additions & 1 deletion CryptoLib/CryptoLib/Encrypt.h
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@

#import <Foundation/Foundation.h>

@class Addressee;
@class CryptoDataFile;

@interface Encrypt : NSObject
- (BOOL)encryptFile: (NSString *)fullPath withDataFiles :(NSArray *) dataFiles withAddressees: (NSArray *) addressees;
+ (BOOL)encryptFile: (NSString * _Nonnull)fullPath withDataFiles :(NSArray<CryptoDataFile*> * _Nonnull) dataFiles withAddressees: (NSArray<Addressee*> * _Nonnull) addressees;
@end
6 changes: 2 additions & 4 deletions CryptoLib/CryptoLib/Encrypt.mm
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@

@implementation Encrypt

- (BOOL)encryptFile: (NSString *)fullPath withDataFiles :(NSArray *) dataFiles withAddressees: (NSArray *) addressees {
+ (BOOL)encryptFile: (NSString *)fullPath withDataFiles :(NSArray<CryptoDataFile*> *) dataFiles withAddressees: (NSArray<Addressee*> *) addressees {

std::string encodedFullPath = std::string([fullPath UTF8String]);

Expand All @@ -43,9 +43,7 @@ - (BOOL)encryptFile: (NSString *)fullPath withDataFiles :(NSArray *) dataFiles w
for (Addressee *addressee in addressees) {
NSData *cert = addressee.cert;
unsigned char *buffer = reinterpret_cast<unsigned char*>(const_cast<void*>(cert.bytes));
std::vector<unsigned char> result = std::vector<unsigned char>(buffer, buffer + cert.length);

cdocWriter.addRecipient(std::move(result));
cdocWriter.addRecipient(std::vector<unsigned char>(buffer, buffer + cert.length));
}

return cdocWriter.encrypt();
Expand Down
2 changes: 1 addition & 1 deletion CryptoLib/CryptoLib/SmartCardTokenWrapper.mm
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ + (instancetype)dataFromVectorNoCopy:(const std::vector<unsigned char>&)data {
std::vector<uchar> SmartCardTokenWrapper::derive(const std::vector<uchar> &publicKey) const
{
NSError *error = nil;
auto result = [[token->smartTokenClass decrypt:[NSData dataFromVectorNoCopy:publicKey] error:&error] toVector];
auto result = [[token->smartTokenClass derive:[NSData dataFromVectorNoCopy:publicKey] error:&error] toVector];
token->error = error;
return result;
}
13 changes: 3 additions & 10 deletions MoppApp/MoppApp/ContainerActions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -288,7 +288,7 @@ extension ContainerActions where Self: UIViewController {
dataFile.filename = filename as String?
dataFile.filePath = $0

containerViewController?.container.dataFiles.add(dataFile)
containerViewController?.container.dataFiles.append(dataFile)
}

landingViewController.importProgressViewController.dismissRecursively(animated: false, completion: {
Expand All @@ -313,14 +313,7 @@ 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
}
}
}
return false
container.dataFiles.contains { $0.filename as NSString == filename }
}

func createNewContainer(with url: URL, dataFilePaths: [String], isEmptyFileImported: Bool, startSigningWhenCreated: Bool = false, cleanUpDataFilesInDocumentsFolder: Bool = true) {
Expand Down Expand Up @@ -401,7 +394,7 @@ extension ContainerActions where Self: UIViewController {
let dataFile = CryptoDataFile.init()
dataFile.filename = FileUtil.getFileName(currentFileName: (dataFilePath as NSString).lastPathComponent)
dataFile.filePath = dataFilePath
container.dataFiles.add(dataFile)
container.dataFiles.append(dataFile)
}

containerViewController.container = container
Expand Down
2 changes: 1 addition & 1 deletion MoppApp/MoppApp/ContainerRemovalActions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ class ContainerRemovalActions {
return false
}

cryptoContainer.dataFiles.removeObject(at: 0)
cryptoContainer.dataFiles.remove(at: 0)

return cryptoContainer.dataFiles.count == 0
}
Expand Down
60 changes: 27 additions & 33 deletions MoppApp/MoppApp/CryptoActions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -31,35 +31,29 @@ protocol CryptoActions {
extension CryptoActions where Self: CryptoContainerViewController {

func startEncryptingProcess() {
if container.addressees.count > 0 {
MoppLibCryptoActions.encryptData(
container.filePath as String?,
withDataFiles: container.dataFiles as? [Any],
withAddressees: container.addressees,
success: {
self.isCreated = false
self.isForPreview = false
self.isEncrypted = 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 let container, container.addressees.count > 0 else {
return self.infoAlert(message: L(.cryptoNoAddresseesWarning))
}
Task.detached { [weak self] in
let result = Encrypt.encryptFile(container.filePath as String, with: container.dataFiles, with: container.addressees)
guard let self else { return }
await MainActor.run {
guard result else { return self.infoAlert(message: L(.cryptoEncryptionErrorText)) }

MoppFileManager.removeFiles()

},
failure: { _ in
DispatchQueue.main.async {
self.infoAlert(message: L(.cryptoEncryptionErrorText))
}
self.isCreated = false
self.isForPreview = false
self.isEncrypted = 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)
}
)
} else {
self.infoAlert(message: L(.cryptoNoAddresseesWarning))
self.reloadCryptoData()

MoppFileManager.removeFiles()
}
}
}
func startDecryptingProcess() {
Expand All @@ -81,20 +75,20 @@ extension CryptoContainerViewController : IdCardDecryptViewControllerDelegate {
guard success else {
if let nsError = error as NSError?,
nsError == .pinBlocked {
return errorAlertWithLink(message: L(.pin1BlockedAlert))
return errorAlertWithLink(message: L(.pinBlockedAlert))
} else {
return infoAlert(message: L(.decryptionErrorMessage))
}
}
container.dataFiles.removeAllObjects()
container.dataFiles.removeAll()
for (filename, data) in dataFiles {
let cryptoDataFile = CryptoDataFile()
cryptoDataFile.filename = filename
guard let destinationPath = MoppFileManager.shared.tempFilePath(withFileName: cryptoDataFile.filename) else {
guard let destinationPath = MoppFileManager.shared.tempFilePath(withFileName: filename) else {
return infoAlert(message: L(.decryptionErrorMessage))
}
let cryptoDataFile = CryptoDataFile()
cryptoDataFile.filename = filename
cryptoDataFile.filePath = destinationPath
container.dataFiles.add(cryptoDataFile)
container.dataFiles.append(cryptoDataFile)
MoppFileManager.shared.createFile(atPath: destinationPath, contents: data)
}

Expand Down
2 changes: 1 addition & 1 deletion MoppApp/MoppApp/CryptoContainer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ class CryptoContainer {

var filename: NSString!
var filePath: NSString!
var dataFiles: NSMutableArray = []
var dataFiles: [CryptoDataFile] = []
var addressees: [Addressee] = []

init(filename: NSString, filePath: NSString){
Expand Down
2 changes: 1 addition & 1 deletion MoppApp/MoppApp/CryptoContainerViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,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
Expand Down
4 changes: 2 additions & 2 deletions MoppApp/MoppApp/ErrorUtil.swift
Original file line number Diff line number Diff line change
Expand Up @@ -41,13 +41,13 @@ class ErrorUtil {
case .noInternetConnection:
generateError(signingError: .noResponseError)
case .pinBlocked:
generateError(signingError: L(.pin2BlockedAlert))
generateError(signingError: L(.pinBlockedAlert))
case .pinLocked:
generateError(signingError: L(.pin2LockedAlert))
case .wrongPin:
let attemptsLeft = nsError.userInfo[MoppLibError.kMoppLibUserInfoRetryCount] as! Int
switch attemptsLeft {
case 0: generateError(signingError: L(.pin2BlockedAlert))
case 0: generateError(signingError: L(.pinBlockedAlert))
case 1: generateError(signingError: L(.wrongPin2Single))
default: generateError(signingError: L(.wrongPin2, [attemptsLeft]))
}
Expand Down
47 changes: 25 additions & 22 deletions MoppApp/MoppApp/IdCardViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,11 @@ class IdCardViewController : MoppViewController {
}
guard retryCount > 0 else {
return self.dismiss(animated: true) {
ErrorUtil.generateError(signingError: L(.pinBlockedAlert))
if self.isActionDecryption {
self.decryptDelegate?.idCardDecryptDidFinished(success: false, dataFiles: .init(), error: MoppLibError.Code.pinBlocked)
} else {
ErrorUtil.generateError(signingError: L(.pinBlockedAlert))
}
}
}
let pinHidden: Bool
Expand All @@ -265,10 +269,10 @@ class IdCardViewController : MoppViewController {
self.pinTextFieldTitleLabel.isHidden = pinHidden
self.pinTextFieldTitleLabel.text = switch (self.isActionDecryption, retryCount) {
case (true, 2): L(.wrongPin1msg, [retryCount])
case (true, 1): L(.wrongPin1Single)
case (true, 1): L(.wrongPin1SingleMsg)
case (true, _): L(.pin1TextfieldLabel)
case (false, 2): L(.wrongPin2msg, [retryCount])
case (false, 1): L(.wrongPin2Single)
case (false, 1): L(.wrongPin2SingleMsg)
case (false, _): L(.pin2TextfieldLabel)
}
self.pinTextFieldTitleLabel.textColor = retryCount == 3 ? UIColor.moppText : UIColor.moppError
Expand Down Expand Up @@ -368,31 +372,30 @@ class IdCardViewController : MoppViewController {

state = .tokenActionInProcess
if isActionDecryption {
guard let cardCommands else {
guard let cardCommands, let containerPath, let cert else {
decryptDelegate?.idCardDecryptDidFinished(success: false, dataFiles: .init(), error: MoppLibError.Code.cardNotFound)
return
}
MoppLibCryptoActions.decryptData(
containerPath, with: SmartToken(card: cardCommands, pin1: pin),
success: { [weak self] decryptedData in
self?.decryptDelegate?.idCardDecryptDidFinished(success: true, dataFiles: decryptedData, error: nil)
},
failure: { [weak self] error in
if let nsError = error as NSError?,
nsError == .wrongPin {
DispatchQueue.main.async {
self?.pinAttemptsLeft = (nsError.userInfo[MoppLibError.kMoppLibUserInfoRetryCount] as? NSNumber)?.uintValue ?? 0
self?.state = .wrongPin
}
} else {
DispatchQueue.main.async {
self?.dismiss(animated: false) {
self?.decryptDelegate?.idCardDecryptDidFinished(success: false, dataFiles: .init(), error: error)
}
Task.detached(priority: .background) { [weak self] in
do {
let response = try Decrypt.decryptFile(containerPath, with: SmartToken(card: cardCommands, pin1: pin, cert: cert))
guard response.count > 0 else { throw MoppLibError.Code.general }
guard let self else { return }
await MainActor.run {
self.decryptDelegate?.idCardDecryptDidFinished(success: true, dataFiles: response, error: nil)
}
} catch let error as NSError {
guard let self else { return }
await MainActor.run {
if error == .wrongPin {
self.pinAttemptsLeft = (error.userInfo[MoppLibError.kMoppLibUserInfoRetryCount] as? NSNumber)?.uintValue ?? 0
self.state = .wrongPin
} else {
self.decryptDelegate?.idCardDecryptDidFinished(success: false, dataFiles: .init(), error: error as NSError)
}
}
}
)
}
} else if DefaultsHelper.isRoleAndAddressEnabled {
let roleAndAddressView = UIStoryboard.tokenFlow.instantiateViewController(of: RoleAndAddressViewController.self)
roleAndAddressView.modalPresentationStyle = .overCurrentContext
Expand Down
2 changes: 0 additions & 2 deletions MoppApp/MoppApp/LocalizationKeys.swift
Original file line number Diff line number Diff line change
Expand Up @@ -237,8 +237,6 @@ enum LocKey : String
case pin1TextfieldLabel = "pin1-textfield-label"
case pin2LockedAlert = "pin2-locked-alert"
case pinBlockedAlert = "pin-blocked-alert"
case pin2BlockedAlert = "pin2-blocked-alert"
case pin1BlockedAlert = "pin1-blocked-alert"
case genericErrorMessage = "generic-error-message"
case decryptionWrongCard = "decryption-wrong-card"
case decryptionErrorMessage = "decryption-error-message"
Expand Down
2 changes: 1 addition & 1 deletion MoppApp/MoppApp/RecentContainersViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,7 @@ extension RecentContainersViewController : UITableViewDelegate {
path.path as String?,
success: { cdocInfo in
let cryptoContainer = (containerViewController as! CryptoContainerViewController)
container.addressees = cdocInfo.addressees as? [Addressee] ?? []
container.addressees = cdocInfo.addressees
container.dataFiles = cdocInfo.dataFiles
cryptoContainer.containerPath = path.path as String?
cryptoContainer.state = .opened
Expand Down
2 changes: 0 additions & 2 deletions MoppApp/MoppApp/en.lproj/Localizable.strings
Original file line number Diff line number Diff line change
Expand Up @@ -306,8 +306,6 @@
"pin1-textfield-label" = "Enter PIN1";
"pin2-locked-alert" = "Signing with the ID-card isn't possible yet. PIN2 code must be changed in order to sign. https://www.id.ee/en/article/changing-id-card-pin-codes-and-puk-code/";
"pin-blocked-alert" = "PIN is blocked. Unblock to use the PIN again. https://www.id.ee/en/article/changing-id-card-pin-codes-and-puk-code/";
"pin2-blocked-alert" = "PIN2 has been blocked";
"pin1-blocked-alert" = "PIN1 has been blocked";
"generic-error-message" = "Something went wrong. Please try again.";
"decryption-wrong-card" = "Unable to decrypt with this card";
"decryption-error-message" = "Something went wrong with decryption. Please try again.";
Expand Down
2 changes: 0 additions & 2 deletions MoppApp/MoppApp/et.lproj/Localizable.strings
Original file line number Diff line number Diff line change
Expand Up @@ -302,8 +302,6 @@
"pin1-textfield-label" = "Sisesta PIN1";
"pin2-locked-alert" = "Selle ID-kaardiga allkirjastamine ei ole veel võimalik. Allkirjastamiseks tuleb PIN2-koodi muuta. https://www.id.ee/artikkel/id-kaardi-pin-ja-puk-koodide-muutmine/";
"pin-blocked-alert" = "PIN on blokeeritud. Tühista blokeering, et PIN-i taas kasutada. https://www.id.ee/artikkel/id-kaardi-pin-ja-puk-koodide-muutmine/";
"pin2-blocked-alert" = "PIN2 on blokeeritud";
"pin1-blocked-alert" = "PIN1 on blokeeritud";
"generic-error-message" = "Midagi läks valesti. Palun proovi uuesti.";
"decryption-wrong-card" = "Kasutatud kaart ei ole adressaatide hulgas";
"decryption-error-message" = "Midagi läks dekrüpteerimisel valesti. Palun proovi uuesti.";
Expand Down
Loading