Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update Swift, ObjC examples code to showcase keygen and passphrase APIs #688

Merged
merged 8 commits into from
Jul 30, 2020
Merged
Show file tree
Hide file tree
Changes from 2 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
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,11 @@ _Code:_

- Minor dependency updates making the world a better place ([#680](https://github.com/cossacklabs/themis/pull/680)).

- **Swift**

- Update Swift examples to showcase usage newest SecureCell API: generating symmetric keys and using Secure Cell with Passphrase ([#687](https://github.com/cossacklabs/themis/pull/687)).


_Infrastructure:_

- Improved package split making `libthemis` thinner ([#678](https://github.com/cossacklabs/themis/pull/678)).
Expand Down
2 changes: 1 addition & 1 deletion docs/examples/swift/iOS-Carthage/Cartfile.resolved
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
github "cossacklabs/themis" "0.13.0"
github "cossacklabs/themis" "gothemis/v0.13.0"
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is truly funny

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

-github "cossacklabs/themis" "0.13.0"
+github "cossacklabs/themis" "gothemis/v0.13.0"

No idea why this happens. It does not happen with "0.12.0", for example, which also has gothemis/v0.12.0 pointing to the same commit. Maybe Carthage does not like annotated signed tags?..

Well, I guess we can leave it like this since that's what users will be get in their projects. And the tags aren't going anywhere. But I'd like to have some fairies come and fix it ☁️

github "krzyzanowskim/OpenSSL" "990bd88219da80d7a77289aeae245b3eb400d834"
94 changes: 83 additions & 11 deletions docs/examples/swift/iOS-Carthage/ThemisTest/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,27 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
// We don't do UI. Please look into debug console to see the results.
//

runExampleSecureCellSealMode()
runExampleSecureCellTokenProtectMode()
runExampleSecureCellImprint()

// generate key from pre-defined string
print("Using key from pre-defined string")
let keyFromString = self.generateMasterKey()
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd suggest to stop calling it generateMasterKey(), just put a constant here, and call it, like, fixedKey.

The TSGenerateSymmetricKey() is the preferred generator that we'd like to teach to the users.


// Secure Cell:
runExampleSecureCellSealMode(masterKeyData: keyFromString)
runExampleSecureCellTokenProtectMode(masterKeyData: keyFromString)
runExampleSecureCellImprint(masterKeyData: keyFromString)

// generate key from key generator
print("Using key from TSGenerateSymmetricKey")
let keyFromGenerator = TSGenerateSymmetricKey()!

// Secure Cell:
runExampleSecureCellSealMode(masterKeyData: keyFromGenerator)
runExampleSecureCellTokenProtectMode(masterKeyData: keyFromGenerator)
runExampleSecureCellImprint(masterKeyData: keyFromGenerator)

// Secure Cell with passphrase
runExampleSecureCellWithPassphrase()

runExampleGeneratingKeys()
runExampleReadingKeysFromFile()

Expand All @@ -46,9 +63,8 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
return masterKeyData
}

func runExampleSecureCellSealMode() {
func runExampleSecureCellSealMode(masterKeyData: Data) {
print("----------------------------------", #function)
let masterKeyData: Data = self.generateMasterKey()
guard let cellSeal: TSCellSeal = TSCellSeal(key: masterKeyData) else {
print("Error occurred while initializing object cellSeal", #function)
return
Expand Down Expand Up @@ -80,9 +96,8 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
}
}

func runExampleSecureCellTokenProtectMode() {
func runExampleSecureCellTokenProtectMode(masterKeyData: Data) {
print("----------------------------------", #function)
let masterKeyData: Data = self.generateMasterKey()
guard let cellToken: TSCellToken = TSCellToken(key: masterKeyData) else {
print("Error occurred while initializing object cellToken", #function)
return
Expand Down Expand Up @@ -116,9 +131,8 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
}
}

func runExampleSecureCellImprint() {
func runExampleSecureCellImprint(masterKeyData: Data) {
print("----------------------------------", #function)
let masterKeyData: Data = self.generateMasterKey()
guard let contextImprint: TSCellContextImprint = TSCellContextImprint(key: masterKeyData) else {
print("Error occurred while initializing object contextImprint", #function)
return
Expand Down Expand Up @@ -150,10 +164,49 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
return
}
}

// MARK: - Secure Cell with Passphrase
func runExampleSecureCellWithPassphrase() {
print("----------------------------------", #function)
let cellWithPassphrase = TSCellSeal(passphrase: "We are the champions")!
let message = "Your secret is safe with us"
let context = "Many secrets are safe"


var encryptedMessage: Data = Data()
do {
// context is optional parameter and may be omitted
encryptedMessage = try cellWithPassphrase.encrypt(message.data(using: .utf8)!,
context: context.data(using: .utf8)!)
print("encryptedMessage = \(encryptedMessage)")

} catch let error as NSError {
print("Error occurred while encrypting \(error)", #function)
return
}

do {
let decryptedMessage = try cellWithPassphrase.decrypt(encryptedMessage,
context: context.data(using: .utf8)!)
let resultString: String = String(data: decryptedMessage, encoding: .utf8)!
print("decryptedMessage = \(resultString)")

} catch let error as NSError {
print("Error occurred while decrypting \(error)", #function)
return
}
}

// MARK: - Key Generation
func runExampleGeneratingKeys() {
runExampleGeneratingAsymKeys()
runExampleGeneratingSymKeys()
}


// MARK: - Key Generation and Loading

func runExampleGeneratingKeys() {
func runExampleGeneratingAsymKeys() {
print("----------------------------------", #function)

// Generating RSA keys
Expand All @@ -176,6 +229,25 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
print("EC privateKey = \(privateKeyEC)")
print("RSA publicKey = \(publicKeyEC)")
}

func runExampleGeneratingSymKeys() {
print("----------------------------------", #function)

let cell = TSCellSeal(key: TSGenerateSymmetricKey()!)!
let message = "All your base are belong to us!"
let context = "For great justice"

let encrypted = try? cell.encrypt(message.data(using: .utf8)!,
context: context.data(using: .utf8)!)
print("Cell encrypted with symm key \(encrypted!)")

let decrypted = try? cell.decrypt(encrypted!,
context: context.data(using: .utf8)!)
print("Cell decrypted with symm key \(decrypted!)")

let decryptedMessage = String(data: decrypted!, encoding: .utf8)
print("Cell decrypted content \(decryptedMessage!)")
}

// Sometimes you will need to read keys from files
func runExampleReadingKeysFromFile() {
Expand Down
2 changes: 1 addition & 1 deletion docs/examples/swift/iOS-CocoaPods/Podfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,4 @@ SPEC CHECKSUMS:

PODFILE CHECKSUM: e0c05d83a39e6247258811a0d61b3eaa99b8889b

COCOAPODS: 1.9.3
COCOAPODS: 1.9.1
Original file line number Diff line number Diff line change
Expand Up @@ -428,7 +428,7 @@
SUPPORTS_MACCATALYST = NO;
SWIFT_OBJC_BRIDGING_HEADER = "$(SRCROOT)/$(PROJECT_NAME)/ThemisSwift-Bridging-Header.h";
SWIFT_SWIFT3_OBJC_INFERENCE = Default;
SWIFT_VERSION = 4.2;
SWIFT_VERSION = 5.0;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe other example projects need to be updated to use Swift 5.0 as well.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

interestingly, Carthage example uses 5.0

TARGETED_DEVICE_FAMILY = "1,2";
};
name = Debug;
Expand All @@ -452,7 +452,7 @@
SUPPORTS_MACCATALYST = NO;
SWIFT_OBJC_BRIDGING_HEADER = "$(SRCROOT)/$(PROJECT_NAME)/ThemisSwift-Bridging-Header.h";
SWIFT_SWIFT3_OBJC_INFERENCE = Default;
SWIFT_VERSION = 4.2;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Release;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,26 @@ class AppDelegate: UIResponder, UIApplicationDelegate {

// Please, look in debug console to see results

// generate key from pre-defined string
print("Using key from pre-defined string")
let keyFromString = self.generateMasterKey()

// Secure Cell:
runExampleSecureCellSealMode(masterKeyData: keyFromString)
runExampleSecureCellTokenProtectMode(masterKeyData: keyFromString)
runExampleSecureCellImprint(masterKeyData: keyFromString)

// generate key from key generator
print("Using key from TSGenerateSymmetricKey")
let keyFromGenerator = TSGenerateSymmetricKey()!

// Secure Cell:
runExampleSecureCellSealMode()
runExampleSecureCellTokenProtectMode()
runExampleSecureCellImprint()
runExampleSecureCellSealMode(masterKeyData: keyFromGenerator)
runExampleSecureCellTokenProtectMode(masterKeyData: keyFromGenerator)
runExampleSecureCellImprint(masterKeyData: keyFromGenerator)

// Secure Cell with passphrase
runExampleSecureCellWithPassphrase()

// Generating/reading keys:
runExampleGeneratingKeys()
Expand All @@ -44,11 +60,11 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
return masterKeyData
}


// MARK: - Secure Cell
// MARK: - cell seal mode
func runExampleSecureCellSealMode() {
func runExampleSecureCellSealMode(masterKeyData: Data) {
print("----------------------------------", #function)
let masterKeyData: Data = self.generateMasterKey()
guard let cellSeal: TSCellSeal = TSCellSeal(key: masterKeyData) else {
print("Error occurred while initializing object cellSeal", #function)
return
Expand All @@ -61,7 +77,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
// context is optional parameter and may be omitted
encryptedMessage = try cellSeal.encrypt(message.data(using: .utf8)!,
context: context.data(using: .utf8)!)
print("decryptedMessagez = \(encryptedMessage)")
print("encryptedMessage = \(encryptedMessage)")

} catch let error as NSError {
print("Error occurred while encrypting \(error)", #function)
Expand All @@ -81,9 +97,8 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
}

// MARK: - cell token protect mode
func runExampleSecureCellTokenProtectMode() {
func runExampleSecureCellTokenProtectMode(masterKeyData: Data) {
print("----------------------------------", #function)
let masterKeyData: Data = self.generateMasterKey()
guard let cellToken: TSCellToken = TSCellToken(key: masterKeyData) else {
print("Error occurred while initializing object cellToken", #function)
return
Expand Down Expand Up @@ -118,9 +133,8 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
}

// MARK: - cell imprint
func runExampleSecureCellImprint() {
func runExampleSecureCellImprint(masterKeyData: Data) {
print("----------------------------------", #function)
let masterKeyData: Data = self.generateMasterKey()
guard let contextImprint: TSCellContextImprint = TSCellContextImprint(key: masterKeyData) else {
print("Error occurred while initializing object contextImprint", #function)
return
Expand Down Expand Up @@ -153,9 +167,47 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
}
}

// MARK: - Secure Cell with Passphrase
func runExampleSecureCellWithPassphrase() {
print("----------------------------------", #function)
let cellWithPassphrase = TSCellSeal(passphrase: "We are the champions")!
let message = "Your secret is safe with us"
let context = "Many secrets are safe"


var encryptedMessage: Data = Data()
do {
// context is optional parameter and may be omitted
encryptedMessage = try cellWithPassphrase.encrypt(message.data(using: .utf8)!,
context: context.data(using: .utf8)!)
print("encryptedMessage = \(encryptedMessage)")

} catch let error as NSError {
print("Error occurred while encrypting \(error)", #function)
return
}

do {
let decryptedMessage = try cellWithPassphrase.decrypt(encryptedMessage,
context: context.data(using: .utf8)!)
let resultString: String = String(data: decryptedMessage, encoding: .utf8)!
print("decryptedMessage = \(resultString)")

} catch let error as NSError {
print("Error occurred while decrypting \(error)", #function)
return
}
}

// MARK: - Key Generation
// MARK: - RSA/EC
func runExampleGeneratingKeys() {
runExampleGeneratingAsymKeys()
runExampleGeneratingSymKeys()
}


// MARK: - RSA/EC
func runExampleGeneratingAsymKeys() {
print("----------------------------------", #function)

// Generating RSA keys
Expand All @@ -179,6 +231,25 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
print("RSA publicKey = \(publicKeyEC)")
}

func runExampleGeneratingSymKeys() {
print("----------------------------------", #function)

let cell = TSCellSeal(key: TSGenerateSymmetricKey()!)!
let message = "All your base are belong to us!"
let context = "For great justice"

let encrypted = try? cell.encrypt(message.data(using: .utf8)!,
context: context.data(using: .utf8)!)
print("Cell encrypted with symm key \(encrypted!)")

let decrypted = try? cell.decrypt(encrypted!,
context: context.data(using: .utf8)!)
print("Cell decrypted with symm key \(decrypted!)")

let decryptedMessage = String(data: decrypted!, encoding: .utf8)
print("Cell decrypted content \(decryptedMessage!)")
}

// MARK: - Keys from file
// Sometimes you will need to read keys from files
func readingKeysFromFile() {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="14313.18" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="01J-lp-oVM">
<device id="retina4_7" orientation="portrait">
<adaptation id="fullscreen"/>
</device>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="16097.2" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="01J-lp-oVM">
<device id="retina4_7" orientation="portrait" appearance="light"/>
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="14283.14"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="16087"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
Expand All @@ -22,12 +20,12 @@
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Themis Example Swift" textAlignment="center" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="eDm-A7-tHW">
<rect key="frame" x="44" y="97" width="287" height="21"/>
<rect key="frame" x="44" y="77" width="287" height="21"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Copyright (c) 2015-2019 Cossack Labs. All rights reserved." textAlignment="center" lineBreakMode="tailTruncation" numberOfLines="0" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="SDJ-TG-gQB">
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Copyright (c) 2015-2020 Cossack Labs. All rights reserved." textAlignment="center" lineBreakMode="tailTruncation" numberOfLines="0" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="SDJ-TG-gQB">
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This isn't the only project with an outdated copyright line.

$ git grep -o 'Copyright (c) .* All rights reserved.'
docs/examples/Themis-server/Obj-C/WorkingWithThemisServer/WorkingWithThemisServer/Base.lproj/LaunchScreen.storyboard:Copyright (c) 2015-2019 Cossack Labs. All rights reserved.
docs/examples/Themis-server/swift/SwiftThemisServerExample/SwiftThemisServerExample/Base.lproj/LaunchScreen.storyboard:Copyright (c) 2015-2019 Cossack Labs. All rights reserved.
docs/examples/objc/iOS-CocoaPods/ThemisTest/ThemisTest/Resources/Base.lproj/LaunchScreen.xib:Copyright (c) 2015-2019 Cossack Labs. All rights reserved." textAlignment="center" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" minimumFontSize="9" translatesAutoresizingMaskIntoConstraints="NO" id="8ie-xW-0ye" userLabel="Copyright (c) 2015-2017 Cossack Labs. All rights reserved.
docs/examples/objc/iOS-CocoaPods/ThemisTest/ThemisTestTests/ThemisTestTests.m:Copyright (c) 2015 Cossack Labs. All rights reserved.
docs/examples/swift/iOS-CocoaPods/ThemisSwift/ThemisSwift/Resources/Base.lproj/LaunchScreen.storyboard:Copyright (c) 2015-2019 Cossack Labs. All rights reserved.

Also, how about leaving only the date when the company assumes copyright, implying that it's still actual in the present? That would save us the trouble of doing or forgetting to do pointless updates every year.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah, makes sense

Copy link
Contributor Author

@vixentael vixentael Jul 29, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

removed copyright label at all from all projects, except Themis-server

<rect key="frame" x="44" y="562" width="287" height="64"/>
<constraints>
<constraint firstAttribute="height" constant="64" id="xwh-Ae-KiH"/>
Expand Down
Loading