浏览代码

String and NSData extension

Marcin Krzyżanowski 11 年之前
父节点
当前提交
675002f8be
共有 4 个文件被更改,包括 24 次插入8 次删除
  1. 8 0
      CryptoSwift/NSDataExtension.swift
  2. 8 0
      CryptoSwift/StringExtension.swift
  3. 5 5
      CryptoSwiftTests/CipherTests.swift
  4. 3 3
      README.md

+ 8 - 0
CryptoSwift/NSDataExtension.swift

@@ -64,6 +64,14 @@ extension NSData {
         return CRC().crc32(self);
     }
 
+    public func encrypt(cipher: Cipher) -> NSData {
+        return cipher.encrypt(self)
+    }
+
+    public func decrypt(cipher: Cipher) -> NSData {
+        return cipher.decrypt(self)
+    }
+
     internal func toHexString() -> String {
         let count = self.length / sizeof(Byte)
         var bytesArray = [Byte](count: count, repeatedValue: 0)

+ 8 - 0
CryptoSwift/StringExtension.swift

@@ -40,4 +40,12 @@ extension String {
         return self.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)?.crc32().toHexString()
     }
 
+    public func encrypt(cipher: Cipher) -> String? {
+        return self.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)?.encrypt(cipher).toHexString()
+    }
+
+    public func decrypt(cipher: Cipher) -> String? {
+        return self.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)?.decrypt(cipher).toHexString()
+    }
+
 }

+ 5 - 5
CryptoSwiftTests/CipherTests.swift

@@ -57,12 +57,12 @@ class CipherTests: XCTestCase {
             let encrypted = Cipher.ChaCha20(setup).encrypt(messageData)
             let decrypted = Cipher.ChaCha20(setup).decrypt(encrypted)
             XCTAssertEqual(messageData, decrypted, "ChaCha20 decryption failed");
-            
-            if (encrypted.isEqual(decrypted)) {
-                print("FAIL!")
-            }
-            
             XCTAssertEqual(encrypted.hexString, expectedHex, "ChaCha20 failed");
+
+            // check extension
+            let encrypted2 = messageData.encrypt(Cipher.ChaCha20(setup))
+            XCTAssertEqual(encrypted, encrypted2, "ChaCha20 extension failed")
+            
         }
     }
 }

+ 3 - 3
README.md

@@ -28,11 +28,11 @@ Good mood
 
 ##Usage
 
-Generally you should use `CryptoSwift.Hash`,`CryptoSwift.Cipher` enums or convenience extensions
+    import CryptoSwift
 
-CryptoHash enum usage
+Generally you should use `CryptoSwift.Hash`,`CryptoSwift.Cipher` enums or convenience extensions
 
-    import CryptoSwift
+Hash enum usage
     
     /* Hash enum usage */
     var data:NSData = NSData(bytes: [49, 50, 51] as [Byte], length: 3)