Giter Site home page Giter Site logo

swift-sodium's Introduction

Swift-Sodium Build Status

Swift-Sodium provides a safe and easy to use interface to perform common cryptographic operations on macOS, iOS, tvOS and watchOS.

It leverages the Sodium library, and although Swift is the primary target, the framework can also be used in Objective-C applications.

Please help!

The current Swift-Sodium documentation is not great. Your help to improve it and make it awesome would be very appreciated!

Usage

To add Swift-Sodium as dependency to your Xcode project, select File > Swift Packages > Add Package Dependency, enter its repository URL: https://github.com/jedisct1/swift-sodium.git and import Sodium as well as Clibsodium.

Then, to use it in your source code, add:

import Sodium

The Sodium library itself doesn't have to be installed on the system: the repository already includes a precompiled library for armv7, armv7s, arm64, as well as for the iOS simulator, WatchOS and Catalyst.

The Clibsodium.xcframework framework has been generated by the dist-build/apple-xcframework.sh script.

Running this script on Xcode 15.4 on the revision 9511c982fb1d046470a8b42aa36556cdb7da15de of libsodium generates files identical to the ones present in this repository.

Secret-key cryptography

Messages are encrypted and decrypted using the same secret key, this is also known as symmetric cryptography.

A key can be generated using the key() method, derived from a password using the Password Hashing API, or computed using a secret key and the peer's public key utilising the Key Exchange API.

Authenticated encryption for a sequence of messages

let sodium = Sodium()
let message1 = "Message 1".bytes
let message2 = "Message 2".bytes
let message3 = "Message 3".bytes

let secretkey = sodium.secretStream.xchacha20poly1305.key()

/* stream encryption */

let stream_enc = sodium.secretStream.xchacha20poly1305.initPush(secretKey: secretkey)!
let header = stream_enc.header()
let encrypted1 = stream_enc.push(message: message1)!
let encrypted2 = stream_enc.push(message: message2)!
let encrypted3 = stream_enc.push(message: message3, tag: .FINAL)!

/* stream decryption */

let stream_dec = sodium.secretStream.xchacha20poly1305.initPull(secretKey: secretkey, header: header)!
let (message1_dec, tag1) = stream_dec.pull(cipherText: encrypted1)!
let (message2_dec, tag2) = stream_dec.pull(cipherText: encrypted2)!
let (message3_dec, tag3) = stream_dec.pull(cipherText: encrypted3)!

A stream is a sequence of messages, that will be encrypted as they depart, and, decrypted as they arrive. The encrypted messages are expected to be received in the same order as they were sent.

Streams can be arbitrarily long. This API can thus be used for file encryption, by splitting files into small chunks, so that the whole file doesn't need to reside in memory concurrently.

It can also be used to exchange a sequence of messages between two peers.

The decryption function automatically checks that chunks have been received without modification, and truncation or reordering.

A tag is attached to each message, and can be used to signal the end of a sub-sequence (PUSH), or the end of the string (FINAL).

Authenticated encryption for single messages

let sodium = Sodium()
let message = "My Test Message".bytes
let secretKey = sodium.secretBox.key()
let encrypted: Bytes = sodium.secretBox.seal(message: message, secretKey: secretKey)!
if let decrypted = sodium.secretBox.open(nonceAndAuthenticatedCipherText: encrypted, secretKey: secretKey) {
    // authenticator is valid, decrypted contains the original message
}

This API encrypts a message. The decryption process will check that the messages haven't been tampered with before decrypting them.

Messages encrypted this way are independent: if multiple messages are sent this way, the recipient cannot detect if some messages have been duplicated, deleted or reordered without the sender including additional data with each message.

Optionally, SecretBox provides the ability to utilize a user-defined nonce via seal(message: secretKey: nonce:).

Public-key Cryptography

With public-key cryptography, each peer has two keys: a secret (private) key, that has to remain secret, and a public key that anyone can use to send an encrypted message to that peer. That public key can be only be used to encrypt a message. The corresponding secret is required to decrypt it.

Authenticated Encryption

let sodium = Sodium()
let aliceKeyPair = sodium.box.keyPair()!
let bobKeyPair = sodium.box.keyPair()!
let message = "My Test Message".bytes

let encryptedMessageFromAliceToBob: Bytes =
    sodium.box.seal(message: message,
                    recipientPublicKey: bobKeyPair.publicKey,
                    senderSecretKey: aliceKeyPair.secretKey)!

let messageVerifiedAndDecryptedByBob =
    sodium.box.open(nonceAndAuthenticatedCipherText: encryptedMessageFromAliceToBob,
                    senderPublicKey: aliceKeyPair.publicKey,
                    recipientSecretKey: bobKeyPair.secretKey)

This operation encrypts and sends a message to someone using their public key.

The recipient has to know the sender's public key as well, and will reject a message that doesn't appear to be valid for the expected public key.

seal() automatically generates a nonce and prepends it to the ciphertext. open() extracts the nonce and decrypts the ciphertext.

Optionally, Box provides the ability to utilize a user-defined nonce via seal(message: recipientPublicKey: senderSecretKey: nonce:).

The Box class also provides alternative functions and parameters to deterministically generate key pairs, to retrieve the nonce and/or the authenticator, and to detach them from the original message.

Anonymous Encryption (Sealed Boxes)

let sodium = Sodium()
let bobKeyPair = sodium.box.keyPair()!
let message = "My Test Message".bytes

let encryptedMessageToBob =
    sodium.box.seal(message: message, recipientPublicKey: bobKeyPair.publicKey)!

let messageDecryptedByBob =
    sodium.box.open(anonymousCipherText: encryptedMessageToBob,
                    recipientPublicKey: bobKeyPair.publicKey,
                    recipientSecretKey: bobKeyPair.secretKey)

seal() generates an ephemeral keypair, uses the ephemeral secret key in the encryption process, combines the ephemeral public key with the ciphertext, then destroys the keypair.

The sender cannot decrypt the resulting ciphertext. open() extracts the public key and decrypts using the recipient's secret key. Message integrity is verified, but the sender's identity cannot be correlated to the ciphertext.

Key exchange

let sodium = Sodium()
let aliceKeyPair = sodium.keyExchange.keyPair()!
let bobKeyPair = sodium.keyExchange.keyPair()!

let sessionKeyPairForAlice = sodium.keyExchange.sessionKeyPair(publicKey: aliceKeyPair.publicKey,
    secretKey: aliceKeyPair.secretKey, otherPublicKey: bobKeyPair.publicKey, side: .CLIENT)!
let sessionKeyPairForBob = sodium.keyExchange.sessionKeyPair(publicKey: bobKeyPair.publicKey,
    secretKey: bobKeyPair.secretKey, otherPublicKey: aliceKeyPair.publicKey, side: .SERVER)!

let aliceToBobKeyEquality = sodium.utils.equals(sessionKeyPairForAlice.tx, sessionKeyPairForBob.rx) // true
let bobToAliceKeyEquality = sodium.utils.equals(sessionKeyPairForAlice.rx, sessionKeyPairForBob.tx) // true

Public-key signatures

Signatures allow multiple parties to verify the authenticity of a public message, using the public key of the author's message.

This can be especially useful to sign software updates.

Detached signatures

The signature is generated separately to the original message.

let sodium = Sodium()
let message = "My Test Message".bytes
let keyPair = sodium.sign.keyPair()!
let signature = sodium.sign.signature(message: message, secretKey: keyPair.secretKey)!
if sodium.sign.verify(message: message,
                      publicKey: keyPair.publicKey,
                      signature: signature) {
    // signature is valid
}

Attached signatures

The signature is generated and prepended to the original message.

let sodium = Sodium()
let message = "My Test Message".bytes
let keyPair = sodium.sign.keyPair()!
let signedMessage = sodium.sign.sign(message: message, secretKey: keyPair.secretKey)!
if let unsignedMessage = sodium.sign.open(signedMessage: signedMessage, publicKey: keyPair.publicKey) {
    // signature is valid
}

Hashing

Deterministic hashing

Hashing effectively "fingerprints" input data, no matter what its size, and returns a fixed length "digest".

The digest length can be configured as required, from 16 to 64 bytes.

let sodium = Sodium()
let message = "My Test Message".bytes
let hash = sodium.genericHash.hash(message: message)
let hashOfSize32Bytes = sodium.genericHash.hash(message: message, outputLength: 32)

Keyed hashing

let sodium = Sodium()
let message = "My Test Message".bytes
let key = "Secret key".bytes
let h = sodium.genericHash.hash(message: message, key: key)

Streaming

let sodium = Sodium()
let message1 = "My Test ".bytes
let message2 = "Message".bytes
let key = "Secret key".bytes
let stream = sodium.genericHash.initStream(key: key)!
stream.update(input: message1)
stream.update(input: message2)
let h = stream.final()

Short-output hashing (SipHash)

let sodium = Sodium()
let message = "My Test Message".bytes
let key = sodium.randomBytes.buf(length: sodium.shortHash.KeyBytes)!
let h = sodium.shortHash.hash(message: message, key: key)

Random numbers generation

Random number generation produces cryptographically secure pseudorandom numbers suitable as key material.

let sodium = Sodium()
let randomBytes = sodium.randomBytes.buf(length: 1000)!
let seed = "0123456789abcdef0123456789abcdef".bytes
let stream = sodium.randomBytes.deterministic(length: 1000, seed: seed)!

Use RandomBytes.Generator as a generator to produce cryptographically secure pseudorandom numbers.

var rng = RandomBytes.Generator()
let randomUInt32 = UInt32.random(in: 0...10, using: &rng)
let randomUInt64 = UInt64.random(in: 0...10, using: &rng)
let randomInt = Int.random(in: 0...10, using: &rng)
let randomDouble = Double.random(in: 0...1, using: &rng)

Password hashing

Password hashing provides the ability to derive key material from a low-entropy password. Password hashing functions are designed to be expensive to hamper brute force attacks, thus the computational and memory parameters may be user-defined.

let sodium = Sodium()
let password = "Correct Horse Battery Staple".bytes
let hashedStr = sodium.pwHash.str(passwd: password,
                                  opsLimit: sodium.pwHash.OpsLimitInteractive,
                                  memLimit: sodium.pwHash.MemLimitInteractive)!

if sodium.pwHash.strVerify(hash: hashedStr, passwd: password) {
    // Password matches the given hash string
} else {
    // Password doesn't match the given hash string
}

if sodium.pwHash.strNeedsRehash(hash: hashedStr,
                                opsLimit: sodium.pwHash.OpsLimitInteractive,
                                memLimit: sodium.pwHash.MemLimitInteractive) {
    // Previously hashed password should be recomputed because the way it was
    // hashed doesn't match the current algorithm and the given parameters.
}

Authentication tags

The sodium.auth.tag() function computes an authentication tag (HMAC) using a message and a key. Parties knowing the key can then verify the authenticity of the message using the same parameters and the sodium.auth.verify() function.

Authentication tags are not signatures: the same key is used both for computing and verifying a tag. Therefore, verifiers can also compute tags for arbitrary messages.

let sodium = Sodium()
let input = "test".bytes
let key = sodium.auth.key()
let tag = sodium.auth.tag(message: input, secretKey: key)!
let tagIsValid = sodium.auth.verify(message: input, secretKey: key, tag: tag)

Key derivation

The sodium.keyDerivation.derive() function generates a subkey using an input (master) key, an index, and a 8 bytes string identifying the context. Up to (2^64) - 1 subkeys can be generated for each context, by incrementing the index.

let sodium = Sodium()
let secretKey = sodium.keyDerivation.keygen()!

let subKey1 = sodium.keyDerivation.derive(secretKey: secretKey,
                                          index: 0, length: 32,
                                          context: "Context!")
let subKey2 = sodium.keyDerivation.derive(secretKey: secretKey,
                                          index: 1, length: 32,
                                          context: "Context!")

Utilities

Zeroing memory

let sodium = Sodium()
var dataToZero = "Message".bytes
sodium.utils.zero(&dataToZero)

Constant-time comparison

let sodium = Sodium()
let secret1 = "Secret key".bytes
let secret2 = "Secret key".bytes
let equality = sodium.utils.equals(secret1, secret2)

Padding

let sodium = Sodium()
var bytes = "test".bytes

// make bytes.count a multiple of 16
sodium.utils.pad(bytes: &bytes, blockSize: 16)!

// restore original size
sodium.utils.unpad(bytes: &bytes, blockSize: 16)!

Padding can be useful to hide the length of a message before it is encrypted.

Constant-time hexadecimal encoding

let sodium = Sodium()
let bytes = "Secret key".bytes
let hex = sodium.utils.bin2hex(bytes)

Hexadecimal decoding

let sodium = Sodium()
let data1 = sodium.utils.hex2bin("deadbeef")
let data2 = sodium.utils.hex2bin("de:ad be:ef", ignore: " :")

Constant-time base64 encoding

let sodium = Sodium()
let b64 = sodium.utils.bin2base64("data".bytes)!
let b64_2 = sodium.utils.bin2base64("data".bytes, variant: .URLSAFE_NO_PADDING)!

Base64 decoding

let data1 = sodium.utils.base642bin(b64)
let data2 = sodium.utils.base642bin(b64, ignore: " \n")
let data3 = sodium.utils.base642bin(b64_2, variant: .URLSAFE_NO_PADDING, ignore: " \n")

Helpers to build custom constructions

Only use the functions below if you know that you absolutely need them, and know how to use them correctly.

Unauthenticated encryption

The sodium.stream.xor() function combines (using the XOR operation) an arbitrary-long input with the output of a deterministic key stream derived from a key and a nonce. The same operation applied twice produces the original input.

No authentication tag is added to the output. The data can be tampered with; an adversary can flip arbitrary bits.

In order to encrypt data using a secret key, the SecretBox class is likely to be what you are looking for.

In order to generate a deterministic stream out of a seed, the RandomBytes.deterministic_rand() function is likely to be what you need.

let sodium = Sodium()
let input = "test".bytes
let key = sodium.stream.key()
let (output, nonce) = sodium.stream.xor(input: input, secretKey: key)!
let twice = sodium.stream.xor(input: output, nonce: nonce, secretKey: key)!

XCTAssertEqual(input, twice)

Algorithms

  • Stream ciphers: XChaCha20, XSalsa20
  • AEADs: XChaCha20Poly1305, AEGIS-128L, AEGIS-256, AES256-GCM
  • MACs: Poly1305, HMAC-SHA512/256
  • Hash function: BLAKE2B
  • Key exchange: X25519
  • Signatures: Ed25519

swift-sodium's People

Contributors

aidantwoods avatar alinradut avatar blochberger avatar brunokoga avatar code28 avatar danielrbrowne avatar guanix avatar indutny avatar jedisct1 avatar jnross avatar johnalanwoods avatar kiliankoe avatar marcelofabri avatar mkuhnt avatar nathankot avatar opfeffer avatar own2pwn avatar psalami avatar qwzybug avatar ricwein avatar robbiet480 avatar rypac avatar stannie avatar tiwoc avatar wangjiejacques avatar westacular avatar xnekoix avatar zacwest avatar zetasq avatar ziogaschr avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

swift-sodium's Issues

Install swift-sodium into Swift app.

Guys, could you please provide the exact steps to import the swift-sodium lib into a Swift app? I tried drag-and-drop the Sodium folder into my app, but it says that there is no such module when I import Sodium. I tried with CocoaPods - there was an error with it. Please, help me and provide the necessary steps.

Generate HMAC

Generate HMAC from string and bytes using 128, 256, 512.
Thanks

Carthage support

Carthage is a really nice way to keep dependencies and projects up to date. Most Swift libraries that I have used offer carthage support.

Please consider it.

Not able to use it with IOS react native project

Hi I am new to ios development, I want to use libsodium to generate private and public key pair for the user on my react native app.

I have copied the Sodium.framework from the example app and when I am trying to import I am getting an error as unable to find the module. However, I get from the docs that I have to run the dist-build/ios.sh script to generate the libsodium-ios.a file. But when I am putting that script in run script of the app I am getting following error.

make: *** No rule to make target `distclean'. Stop.
/Users/anurag/Library/Developer/Xcode/DerivedData/sodium-dquxckzavonrivbryatoncvgwgtv/Build/Intermediates/sodium.build/Debug-iphonesimulator/sodium.build/Script-75EC7FC31F5F46EE006E8F63.sh: line 43: ./configure: No such file or directory

I am using xcode 8.3.3 (8E3004b).

Can someone help me out in what could be the issue here, or if I am working in totally wrong direction?

if I am working in the wrong direction what is the correct path for integrating this.

Thanks in advance.

Sodium Pod Swift 3

Hi!
I'm downloading the Sodium library using CocoaPods.
source 'https://github.com/CocoaPods/Specs.git'

platform :ios, '8.0'
inhibit_all_warnings!

use_frameworks!

target 'my_app' do
pod 'Fabric'
pod 'Crashlytics'
pod 'Sodium'
end

All installed correctly but when I launch the .xcworkspaceXcode8 shows me this alert:
captura de pantalla 2016-10-01 a les 13 50 49

I don't understand why this happens because in repository readme says Swift 3 is now the default.

What can I do?

Thanks!

Package Manager error "error: unsatisfiable"

Trying to add the dependency to Swift-Sodium but I get a error when building
error: unsatisfiable

dependencies: [
    .Package(url: "https://github.com/SwiftyJSON/SwiftyJSON.git", majorVersion: 3, minor: 1),
    .Package(url: "https://github.com/jedisct1/swift-sodium.git", majorVersion: 0),
],

The JSON dependency works as intended so I believe that my environment is ok. Tried many combinations of majorVersion and minor version. Even tried:
.Package(url: "https://github.com/jedisct1/swift-sodium.git", Version(0,0,3, prereleaseIdentifiers: ["beta"])),

I see that only 3 releases exist 0,1 0,2 and 0,3 but I can not figure out how to to use them.

Failed to install via Carthage

I try to do install swift-sodium via carthage

I use this on my Cartfile:
github "jedisct1/swift-sodium" == 0.1

Below is the error that appear

carthage update
*** Cloning swift-sodium
*** Checking out swift-sodium at "0.1"
*** xcodebuild output can be found in /var/folders/qr/rsdx9s_91b15fx_lzfy5yfwh0000gw/T/carthage-xcodebuild.mRnTvx.log
Failed to discover shared schemes in project Sodium.xcodeproj—either the project does not have any shared schemes, or xcodebuild never returned

If you believe this to be a project configuration error, please file an issue with the maintainers at https://github.com/jedisct1/swift-sodium/issues/new

Add tag

Hello. can you please add tag 0.1 for correct Carthage/CocoaPods distribution?

Add 0.2 Release to Cocoapods

Can you push the 0.2 release to Cocoapods. That way that we can reference 0.2 using just pod 'Sodium' or 'Sodium', '~> 0.2'?

Thanks

KeyDerivation.swift OSX

Compiling currently fails because KeyDerivation.swift is not a member of the Sodium_OSX target.

Missing headers in umbrella header

Hi,

we're using swift-soidum as a Carthage module - it's working flawlessly, however, in most of cases project compilation returns warnings:

<module-includes>:1:1: warning: umbrella header for module 'Sodium' does not include header 'crypto_int32.h'
#import "Headers/Sodium.h"
^
<module-includes>:1:1: warning: umbrella header for module 'Sodium' does not include header 'crypto_int64.h'
#import "Headers/Sodium.h"
^
<module-includes>:1:1: warning: umbrella header for module 'Sodium' does not include header 'crypto_sign_edwards25519sha512batch.h'
#import "Headers/Sodium.h"
^
<module-includes>:1:1: warning: umbrella header for module 'Sodium' does not include header 'crypto_uint16.h'
#import "Headers/Sodium.h"
^
<module-includes>:1:1: warning: umbrella header for module 'Sodium' does not include header 'crypto_uint32.h'
#import "Headers/Sodium.h"
^
<module-includes>:1:1: warning: umbrella header for module 'Sodium' does not include header 'crypto_uint64.h'
#import "Headers/Sodium.h"
^
<module-includes>:1:1: warning: umbrella header for module 'Sodium' does not include header 'crypto_uint8.h'
#import "Headers/Sodium.h"
^

It seems, that these headers are not even used - should they be added to sodium_lib.h or simply removed?

Thanks!

Error when using Sodium with Cocoapods

Hello guys,

This is my pod file:
screen shot 2016-10-27 at 11 39 19 am

I did "pod install"

When I imported Sodium in the project, it gives me those error:
screen shot 2016-10-27 at 11 39 59 am

I'm using Xcode 8 and Swift 3.

Can you help, please?

GenericHash::Stream - testStreaming fails sometimes

SodiumTests.ReadmeTests sometimes (in about 30% of attempts) fails with the following error:

Test Case '-[SodiumTests.ReadmeTests testStreaming]' started.
xctest(6198,0x107d243c0) malloc: *** error for object 0x7fb14cd89ae8: incorrect checksum for freed object - object was probably modified after being freed.
*** set a breakpoint in malloc_error_break to debug

Environment:
iPhone 7 Plus simulator, iOS 10.3

This could possibly be due to the Stream.state property being an unsafe pointer.

use "let" instead of "var" for properties in public class Sodium

public class Sodium {
    public var box = Box()
    public var secretBox = SecretBox()
    public var genericHash = GenericHash()
    public var pwHash = PWHash()
    public var randomBytes = RandomBytes()
    public var shortHash = ShortHash()
    public var sign = Sign()
    public var utils = Utils()
    public var keyExchange = KeyExchange()
    public var auth = Auth()

I think the properties in the class Sodium should be constant stored properties, it's better to use let instead of var
see https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Properties.html

Add wrapper for ChaCha20 functions

It would be nice, would the ChaCha20 functions also get a wrapper.

motivation
a) To make them accessible just by including the Sodium.framework to one's project (right now, directly accessing the raw C-functions results in linker errors).
b) To make it easier to use them. Not only could the pointers nicely be wrapped, but also some logic could be implemented to help users handle e.g. data-streams.

Right now, one could use those unaccessible C-functions by including the respective libsodium.a file to one's project. But that's where motivation b) kicks in.

Can't figure out how to use Scrypt, no documentation

I have tried digging through the header files in order to determine how to use Scrypt without any success. I did find this:

int crypto_pwhash_scryptsalsa208sha256_str(char out[crypto_pwhash_scryptsalsa208sha256_STRBYTES],
                                           const char * const passwd,
                                           unsigned long long passwdlen,
                                           unsigned long long opslimit,
                                           size_t memlimit);

But I cannot figure out how to use it. Node.js returns "is not a function". I am using var sodium = require("sodium").api;.

How can I use the Scrypt implementation with this library?

sodium.secretBox.seal() function does not allow nonce to be passed as parameter

sodium.secretBox.seal() function does not allow nonce to be passed as parameter. Now this makes the library pretty much unusable for us as we are communicating from devices on different platform. We are using UWP flavor of the same api [https://github.com/charlesportwoodii/libsodium-uwp/tree/master/docs]. We are using SecretBox.Open(ciphertext, nonce, secretKey) from UWP to decrypt the cipher text. But in Swift there is no way to create the encrypted message using the custom nonce [to add randomness to the the encryption]. Could anyone please guide if we have a way to create the encrypted message using nonce using swift-sodium library?

Swift 3 Support

I created a test project with sodium library added using cocoapods. I was able to install version 0.2.0. But when I tried to build XCode 8 throws swift versioning errors. I can manually fix those errors to build the project but is it possible to fix them ahead
Test.zip
?

Box, SecretBox implementation.

I found that Box only implements crypto_box, but no implementation for crypto_box_curve25519xchacha20poly1305 and crypto_box_curve25519xsalsa20poly1305,
and SecretBox only implement crypto_secretbox, but no crypto_secretbox_xsalsa20poly1305 and crypto_secretbox_xchacha20poly1305.
I would like to create a pull request for all these crypto_box_curve25519xchacha20poly1305, crypto_box_curve25519xsalsa20poly1305, crypto_secretbox_xsalsa20poly1305, crypto_secretbox_xchacha20poly1305, but I don't know the relationship between these box or secretbox, should I create new classes like XChaChaBox, XSalsaBox, XSalsaSecretBox, XChachaSecretBox for these implementations or I can add them to Box, SecretBox directly.

iOS and OSX Example apps

In my local branch, I have added iOS and OSX app using the build frameworks.
But the app didn't have any thing than just

import Sodium
let sodium = Sodium()!

If any one having some example code with UI that want to include, let me know, I will add the code and will make a pull request.

Or just let me know, I will merge the sample apps as it is and make a pull request.

Add podspec to the Cocoapods

Hello @jedisct1,
can you please push your podspec to the Cocoapods so as I can add Sodium as a dependency to other projects podspec?

Here is how-to do it. I could do this for you, but it is your project :)

Thanks,
Chris

Is there a mistake in README?

In the Public-key authenticated encryption example:

let messageVerifiedAndDecryptedByBob = sodium.box.open(encryptedMessageFromAliceToBob,
     senderPublicKey: bobKeyPair.publicKey,
     recipientSecretKey: aliceKeyPair.secretKey)

Would not be ?


let messageVerifiedAndDecryptedByBob = sodium.box.open(encryptedMessageFromAliceToBob,
      senderPublicKey: aliceKeyPair.publicKey,
      recipientSecretKey: bobKeyPair.secretKey)

Default hash/encrypt methods never changed ?

Just wondering if you would ensure that future implementations or versions of the library will use the exact same algorithms for the same hashing methods, specifically BLAKE2 for generichash or ARGON2i for pwhash, as well as the default secretbox and box encryption/decryption methods based on AES256 and EC if I read your documentation correctly ?
And if that's not the case, will you provide fallback methods to ensure one can still revert to the replaced algorithms ?
The reason for this is if stored in a persistent database, you don't want the encrypted data to be all of a sudden undecipherable due to an update of the library.
Thank you

Bug: Current Podspec for Sodium/libsodium is broken

Since the commit 865e819 moves all libsodium files into a subdirectory, the Podspec should adapt the changes. Using the current Podspec will skip all files inside Sodium/libsodium directory, resulting in missing libsodium-ios.a/libsodium-osx.a and more

Instead of

s.ios.vendored_library    = 'Sodium/libsodium-ios.a'
s.osx.vendored_library    = 'Sodium/libsodium-osx.a'

s.source_files = 'Sodium/*.{swift,h}'

the lines should probably be

s.ios.vendored_library    = 'Sodium/libsodium/libsodium-ios.a'
s.osx.vendored_library    = 'Sodium/libsodium/libsodium-osx.a'

s.source_files = 'Sodium/*.{swift,h}', 'Sodium/libsodium/*.{swift,h}'

But even then, building with xcode for iOS fails, being unable to import libsodium.

Greetings

Install via CocoaPods.

Trying to install via CocoaPods, got this message:

[!] Unable to find a specification for Sodium (~> 0.1)

Support for password hashing

More a feature request than an issue... it would be extremely useful to add a Swift API for Scrypt password hashing.

How to use an existing key pair?

Hi,

what is the best way to use an existing key pair which is saved on the local device?

Ist this method the optimal solution?
KeyPair(publicKey: pk, secretKey: sk)
pk and sk are the data of the keys.

Thank´s in advance!

crypto_stream_xor implementation.

I can't find crypto_stream_xor implementation, but I'm not sure if there is some high-level API for this, if not, I would like to create a pull request for this.

Update version

Can you please add new version tag or move 0.1 up to latest commit?

Undefined symbols for architecture arm64

I used some low-level functions because they are not provided in the Sodium class. When linking, I got the following error:

Undefined symbols for architecture arm64:
  "_sodium_init", referenced from:
      __TToFC7keyacid11AppDelegate11applicationfTCSo13UIApplication29didFinishLaunchingWithOptionsGSqGVs10DictionaryVSC29UIApplicationLaunchOptionsKeyP____Sb in AppDelegate.o
  "_crypto_sign_ed25519_sk_to_pk", referenced from:
      __TTSf4n_g___TFFC7keyacid12LocalProfile10isValidKeyFT_SbU_FGSpVs5UInt8_T_ in LocalProfile.o
  "_crypto_sign_ed25519_secretkeybytes", referenced from:
      __TFC7keyacid14ViewController11viewDidLoadfT_T_ in ViewController.o
      __TFC7keyacid12LocalProfile10isValidKeyfT_Sb in LocalProfile.o
      __TFC7keyacid12LocalProfile15generateKeyPairfT_T_ in LocalProfile.o
  "_crypto_sign_ed25519_publickeybytes", referenced from:
      __TFC7keyacid14ViewController11viewDidLoadfT_T_ in ViewController.o
      __TFC7keyacid12LocalProfile10isValidKeyfT_Sb in LocalProfile.o
      __TFC7keyacid12LocalProfile15generateKeyPairfT_T_ in LocalProfile.o
      __TFC7keyacid13RemoteProfile10isValidKeyfT_Sb in RemoteProfile.o
      __TFC7keyacid13RemoteProfile19curve25519PublicKeyfT_V10Foundation4Data in RemoteProfile.o
ld: symbol(s) not found for architecture arm64

I tested many other low-level functions, including crypto_box_easy, crypto_sign_detached, etc, and they are all normal. Only the functions listed above had these linking issues.

It's strange to have sodium_init included...

I am using swift-sodium tag 0.3

sodium.sign.signature crashes with found nil

This is my code:

let _message = message.data(using:.utf8)!
let signature:Data?
        if let myKey = self.secretKey {
            if let _signature = self.sodium.sign.signature(message: _message, secretKey: myKey) {
                signature = _signature
            }
            else {
                print("signing failed")
                signature = nil
            }
        }

always goes into the else.

If I set it as self.sodium.sign.signature(message: _message, secretKey: myKey)! it crashes with unwrapping optional found nil error

message/_message is not nil (it is an image as base64 string)
myKey is not nil and is produced via let selfKeyPair = self.sodium.box.keyPair()!

any ideas why it is failing?

Bitcode issue.

Hello!

Got any ideas? I updated my Xcode to 8.3 '8E162` but still getting this error:

`The following build commands failed:
Ld /Users/dvorobyov/Library/Developer/Xcode/DerivedData/Sodium-fghfwsjgacqbzghiyclxcedbipbx/Build/Products/Release/Sodium.framework/Versions/A/Sodium normal x86_64
(1 failure)
error: Invalid bitcode version (Producer: '802.0.38.0_0' Reader: '800.0.42_0')
clang: error: linker command failed with exit code 1 (use -v to see invocation)
A shell task (/usr/bin/xcrun xcodebuild -project /Users/dvorobyov/Documents/Projects/Phoenix/Carthage/Checkouts/swift-sodium/Sodium.xcodeproj -scheme Sodium_OSX -configuration Release ONLY_ACTIVE_ARCH=NO CODE_SIGNING_REQUIRED=NO CODE_SIGN_IDENTITY= CARTHAGE=YES clean build) failed with exit code 65:
** BUILD FAILED **

The following build commands failed:
Ld /Users/dvorobyov/Library/Developer/Xcode/DerivedData/Sodium-fghfwsjgacqbzghiyclxcedbipbx/Build/Products/Release/Sodium.framework/Versions/A/Sodium normal x86_64
(1 failure)
`

[Feature Request] ECDH Shared Secret scalarmult_*() API

While it is shown in #61 that a wrapper for the crypto_kx_client_session_keys() and crypto_kx_server_session_keys() API is now implemented in the sessionKeyPair function, there is currently no wrapper available for the crypto_scalarmult_*() API. As noted in the libsodium key exchange documentation notes, the crypto_scalarmult_*() API should be used to build constructions that differ from the higher-level crypto_kx_*_session_keys() implementation.

See also the libsodium Diffie-Hellman function documentation.

Direct access to the X25519 function is necessary, for example, to implement a double ratchet algorithm. In addition, access to the crypto_scalarmult_base() function is also necessary to derive a public key from a private key.

Cocoa pods support

Please add support for cocoa pods. It's way easier to manage dependencies.
Great job!
Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.