Git Product home page Git Product logo

shield's Introduction

🛡 Shield

Security library covering Cryptography, Hashing, HMAC, Random, PBKDF, PKCS, X509, & PKCS10.

GitHub Workflow Status Coverage

Getting Started

Shield is a Swift package (comprised of many distinct modules) and delivered using the Swift Package Manager.

To use Shield in your project, add the following dependency to its package.swift:

  dependencies: [
    .package(url: "https://github.com/outfoxx/Shield", from: "3.0.0")
  ],

Documentation

Shield has documentation describing the modules and some basic reference documentation.

Package Documentation

Note

The documentation is currently lacking due to issues with Swift DocC surrounding multi-module packages and extension methods. They will be remedied soon with an upcoming releases of Swift.

License

MIT License

Copyright (c) 2019 Outfox, inc.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

shield's People

Contributors

feralbob avatar kdubb avatar mjg59 avatar wadetregaskis 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

Watchers

 avatar  avatar  avatar  avatar  avatar

shield's Issues

Digitally sign a pdf

Hello to all.
as the title suggests I'm trying to figure out how to digitally sign a pdf. In the iOS documentation I did not find anything that can help me.
The alternatives I have are OpenSSL (too complex, I'm not a C / C ++ developer), BouncyCastle (unfortunately only java or C #).

Reading the code, it looks like Shield can help me.

These are code snippets from my colleagues on Android:

import org.bouncycastle.asn1.x509.AlgorithmIdentifier
import org.bouncycastle.crypto.Digest
import org.bouncycastle.crypto.Signer
import org.bouncycastle.operator.bc.BcContentSignerBuilder

internal class ContentSignerBuilder(
    val sigAlgId: AlgorithmIdentifier,
    val digAlgId: AlgorithmIdentifier
) : BcContentSignerBuilder(sigAlgId, digAlgId) {

    var digestSigner: DigestSigner? = null

    override fun createSigner(sigAlgId: AlgorithmIdentifier, digAlgId: AlgorithmIdentifier): Signer {
        val digest: Digest = digestProvider.get(digAlgId)
        digestSigner = DigestSigner(
            digest = digest
        )

        return digestSigner!!
    }

}

where DigestSigner

import org.bouncycastle.crypto.*


internal class DigestSigner(
    val digest: Digest
) : Signer {

    var byteToSign: ByteArray? = null
    var signedBytes: ByteArray? = null

    override fun init(forSigning: Boolean, param: CipherParameters?) {
        if(byteToSign == null)
            reset()
    }

    override fun update(b: Byte) {
        if(byteToSign !== null)
            digest.update(b)
    }

    override fun update(b: ByteArray?, off: Int, len: Int) {
        if(byteToSign == null)
            digest.update(b, off, len)
    }

    override fun generateSignature(): ByteArray {
        if(signedBytes != null && signedBytes!!.isNotEmpty()) {
            return signedBytes as ByteArray
        }

        val hash = ByteArray(digest.digestSize)
        digest.doFinal(hash, 0)

        byteToSign = hash
        return hash
    }

    override fun verifySignature(signature: ByteArray?): Boolean {
        throw IllegalStateException(DigestSigner::class.java.simpleName + ": verifySignature not supported");
    }

    override fun reset() {
        digest.reset()
    }

    @Throws(CryptoException::class, DataLengthException::class)
    fun getHashToSign(): ByteArray? {
        return byteToSign
    }
}

I would understand if Shield is able to do the same things as BouncyCastle.
And above all, how can I make them happen.

Thanks in advance!

Package.swift: Missing dependency in ShieldX509 causes IBDesignables crash.

Hello, I've been experiencing an issue where this package causes Interface Builder IBDesignables to crash.

There's a strong possibility that I'm mis-understanding swift package dependencies, but ShieldCrypto is not listed as a Shieldx509 dependency in Package.swift, even though the CertificateBuilder.swift file in the ShieldX509 module imports ShieldCrypto.

This is probably not generally an issue, as ShieldCrypto is –I think– normally compiled anyway. But for some unknown reason Interface Builder is doing its own thing when it compiles the package, and is being selective about which Shield modules it compiles. According to the Report navigator, it's skipping the ShieldCrypto module, which is normally included when I build for the simulator, but still attempts to compile ShieldX509. It first compiles all of ShieldX509's dependencies –in order, as far as I can tell– but then crashes as it tries to find ShieldCrypto.

I'm sure that this is ultimately a bug in Interface Builder, not an actual issue with the package. However, I downloaded the source code, made the change, then re-added the package locally, and confirmed that including "ShieldCrypto" in the dependencies for ShieldX509 in Package.swift solves the issue.

Would you be able to include this change in a future update?

Elliptic curve cryptography support?

Does this library support elliptic curves?

I see that there's a kSecAttrKeyTypeEC in SecKeyType.swift, but then in ShieldSecurity/AlgorithmIdentifier.swift I see

init(publicKey: SecKey) throws {
    switch try publicKey.keyType(class: kSecAttrKeyClassPublic) {
    case .rsa:
      self.init(algorithm: iso.memberBody.us.rsadsi.pkcs.pkcs1.rsaEncryption.oid, parameters: nil)

    default:
      fatalError("unsupported public key type")
    }
  }

adding subjects to csr example?

Hi, I'm very new to learning swift. I have a need to create a csr from a dictionary of subject names and values that is structured as follows. This dictionary will vary in length and change , meaning that some subject values (such as O, OU or others) may or may not be present. I'm sure this is a very elementary task, but i'm struggling with how to accomplish it.

subjectDict = ["C": "US", "ST": "FL", "L": "Grant", "O": "Cypress Creek", "OU": "Gardenwood", "CN": "flask-client", "emailAddress": "[email protected]"]

I would like to interate through the key value pairs to build the proper subject string
for (key, value) in subjectDict!{
print("(key) : (value)")
//build array of subject names and values, suitable for passing to CertificationRequest.Builder() in next command
//need assist with this part

let csr =
try! CertificationRequest.Builder()
.subject(name: subject)<--Add prepared Subject here
.alternativeNames(names: .dnsName("outfoxx.io"))
.publicKey(keyPair: keyPair, usage: [.keyEncipherment])
.extendedKeyUsage(keyPurposes: [kp.clientAuth.oid, kp.serverAuth.oid], isCritical: true)
.build(signingKey: keyPair.privateKey, digestAlgorithm: .sha256)

I really like this project, as it greatly simplifies the csr creation process.Thanks

Standardize error reporting

Currently thrown errors are very "ad hoc". Shield needs to standardize error reporting and structures.

  • Common Protocol (e.g. ShieldError) that all error enums/structs implement.
  • Universally support NSUnderlyingErrorKey and/or NSMultipleUnderlyingErrorsKey
  • OSStatus check failures need to include the status as an underlying error.
  • CCStatus/CCCryptorStatus check failures need to include the status as an underlying error.

Fails to compile on clean checkout

Hi,

Doing a fresh checkout currently fails

bob@valen:~/Projects/Shield$ git status
On branch master
Your branch is up to date with 'origin/master'.

nothing to commit, working tree clean
bob@valen:~/Projects/Shield$ make
rm -rf ShieldTest.xcodeproj
rm -rf Project
rm -rf TestResults
xcodebuild -scheme Shield -resultBundleVersion 3 -resultBundlePath ./TestResults/macOS -destination 'platform=macOS' test
Command line invocation:
    /Applications/Xcode.app/Contents/Developer/usr/bin/xcodebuild -scheme Shield -resultBundleVersion 3 -resultBundlePath ./TestResults/macOS -destination platform=macOS test

<SNIP SNIP SNIP SNIP SNIP SNIP>

CompileSwift normal x86_64 /Users/bob/Projects/Shield/Tests/SecCertificateTests.swift (in target 'ShieldTests' from project 'Shield')
    cd /Users/bob/Projects/Shield
    /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift -frontend -c /Users/bob/Projects/Shield/Tests/CertificateBuilderTests.swift /Users/bob/Projects/Shield/Tests/CertificationRequestBuilderTests.swift /Users/bob/Projects/Shield/Tests/CryptorTests.swift /Users/bob/Projects/Shield/Tests/DigestTests.swift /Users/bob/Projects/Shield/Tests/DistinguishedNameComposerTests.swift /Users/bob/Projects/Shield/Tests/DistinguishedNameParserTests.swift /Users/bob/Projects/Shield/Tests/HmacTests.swift /Users/bob/Projects/Shield/Tests/OIDTests.swift /Users/bob/Projects/Shield/Tests/ParameterizedTest.swift -primary-file /Users/bob/Projects/Shield/Tests/SecCertificateTests.swift /Users/bob/Projects/Shield/Tests/SecIdentityTests.swift /Users/bob/Projects/Shield/Tests/SecKeyPairTests.swift /Users/bob/Projects/Shield/Tests/SecKeyTests.swift -emit-module-path /Users/bob/Library/Developer/Xcode/DerivedData/Shield-acntwdzcbdshbpatwyumshtotcmh/Build/Intermediates.noindex/Shield.build/Debug/ShieldTests.build/Objects-normal/x86_64/SecCertificateTests\~partial.swiftmodule -emit-module-doc-path /Users/bob/Library/Developer/Xcode/DerivedData/Shield-acntwdzcbdshbpatwyumshtotcmh/Build/Intermediates.noindex/Shield.build/Debug/ShieldTests.build/Objects-normal/x86_64/SecCertificateTests\~partial.swiftdoc -emit-module-source-info-path /Users/bob/Library/Developer/Xcode/DerivedData/Shield-acntwdzcbdshbpatwyumshtotcmh/Build/Intermediates.noindex/Shield.build/Debug/ShieldTests.build/Objects-normal/x86_64/SecCertificateTests\~partial.swiftsourceinfo -serialize-diagnostics-path /Users/bob/Library/Developer/Xcode/DerivedData/Shield-acntwdzcbdshbpatwyumshtotcmh/Build/Intermediates.noindex/Shield.build/Debug/ShieldTests.build/Objects-normal/x86_64/SecCertificateTests.dia -emit-dependencies-path /Users/bob/Library/Developer/Xcode/DerivedData/Shield-acntwdzcbdshbpatwyumshtotcmh/Build/Intermediates.noindex/Shield.build/Debug/ShieldTests.build/Objects-normal/x86_64/SecCertificateTests.d -emit-reference-dependencies-path /Users/bob/Library/Developer/Xcode/DerivedData/Shield-acntwdzcbdshbpatwyumshtotcmh/Build/Intermediates.noindex/Shield.build/Debug/ShieldTests.build/Objects-normal/x86_64/SecCertificateTests.swiftdeps -target x86_64-apple-macos10.12 -enable-objc-interop -sdk /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk -I /Users/bob/Library/Developer/Xcode/DerivedData/Shield-acntwdzcbdshbpatwyumshtotcmh/Build/Products/Debug -I /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/usr/lib -I /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/usr/lib -I /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/usr/lib -I /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/usr/lib -F /Users/bob/Library/Developer/Xcode/DerivedData/Shield-acntwdzcbdshbpatwyumshtotcmh/Build/Products/Debug -F /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/Library/Frameworks -enable-testing -g -module-cache-path /Users/bob/Library/Developer/Xcode/DerivedData/ModuleCache.noindex -swift-version 5 -enforce-exclusivity=checked -Onone -D SWIFT_PACKAGE -D DEBUG -D Xcode -serialize-debugging-options -serialize-debugging-options -Xcc -working-directory -Xcc /Users/bob/Projects/Shield -enable-anonymous-context-mangled-names -Xcc -I/Users/bob/Library/Developer/Xcode/DerivedData/Shield-acntwdzcbdshbpatwyumshtotcmh/Build/Products/Debug/include -Xcc -I/Users/bob/Library/Developer/Xcode/DerivedData/Shield-acntwdzcbdshbpatwyumshtotcmh/Build/Intermediates.noindex/Shield.build/Debug/ShieldTests.build/DerivedSources-normal/x86_64 -Xcc -I/Users/bob/Library/Developer/Xcode/DerivedData/Shield-acntwdzcbdshbpatwyumshtotcmh/Build/Intermediates.noindex/Shield.build/Debug/ShieldTests.build/DerivedSources/x86_64 -Xcc -I/Users/bob/Library/Developer/Xcode/DerivedData/Shield-acntwdzcbdshbpatwyumshtotcmh/Build/Intermediates.noindex/Shield.build/Debug/ShieldTests.build/DerivedSources -Xcc -DSWIFT_PACKAGE -Xcc -DDEBUG=1 -module-name ShieldTests -o /Users/bob/Library/Developer/Xcode/DerivedData/Shield-acntwdzcbdshbpatwyumshtotcmh/Build/Intermediates.noindex/Shield.build/Debug/ShieldTests.build/Objects-normal/x86_64/SecCertificateTests.o -index-store-path /Users/bob/Library/Developer/Xcode/DerivedData/Shield-acntwdzcbdshbpatwyumshtotcmh/Index/DataStore -index-system-modules

Resolve Package Graph

Test session results, code coverage, and logs:
	/Users/bob/Projects/Shield/TestResults/macOS

Testing failed:
	Use of unresolved identifier 'iso'
	Testing cancelled because the build failed.

** TEST FAILED **


The following build commands failed:
	CompileSwift normal x86_64 /Users/bob/Projects/Shield/Tests/CertificationRequestBuilderTests.swift
	CompileSwiftSources normal x86_64 com.apple.xcode.tools.swift.compiler
(2 failures)
make: *** [build-test-macOS] Error 65
bob@valen:~/Projects/Shield$ 

Move to Swift DocC when Swift 5.8 is available

Many of the features provided by Shield are via extensions to external frameworks (e.g. to the Security framework). 5.8 has support for documenting extensions where previous versions do not. Much of the documentation and switch from README is complete but needs 5.8 to work correctly.

Cocoapods support?

This is a great library, can you add it to cocoapods to make easier for ppl to import? Thanks!

Simplify SecKey.attributes codepaths?

Hi Everyone,

I'm still a newbie at Cryptography; especially with the iOS/Mac SDKs.

Looking at project.yml - I see the deployment targets are set for at least iOS 10 and Mac 10.12

deploymentTarget:
      macOS: 10.12
      iOS: 10.0
      tvOS: 10.0
      watchOS: 3.0

Given the deploymentTarget above can the attributes function in SecKey.swift be simplified to just use SecKeyCopyAttributes no matter what codepath?

I'll prepare a simple PR anyway - but I'd welcome the teams thoughts with me being a newbie. Looking forward to hearing what you think and if I'm completely off the mark or not :)

Thanks

ASN.1 AlgorithmIdentifier parsing fails if ecdsa-with-SHA256 has no parameters field

In my case I have to parse signed certificate, signatureAlgorithm field of which has no parameters field and looks like this:

Screen Shot 2021-09-15 at 10 56 52 PM

According to RFC 5758, "When ..., ecdsa-with-SHA256, ... algorithm identifier appears in the algorithm field as an AlgorithmIdentifier, the encoding MUST omit the parameters field. That is, the AlgorithmIdentifier SHALL be a SEQUENCE of one component, the OID ..., ecdsa-with-SHA256, ....".

So the certificate is correct, but its parsing fails.

My solution which solves the issue - added this implementation of init(from decoder: Decoder), which explicitly sets value of parameters to .null if there's no parameters field in the container:

Sources/ShieldX509/AlgorithmIdentifier.swift

  public init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: CodingKeys.self)
    algorithm = try container.decode(ObjectIdentifier.self, forKey: .algorithm)
    parameters = try container.decodeIfPresent(ASN1.self, forKey: .parameters) ?? .null
  }

Validity of certificate

How to access the validity/expiration date of certificate like issuerName and subjectName

example of adding othername SAN to a CSR?

Hi,
In my csr, i'd like to be able to include a UPN value for the SAN. In openssl's configuration, this would appear in the following form: subjectAltName = otherName:1.3.18.0.2.4.318;UTF8:[email protected]
I see CertificateRequestBuilder() accepts 'otherName' as a parameter, but since i'm new to swift, I'm not sure how to create the proper data for that parameter. Can anyone provide an example that shows how to accomplish this?
Just for reference, this is an example that i'm starting from

let csr =
try CertificationRequest.Builder()
.subject(name: NameBuilder().add("Outfox Signing", forTypeName: "CN").name)
.alternativeNames(names: .otherName(???HOW TO POPULATE THIS???))
.publicKey(keyPair: Self.keyPair, usage: [.keyEncipherment])
.extendedKeyUsage(keyPurposes: [kp.clientAuth.oid, kp.serverAuth.oid], isCritical: true)
.build(signingKey: Self.keyPair.privateKey, digestAlgorithm: .sha256)

output(csr)

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.