Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix install introduction of android in readme #4

Open
wants to merge 11 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 44 additions & 20 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,53 +1,62 @@
# React Native Des (remobile)
A des crypto for react-native

> fork from remobile/react-native-des
> only add cbc feature in Android and iOS

## Installation
```sh
npm install @remobile/react-native-des --save
npm install react-native-des-cbc --save
```

### Installation (iOS)
* Drag RCTDes.xcodeproj to your project on Xcode.
* Click on your main project file (the one that represents the .xcodeproj) select Build Phases and drag libRCTDes.a from the Products folder inside the RCTDes.xcodeproj.
* Look for Header Search Paths and make sure it contains both $(SRCROOT)/../../../react-native/React as recursive.
1. Drag `node_modules/react-native-des-cbc/ios/RCTDes.xcodeproj` to your project's `Libraries` in Xcode.
2. Click on your main project and select `Build Phases` then drag `libRCTDes.a` from the `Libraries/RCTDes.xcodeproj/Products` into `Link Binary With Libraries`.
3. (Optional) Look for `Build Settings/Header Search Paths` and make sure it contains both `$(SRCROOT)/../../../react-native/React` as recursive.
4. `command + b` to buil it.

### Installation (Android)

1/3. In `android/settings.gradle`

```gradle
...
include ':react-native-des'
project(':react-native-des').projectDir = new File(rootProject.projectDir, '../node_modules/@remobile/react-native-des/android/RCTDes')
//...
include ':react-native-des-cbc'
project(':react-native-des-cbc').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-des-cbc/android')
```

* In `android/app/build.gradle`
2/3. In `android/app/build.gradle`

```gradle
...
//...
dependencies {
...
compile project(':react-native-des')
//...
compile project(':react-native-des-cbc')
}
```

* register module (in MainApplication.java)
3/3. register module (in `MainApplication.java`)

```java
......
//......
import com.remobile.des.RCTDesPackage; // <--- import

......
//......

@Override
protected List<ReactPackage> getPackages() {
......
new RCTDesPackage(), // <------ add here
......
return Arrays.<ReactPackage>asList(
//......
new RCTDesPackage(), // <------ add here
//......
);
}

```

## Usage

### Example
```js
var Des = require('@remobile/react-native-des');
var Des = require('react-native-des-cbc');

Des.encrypt("fangyunjiang is a good developer", "ABCDEFGH", function(base64) {
console.log(base64); //wWcr2BJdyldTHn4z3AxA0qBIdHQkIKmpqhTgNuRd3fAFXzvIO5347g==
Expand All @@ -59,12 +68,27 @@ Des.encrypt("fangyunjiang is a good developer", "ABCDEFGH", function(base64) {
}, function() {
console.log("error");
});

var vec = "cute";
Des.encryptCbc("PizzaLiu is a good developer too", "ABCDEFGH", vec, function(base64) {
console.log(base64);
Des.decryptCbc(base64, "ABCDEFGH", vec, function(text) {
console.log(text); //PizzaLiu is a good developer
}, function(){
console.log("error");
});
}, function() {
console.log("error");
});
```

### method
- `encrypt(text, key, callback)`
- `encrypt(base64, key, callback)`

- `encryptCbc(text, key, vec, callback)`
- `encryptCbc(base64, key, vec, callback)`


## Server Side
* see https://github.com/remobile/react-native-des/blob/master/server
Expand Down
7 changes: 3 additions & 4 deletions android/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ apply plugin: 'com.android.library'

android {
compileSdkVersion 23
buildToolsVersion "23.0.1"

defaultConfig {
minSdkVersion 16
Expand All @@ -19,7 +18,7 @@ android {
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:23.0.1'
compile 'com.facebook.react:react-native:+'
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:23.0.1'
implementation 'com.facebook.react:react-native:+'
}
73 changes: 61 additions & 12 deletions android/src/main/java/com/remobile/des/RCTDes.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

import Decoder.BASE64Decoder;
import Decoder.BASE64Encoder;
Expand All @@ -25,6 +26,7 @@

public class RCTDes extends ReactContextBaseJavaModule {
private final static String DES = "DES";
private final static String DES_CBC = "DES/CBC/PKCS5Padding";

public RCTDes(ReactApplicationContext reactContext) {
super(reactContext);
Expand All @@ -38,7 +40,7 @@ public String getName() {
@ReactMethod
public void encrypt(String data, String key, Callback success, Callback error) {
try {
byte[] bt = encrypt(data.getBytes(), key.getBytes());
byte[] bt = encrypt(data.getBytes(), key.getBytes(), null);
String strs = new BASE64Encoder().encode(bt);
success.invoke(strs);
} catch (Exception e) {
Expand All @@ -51,7 +53,31 @@ public void decrypt(String data, String key, Callback success, Callback error) {
try {
BASE64Decoder decoder = new BASE64Decoder();
byte[] buf = decoder.decodeBuffer(data);
byte[] bt = decrypt(buf,key.getBytes());
byte[] bt = decrypt(buf,key.getBytes(),null);
String strs = new String(bt);
success.invoke(strs);
} catch (Exception e) {
error.invoke(e.getMessage());
}
}

@ReactMethod
public void encryptCbc(String data, String key, String vec, Callback success, Callback error) {
try {
byte[] bt = encrypt(data.getBytes(), key.getBytes(), vec);
String strs = new BASE64Encoder().encode(bt);
success.invoke(strs);
} catch (Exception e) {
error.invoke(e.getMessage());
}
}

@ReactMethod
public void decryptCbc(String data, String key, String vec, Callback success, Callback error) {
try {
BASE64Decoder decoder = new BASE64Decoder();
byte[] buf = decoder.decodeBuffer(data);
byte[] bt = decrypt(buf,key.getBytes(),vec);
String strs = new String(bt);
success.invoke(strs);
} catch (Exception e) {
Expand All @@ -63,12 +89,15 @@ public void decrypt(String data, String key, Callback success, Callback error) {
* Description 根据键值进行加密
* @param data
* @param key 加密键byte数组
* @param vecStr CBC加密向量String字符串
* @return
* @throws Exception
*/
private static byte[] encrypt(byte[] data, byte[] key) throws Exception {
private static byte[] encrypt(byte[] data, byte[] key, String vecStr) throws Exception {
// 生成一个可信任的随机数源
SecureRandom sr = new SecureRandom();
// CBC 加密向量(只有CBC加密时用到)
IvParameterSpec iv;

// 从原始密钥数据创建DESKeySpec对象
DESKeySpec dks = new DESKeySpec(key);
Expand All @@ -77,11 +106,19 @@ private static byte[] encrypt(byte[] data, byte[] key) throws Exception {
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
SecretKey securekey = keyFactory.generateSecret(dks);

// Cipher对象实际完成加密操作
Cipher cipher = Cipher.getInstance(DES);

// 用密钥初始化Cipher对象
cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
// Cipher对象实际完成解密操作
Cipher cipher;

if (vecStr != null) {
iv = new IvParameterSpec(vecStr.getBytes());
cipher = Cipher.getInstance(DES_CBC);
// 用密钥和加密向量初始化Cipher对象
cipher.init(Cipher.ENCRYPT_MODE, securekey, iv);
} else {
cipher = Cipher.getInstance(DES);
// 用密钥初始化Cipher对象
cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
}

return cipher.doFinal(data);
}
Expand All @@ -91,12 +128,15 @@ private static byte[] encrypt(byte[] data, byte[] key) throws Exception {
* Description 根据键值进行解密
* @param data
* @param key 加密键byte数组
* @param vecStr CBC加密向量String字符串
* @return
* @throws Exception
*/
private static byte[] decrypt(byte[] data, byte[] key) throws Exception {
private static byte[] decrypt(byte[] data, byte[] key, String vecStr) throws Exception {
// 生成一个可信任的随机数源
SecureRandom sr = new SecureRandom();
// CBC 加密向量(只有CBC解密时用到)
IvParameterSpec iv;

// 从原始密钥数据创建DESKeySpec对象
DESKeySpec dks = new DESKeySpec(key);
Expand All @@ -106,10 +146,19 @@ private static byte[] decrypt(byte[] data, byte[] key) throws Exception {
SecretKey securekey = keyFactory.generateSecret(dks);

// Cipher对象实际完成解密操作
Cipher cipher = Cipher.getInstance(DES);
Cipher cipher;

if (vecStr != null) {
iv = new IvParameterSpec(vecStr.getBytes());
cipher = Cipher.getInstance(DES_CBC);
// 用密钥和加密向量初始化Cipher对象
cipher.init(Cipher.DECRYPT_MODE, securekey, iv);
} else {
cipher = Cipher.getInstance(DES);
// 用密钥初始化Cipher对象
cipher.init(Cipher.DECRYPT_MODE, securekey, sr);
}

// 用密钥初始化Cipher对象
cipher.init(Cipher.DECRYPT_MODE, securekey, sr);

return cipher.doFinal(data);
}
Expand Down
2 changes: 1 addition & 1 deletion android/src/main/java/com/remobile/des/RCTDesPackage.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public List<NativeModule> createNativeModules(ReactApplicationContext reactConte
);
}

@Override
//@Override
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
Expand Down
2 changes: 2 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,6 @@ var {
module.exports = ENABLE ? NativeModules.Des : {
encrypt: (text, key, callback)=>callback(text),
decrypt: (code, key, callback)=>callback(code),
encryptCbc: (text, key, vec, callback)=>callback(text),
decryptCbc: (code, key, vec, callback)=>callback(code),
};
23 changes: 21 additions & 2 deletions ios/RCTDes/RCTDes.m
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ @implementation RCTDes
RCT_EXPORT_MODULE()

RCT_EXPORT_METHOD(encrypt:(NSString *)data key:(NSString *)key success:(RCTResponseSenderBlock)success error:(RCTResponseSenderBlock)error) {
NSString *base64 = [DesBase64 encryptUseDES:data key:key];
NSString *base64 = [DesBase64 encryptUseDES:data key:key vec:nil];
if (base64 == nil) {
error(@[]);
} else {
Expand All @@ -23,11 +23,30 @@ @implementation RCTDes
}

RCT_EXPORT_METHOD(decrypt:(NSString *)base64 key:(NSString *)key success:(RCTResponseSenderBlock)success error:(RCTResponseSenderBlock)error) {
NSString *data = [DesBase64 decryptUseDES:base64 key:key];
NSString *data = [DesBase64 decryptUseDES:base64 key:key vec:nil];
if (data == nil) {
error(@[]);
} else {
success(@[data]);
}
}

RCT_EXPORT_METHOD(encryptCbc:(NSString *)data key:(NSString *)key vec:(NSString *)vec success:(RCTResponseSenderBlock)success error:(RCTResponseSenderBlock)error) {
NSString *base64 = [DesBase64 encryptUseDES:data key:key vec:vec];
if (base64 == nil) {
error(@[]);
} else {
success(@[base64]);
}
}

RCT_EXPORT_METHOD(decryptCbc:(NSString *)base64 key:(NSString *)key vec:(NSString *)vec success:(RCTResponseSenderBlock)success error:(RCTResponseSenderBlock)error) {
NSString *data = [DesBase64 decryptUseDES:base64 key:key vec:vec];
if (data == nil) {
error(@[]);
} else {
success(@[data]);
}
}

@end
4 changes: 2 additions & 2 deletions ios/RCTDes/lib/DesBase64.h
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
#import <Foundation/Foundation.h>

@interface DesBase64 : NSObject
+ (NSString *)encryptUseDES:(NSString *)clearText key:(NSString *)key;
+ (NSString*)decryptUseDES:(NSString*)cipherText key:(NSString*)key;
+ (NSString *)encryptUseDES:(NSString *)clearText key:(NSString *)key vec:(NSString *)vec;
+ (NSString*)decryptUseDES:(NSString*)cipherText key:(NSString*)key vec:(NSString *)vec;

@end
27 changes: 19 additions & 8 deletions ios/RCTDes/lib/DesBase64.m
Original file line number Diff line number Diff line change
Expand Up @@ -12,20 +12,26 @@

@implementation DesBase64

+ (NSString *)encryptUseDES:(NSString *)clearText key:(NSString *)key
+ (NSString *)encryptUseDES:(NSString *)clearText key:(NSString *)key vec:(NSString*)vec
{
NSData *data = [clearText dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSUInteger dataLength = [data length];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = calloc(bufferSize, sizeof(char));
size_t numBytesEncrypted = 0;
CCOptions ccOp = kCCOptionPKCS7Padding | kCCOptionECBMode;
void *iv = nil;
if (vec) {
iv = (void *)[vec UTF8String];
ccOp = kCCOptionPKCS7Padding;
}

CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
kCCAlgorithmDES,
kCCOptionPKCS7Padding | kCCOptionECBMode,
ccOp,
[key UTF8String],
kCCKeySizeDES,
nil,
iv,
[data bytes],
dataLength,
buffer,
Expand All @@ -43,21 +49,26 @@ + (NSString *)encryptUseDES:(NSString *)clearText key:(NSString *)key
return plainText;
}

+ (NSString*)decryptUseDES:(NSString*)cipherText key:(NSString*)key {
+ (NSString*)decryptUseDES:(NSString*)cipherText key:(NSString*)key vec:(NSString*)vec {
// 利用 GTMBase64 解碼 Base64 字串
NSData* cipherData = [GTMBase64 decodeString:cipherText];
NSUInteger dataLength = [cipherData length];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = calloc(bufferSize, sizeof(char));
size_t numBytesDecrypted = 0;

// IV 偏移量不需使用
CCOptions ccOp = kCCOptionPKCS7Padding | kCCOptionECBMode;
void *iv = nil;
if (vec) {
iv = (void *)[vec UTF8String];
ccOp = kCCOptionPKCS7Padding;
}

CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,
kCCAlgorithmDES,
kCCOptionPKCS7Padding | kCCOptionECBMode,
ccOp,
[key UTF8String],
kCCKeySizeDES,
nil,
iv,
[cipherData bytes],
dataLength,
buffer,
Expand Down
Loading