Skip to content

Commit

Permalink
Merge pull request #2 from starkbank/init
Browse files Browse the repository at this point in the history
feature/init
  • Loading branch information
cdottori-stark authored Mar 16, 2022
2 parents 3733994 + 4b054f2 commit 3180160
Show file tree
Hide file tree
Showing 26 changed files with 1,600 additions and 1 deletion.
8 changes: 8 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
.DS_Store
/.build
/Packages
/*.xcodeproj
xcuserdata/
DerivedData/
.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata
Package.resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>IDEDidComputeMac32BitWarning</key>
<true/>
</dict>
</plist>
17 changes: 17 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Changelog

All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
and this project adheres to the following versioning pattern:

Given a version number MAJOR.MINOR.PATCH, increment:

- MAJOR version when **breaking changes** are introduced;
- MINOR version when **backwards compatible changes** are introduced;
- PATCH version when backwards compatible bug **fixes** are implemented.


## [Unreleased]
### Added
- first official version
33 changes: 33 additions & 0 deletions Package.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// swift-tools-version:5.3
// The swift-tools-version declares the minimum version of Swift required to build this package.

import PackageDescription

let package = Package(
name: "starkbank-ecdsa",
products: [
// Products define the executables and libraries a package produces, and make them visible to other packages.
.library(
name: "starkbank-ecdsa",
targets: ["starkbank-ecdsa"]),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
.package(
url: "https://github.com/attaswift/BigInt.git",
from: "5.3.0")
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages this package depends on.
.target(
name: "starkbank-ecdsa",
dependencies: [
"BigInt"
]),
.testTarget(
name: "starkbank-ecdsaTests",
dependencies: ["starkbank-ecdsa"]),
]
)
126 changes: 125 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,125 @@
# ecdsa-swift
## A lightweight and fast pure Swift ECDSA

### Overview

This is a pure Swift implementation of the Elliptic Curve Digital Signature Algorithm. It is compatible with Swift 5.3. It is also compatible with OpenSSL. It uses some elegant math such as Jacobian Coordinates to speed up the ECDSA on pure Swift.

### Curves

We currently support `secp256k1`, but it's super easy to add more curves to the project. Just add them on `Curve.swift`

### Speed

We ran a test on a MAC Pro i5 2017. The libraries were run 100 times and the averages displayed bellow were obtained:

| Library | sign | verify |
| ------------------ |:-------------:| -------:|
| starkbank-ecdsa | 0.3ms | 1.1ms |

### Sample Code

How to sign a json message for [Stark Bank]:

```swift
import starkbank

// Generate privateKey from PEM string
let privateKey = try PrivateKey.fromPem("""
-----BEGIN EC PARAMETERS-----
BgUrgQQACg==
-----END EC PARAMETERS-----
-----BEGIN EC PRIVATE KEY-----
MHQCAQEEIODvZuS34wFbt0X53+P5EnSj6tMjfVK01dD1dgDH02RzoAcGBSuBBAAK
oUQDQgAE/nvHu/SQQaos9TUljQsUuKI15Zr5SabPrbwtbfT/408rkVVzq8vAisbB
RmpeRREXj5aog/Mq8RrdYy75W9q/Ig==
-----END EC PRIVATE KEY-----
""")

// Create message from json
let message = "This is a text message"

let signature = Ecdsa.sign(message: message, privateKey: privateKey)

// Generate Signature in base64. This result can be sent to Stark Bank in the request header as the Digital-Signature parameter.
print(signature.toBase64())

// To double check if the message matches the signature, do this:
let publicKey = privateKey.publicKey()

print(Ecdsa.verify(message: message, signature: signature, publicKey: publicKey))

```

Simple use:

```swift
import starkbank

// Generate new Keys
let privateKey = PrivateKey()
let publicKey = privateKey.publicKey()

let message = "My test message"

// Generate Signature
let signature = Ecdsa.sign(message: message, privateKey: privateKey)

// To verify if the signature is valid
print(Ecdsa.verify(message: message, signature: signature, publicKey: publicKey))
```

### OpenSSL

This library is compatible with OpenSSL, so you can use it to generate keys:

```
openssl ecparam -name secp256k1 -genkey -out privateKey.pem
openssl ec -in privateKey.pem -pubout -out publicKey.pem
```

Create a message.txt file and sign it:

```
openssl dgst -sha256 -sign privateKey.pem -out signatureDer.txt message.txt
```

To verify, do this:

```swift
import starkbank

let publicKeyPem = try? NSString(contentsOfFile: NSString(string:"/path/to/your/public-key/publicKey.pem").expandingTildeInPath, encoding: String.Encoding.utf8.rawValue)
let signatureDer = try? NSString(contentsOfFile: NSString(string:"/path/to/your/signature/signatureDer.txt").expandingTildeInPath, encoding: String.Encoding.utf8.rawValue)
let message = try? NSString(contentsOfFile: NSString(string:"/path/to/your/message/message.txt").expandingTildeInPath, encoding: String.Encoding.utf8.rawValue)

let publicKey = try PrivateKey.fromPem(privateKeyPem! as String)
let signature = try Signature.fromDer(signatureDer)

print(Ecdsa.verify(message: message! as String, signature: signature, publicKey: publicKey))
```

You can also verify it on terminal:

```
openssl dgst -sha256 -verify publicKey.pem -signature signatureDer.txt message.txt
```

NOTE: If you want to create a Digital Signature to use with [Stark Bank], you need to convert the binary signature to base64.

```
openssl base64 -in signatureDer.txt -out signatureBase64.txt
```

You can do the same with this library:

```swift
import starkbank

let signatureDer = try? NSString(contentsOfFile: NSString(string:"/path/to/your/signature/signatureDer.txt").expandingTildeInPath, encoding: String.Encoding.utf8.rawValue)

let signature = try Signature.fromDer(signatureDer)

print(signature.toBase64())
```

[Stark Bank]: https://starkbank.com
95 changes: 95 additions & 0 deletions Sources/starkbank-ecdsa/Curve.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
//
// File.swift
//
//
// Created by Rafael Stark on 2/14/21.
//

import BigInt
import Foundation


public class CurveFp {

public var A: BigInt
public var B: BigInt
public var P: BigInt
public var N: BigInt
public var G: Point
public var name: String
public var oid: [Int]

init(name: String, A: BigInt, B: BigInt, P: BigInt, N: BigInt, Gx: BigInt, Gy: BigInt, oid: [Int]) {
self.A = A
self.B = B
self.P = P
self.N = N
self.G = Point(Gx, Gy)
self.name = name
self.oid = oid
}

/**
Verify if the point `p` is on the curve
- Parameter p: Point p = Point(x, y)
- Returns: boolean
*/
func contains(p: Point) -> Bool {
if (p.x < 0 || p.x >= self.P) {
return false
}
if (p.y < 0 || p.y >= self.P) {
return false
}
if ((p.y.power(2) - (p.x.power(3) + self.A * p.x + self.B)) % self.P != 0) {
return false
}
return true
}

func length() -> Int {
return (1 + String(N, radix: 16).count) / 2
}
}

public let secp256k1 = CurveFp(
name: "secp256k1",
A: BigInt("0000000000000000000000000000000000000000000000000000000000000000", radix: 16)!,
B: BigInt("0000000000000000000000000000000000000000000000000000000000000007", radix: 16)!,
P: BigInt("fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f", radix: 16)!,
N: BigInt("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141", radix: 16)!,
Gx: BigInt("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", radix: 16)!,
Gy: BigInt("483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8", radix: 16)!,
oid: [1, 3, 132, 0, 10]
)

public let prime256v1 = CurveFp(
name: "prime256v1",
A: BigInt("ffffffff00000001000000000000000000000000fffffffffffffffffffffffc", radix: 16)!,
B: BigInt("5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b", radix: 16)!,
P: BigInt("ffffffff00000001000000000000000000000000ffffffffffffffffffffffff", radix: 16)!,
N: BigInt("ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551", radix: 16)!,
Gx: BigInt("6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296", radix: 16)!,
Gy: BigInt("4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5", radix: 16)!,
oid: [1, 2, 840, 10045, 3, 1, 7]
)

let supportedCurves = [
secp256k1,
prime256v1
]

let curvesByOid = supportedCurves.reduce([Array<Int>: CurveFp]()) { (dict, curve) -> [Array<Int>: CurveFp] in
var dict = dict
dict[curve.oid] = curve
return dict
}

public func getCurveByOid(_ oid: Array<Int>) throws -> CurveFp {
if (curvesByOid[oid] == nil) {
throw Error.invalidOidError("Unknown curve with oid {receivedOid}; The following are registered: {registeredOids}"
.replacingOccurrences(of: "{receivedOid}", with: oid.description)
.replacingOccurrences(of: "{registeredOids}", with: supportedCurves.description))
}
return curvesByOid[oid]!
}
48 changes: 48 additions & 0 deletions Sources/starkbank-ecdsa/Ecdsa.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
//
// File.swift
//
//
// Created by Rafael Stark on 2/15/21.
//

import BigInt
import Foundation


public class Ecdsa {

public static func sign(message: String, privateKey: PrivateKey, hashfunc: Hash = Sha256()) -> Signature {
let hashMessage = hashfunc.digest(message)
let numberMessage = BinaryAscii.intFromHex(BinaryAscii.hexFromData(hashMessage as Data))
let curve = privateKey.curve
let randNum = RandomInteger.between(min: BigInt(1), max: curve.N)
let randomSignPoint = Math.multiply(curve.G, randNum, curve.N, curve.A, curve.P)
let r = randomSignPoint.x.modulus(curve.N)
let s = ((numberMessage + r * privateKey.secret) * (Math.inv(randNum, curve.N))).modulus(curve.N)
return Signature(r, s)
}

public static func verify(message: String, signature: Signature, publicKey: PublicKey, hashfunc: Hash = Sha256()) -> Bool {
let hashMessage = hashfunc.digest(message)
let numberMessage = BinaryAscii.intFromHex(BinaryAscii.hexFromData(hashMessage as Data))
let curve = publicKey.curve
let r = signature.r
let s = signature.s

if (r < 1 || r >= curve.N) {
return false
}
if (s < 1 || s >= curve.N) {
return false
}

let inv = Math.inv(s, curve.N)
let u1 = Math.multiply(curve.G, (numberMessage * inv).modulus(curve.N), curve.N, curve.A, curve.P)
let u2 = Math.multiply(publicKey.point, (r * inv).modulus(curve.N), curve.N, curve.A, curve.P)
let v = Math.add(u1, u2, curve.A, curve.P)
if (v.isAtInfinity()) {
return false
}
return v.x.modulus(curve.N) == r
}
}
32 changes: 32 additions & 0 deletions Sources/starkbank-ecdsa/Hash.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
//
// File.swift
//
//
// Created by Rafael Stark on 2/15/21.
//

import Foundation
import CommonCrypto


public protocol Hash {
func digest(_ string: String) -> NSData
func digest(_ data: NSData) -> NSData
}

public class Sha256: Hash {

public init() {}

public func digest(_ string: String) -> NSData {
let data = string.data(using: String.Encoding.utf8)!
return digest(data as NSData)
}

public func digest(_ data : NSData) -> NSData {
let digestLength = Int(CC_SHA256_DIGEST_LENGTH)
var hash = [UInt8](repeating: 0, count: digestLength)
CC_SHA256(data.bytes, UInt32(data.length), &hash)
return NSData(bytes: hash, length: digestLength)
}
}
Loading

0 comments on commit 3180160

Please sign in to comment.