Skip to content

Commit

Permalink
Reformat
Browse files Browse the repository at this point in the history
  • Loading branch information
jedisct1 committed Sep 23, 2017
1 parent 832171d commit 36b11e3
Showing 1 changed file with 55 additions and 110 deletions.
165 changes: 55 additions & 110 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,27 +1,22 @@
# Sodium [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage)

[![Make a donation to support this project](https://img.shields.io/badge/donate-PayPal-green.svg?style=flat)](https://www.libsodium.org/donate)

Swift-Sodium
============
# Swift-Sodium

Swift-Sodium provides a safe and easy to use interface to perform
common cryptographic operations on iOS and OSX.
Swift-Sodium provides a safe and easy to use interface to perform common cryptographic operations on iOS and OSX.

It leverages the [Sodium](https://download.libsodium.org/doc/) library,
and although Swift is the primary target, the framework can also be used in
Objective C.
It leverages the [Sodium](https://download.libsodium.org/doc/) library, and although Swift is the primary target, the framework can also be used in Objective C applications.

Usage
=====
## Usage

Add `Sodium.framework` as a dependency to your project, and import the module:

```swift
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.
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.

It targets Swift 4, introduced in Xcode 9.0.

Expand All @@ -32,15 +27,11 @@ The `libsodium-osx.a` file has been generated by the
[dist-build/osx.sh](https://github.com/jedisct1/libsodium/blob/master/dist-build/osx.sh)
script.

Running these scripts on Xcode 9.0 (`9A235`) on the revision
`94550cefd5921c09a1ea352c759851b7ad0e592b` of libsodium generates files
identical to the ones present in this repository.
Running these scripts on Xcode 9.0 (`9A235`) on the revision `94550cefd5921c09a1ea352c759851b7ad0e592b` of libsodium generates files identical to the ones present in this repository.

Public-key Cryptography
=======================
## Public-key Cryptography

Authenticated Encryption
------------------------
### Authenticated Encryption

```swift
let sodium = Sodium(())!
Expand All @@ -59,18 +50,17 @@ let messageVerifiedAndDecryptedByBob =
recipientSecretKey: bobKeyPair.secretKey)
```

`seal()` automatically generates a nonce and prepends it to the
ciphertext. `open()` extracts the nonce and decrypts the ciphertext.
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.

Optionally, `Box` provides the ability to utilize a user-defined nonce via
`seal(message: recipientPublicKey: senderSecretKey: nonce:)`.
`seal()` automatically generates a nonce and prepends it to the ciphertext. `open()` extracts the nonce and decrypts the ciphertext.

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.
Optionally, `Box` provides the ability to utilize a user-defined nonce via `seal(message: recipientPublicKey: senderSecretKey: nonce:)`.

Anonymous Encryption (Sealed Boxes)
-----------------------------------
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)

```swift
let sodium = Sodium()
Expand All @@ -86,18 +76,13 @@ let messageDecryptedByBob =
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 can not 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.
`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 can not 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.

Public-key signatures
=====================
## Public-key signatures

Detached signatures
-------------------
### Detached signatures

```swift
let sodium = Sodium()
Expand All @@ -111,8 +96,7 @@ if sodium.sign.verify(message: message,
}
```

Attached signatures
-------------------
### Attached signatures

```swift
let sodium = Sodium()
Expand All @@ -124,11 +108,9 @@ if let unsignedMessage = sodium.sign.open(signedMessage: signedMessage, publicKe
}
```

Secret-key authenticated encryption
===================================
## Secret-key authenticated encryption

Authenticated encryption for a sequence of messages
---------------------------------------------------
### Authenticated encryption for a sequence of messages

```swift
let sodium = Sodium()
Expand All @@ -154,8 +136,7 @@ let (message2_dec, tag2) = stream_dec.pull(cipherText: encrypted2)!
let (message3_dec, tag3) = stream_dec.pull(cipherText: encrypted3)!
```

Authenticated encryption for independent messages
-------------------------------------------------
### Authenticated encryption for independent messages

```swift
let sodium = Sodium()
Expand All @@ -167,20 +148,17 @@ if let decrypted = sodium.secretBox.open(nonceAndAuthenticatedCipherText: encryp
}
```

Hashing
=======
## Hashing

Deterministic hashing
---------------------
### Deterministic hashing

```swift
let sodium = Sodium()
let message = "My Test Message".data(using:.utf8)!
let h = sodium.genericHash.hash(message: message)
```

Keyed hashing
-------------
### Keyed hashing

```swift
let sodium = Sodium()
Expand All @@ -189,8 +167,7 @@ let key = "Secret key".data(using:.utf8)!
let h = sodium.genericHash.hash(message: message, key: key)
```

Streaming
---------
### Streaming

```swift
let sodium = Sodium()
Expand All @@ -203,8 +180,7 @@ stream.update(input: message2)
let h = stream.final()
```

Short-output hashing (SipHash)
==============================
### Short-output hashing (SipHash)

```swift
let sodium = Sodium()
Expand All @@ -213,8 +189,7 @@ let key = sodium.randomBytes.buf(length: sodium.shortHash.KeyBytes)!
let h = sodium.shortHash.hash(message: message, key: key)
```

Random numbers generation
=========================
## Random numbers generation

```swift
let sodium = Sodium()
Expand All @@ -223,8 +198,7 @@ let seed = "0123456789abcdef0123456789abcdef".data(using:.utf8)!
let stream = sodium.randomBytes.deterministic(length: 1000, seed: seed)!
```

Password hashing
================
## Password hashing

```swift
let sodium = Sodium()
Expand All @@ -247,8 +221,7 @@ if sodium.pwHash.strNeedsRehash(hash: hashedStr,
}
```

Key exchange
============
## Key exchange

```swift
let sodium = Sodium()
Expand All @@ -264,17 +237,11 @@ let aliceToBobKeyEquality = sodium.utils.equals(sessionKeyPairForAlice.tx, sessi
let bobToAliceKeyEquality = sodium.utils.equals(sessionKeyPairForAlice.rx, sessionKeyPairForBob.tx) // true
```

Authentication tags
===================
## 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.
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.
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.

```swift
let sodium = Sodium()
Expand All @@ -284,13 +251,9 @@ let tag = sodium.auth.tag(message: input, secretKey: key)!
let tagIsValid = sodium.auth.verify(message: input, secretKey: key, tag: tag)
```

Key derivation
==============
## 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.
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.

```swift
let sodium = Sodium()
Expand All @@ -304,20 +267,17 @@ let subKey2 = sodium.keyDerivation.derive(secretKey: secretKey,
context: "Context!")
```

Utilities
=========
## Utilities

Zeroing memory
--------------
### Zeroing memory

```swift
let sodium = Sodium()
var dataToZero = "Message".data(using:.utf8)!
sodium.utils.zero(&dataToZero)
```

Constant-time comparison
------------------------
### Constant-time comparison

```swift
let sodium = Sodium()
Expand All @@ -326,8 +286,7 @@ let secret2 = "Secret key".data(using:.utf8)!
let equality = sodium.utils.equals(secret1, secret2)
```

Padding
-------
### Padding

```swift
let sodium = Sodium()
Expand All @@ -340,65 +299,51 @@ sodium.utils.pad(data: &data, blockSize: 16)!
sodium.utils.unpad(data: &data, blockSize: 16)!
```

Constant-time hexadecimal encoding
----------------------------------
### Constant-time hexadecimal encoding

```swift
let sodium = Sodium()
let data = "Secret key".data(using:.utf8)!
let hex = sodium.utils.bin2hex(data)
```

Hexadecimal decoding
--------------------
### Hexadecimal decoding

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

Constant-time base64 encoding
-----------------------------
### Constant-time base64 encoding

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

Base64 decoding
---------------
### Base64 decoding

```swift
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
=====================================
## 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.
Only use the functions below if you know that you absolutely need them, and know how to use them correctly.

Unauthenticated encryption
--------------------------
## 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.
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.
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 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.
In order to generate a deterministic stream out of a seed, the `RandomBytes.deterministic_rand()` function is likely to be what you need.

```swift
let sodium = Sodium()
Expand Down

0 comments on commit 36b11e3

Please sign in to comment.