-
Notifications
You must be signed in to change notification settings - Fork 0
/
App.js
522 lines (465 loc) · 13.7 KB
/
App.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
/**
* Izzulmakin
* April 2018
*/
import React, { PureComponent, Children } from 'react';
import {
StyleSheet, Text, View, TextInput, TouchableOpacity, Button, Dimensions,
KeyboardAvoidingView, Animated,
AsyncStorage,
} from 'react-native';
import { Buffer } from 'buffer';
import aesjs from 'aes-js';
// crypto-save physical sensor analog to digital generated secure random initial vector
const iv = [69, 187, 210, 105, 38, 42, 222, 28, 171, 150, 136, 234, 228, 139, 194, 50];
/**
* generate 128-bit key from password with any length
* @param {*string} password
*/
function passwordToKey(password) {
var buffer;
buffer = Buffer.from(password.toString(), 'binary');
buffer = Buffer.concat([buffer], 16); // padd to 16byte
return [...buffer]; // to array
}
/** padd a text to have length of multiple of 16 bytes
* @param length: length of text to be padded
*/
function makePadd(length) {
const padding_char = ' ';
return padding_char.repeat(
((length-1)|15)+1-length // closest upper multiplier of 16
);
}
/**
* Encrypt text string using password string with AES-CBC method
* @param {*string} text
* @param {*string} password
* @return hexstring of encrypted text
*/
function encrypt(text, password) {
console_log("to encrypt: ["+text+makePadd(text.length)+"]");
var aesCbc = new aesjs.ModeOfOperation.cbc(passwordToKey(password), iv);
var encryptedBytes = aesCbc.encrypt(
aesjs.utils.utf8.toBytes( // convert to bytes
text+makePadd(text.length) // pad to multiplier of 16 length
)
);
return aesjs.utils.hex.fromBytes(encryptedBytes); //convert to hexstring
}
/**
* Decrypt hexstringEncryptedData (hex string) using password
* @param {*} hexstringEncryptedData: a hexstring of encrypted bytes
* @param {*} password: password used
*/
function decrypt(hexstringEncryptedData, password) {
var aesCbc = new aesjs.ModeOfOperation.cbc(passwordToKey(password), iv);
var encryptedBytes = aesjs.utils.hex.toBytes(hexstringEncryptedData);//hexstring to encrypted bytes
var decryptedBytes = aesCbc.decrypt(encryptedBytes); //decrypt to bytes
return aesjs.utils.utf8.fromBytes(decryptedBytes).trim();//from Bytes to string, trim trailing spaces
}
const windowW = Dimensions.get('window').width;
const windowH = Dimensions.get('window').height;
const passwordViewHeight = windowH/3;
const windowHmB = windowH - passwordViewHeight-20;
const topBarHeight = 30;
const db ={
"encrypted_aaa": "@ANoteR:encrypted_aaa",
"encrypted_data": "@ANoteR:encrypted_data",
};
const allow_log = true;
function console_log(x) {
if (allow_log) console.log(x);
}
class FadeInView extends React.Component {
state = {
fadeAnim: new Animated.Value(0), // Initial value for opacity: 0
}
componentDidMount() {
let ftime = this.props.fadeInTime || 2000;
Animated.timing( // Animate over time
this.state.fadeAnim, // The animated value to drive
{
toValue: 1, // Animate to opacity: 1 (opaque)
duration: ftime, // Make it take a while
}
).start(); // Starts the animation
}
render() {
let { fadeAnim } = this.state;
return (
<Animated.View // Special animatable View
style={{
...this.props.style,
opacity: fadeAnim, // Bind opacity to animated value
}}
>
{this.props.children}
</Animated.View>
);
}
}
class RoomPassword extends React.Component {
/**
* this.props.passwordLength
*/
state = {
input: [],
};
constructor() {
super();
this.buttonPressed = this.buttonPressed.bind(this);
};
componentDidMount() {
this.setState({input: this.props.passwordWritten});
};
buttonPressed(buttonId) {
this.setState((prevState, props) => {
var _input = prevState.input;
if (_input.length==props.passwordLength) {
_input = _input.slice(1); //new copy of array and pop index 0
}
else {
_input = _input.slice(0); //new copy array
}
_input.push(buttonId);
if (_input.length==props.passwordLength) {
console_log("password set: "+_input);
props.setPassword(_input); // !! set password is here
}
return {input: _input};
});
console_log(this.state.input);
}
render() {
let buttons = [];
for (var i=1; i<=9; i=(i+1)) {
const btId = i;
buttons.push(
<TouchableOpacity
style={[styles.roomPasswordButton]}
onPress={() => this.buttonPressed(btId)}
key={btId}
>
<Text style={styles.buttonText}>{btId}</Text>
</TouchableOpacity>
);
}
buttons.push(
<TouchableOpacity
style={[styles.roomPasswordButton,styles.roomPasswordButton0]}
onPress={() => this.buttonPressed(0)}
key={0}
>
<Text style={styles.buttonText}>{0}</Text>
</TouchableOpacity>
)
var textInfo = "Type your password";
if (this.props.isNew) {
textInfo = "Create new password (length: "+this.props.passwordLength+" digit)";
}
let textInfoView = (<Text style={{color: 'rgb(210,230,80)'}}>
{textInfo} {this.props.additionalMessage}
</Text>);
return (
<View style={styles.roomPassword}>
<FadeInView
style={{
alignItems: 'center',
width: windowW,
justifyContent: 'center',
paddingTop: 20,
paddingBottom: 20,
backgroundColor: 'rgb(23, 91, 114)'}}
children={textInfoView}
fadeInTime={400}
/>
{buttons}
</View>
);
};
};
class RoomNote extends React.Component {
/**
* props:
* password: password string
* encrypted_aaa: hexstring of encrypted "aaa"
* encrypted_data: hexstring of encrypted data
* onWrongPassword: callback when password is wrong, called by `onWrongPassword();`
* saveMethod: called when saving to database `saveMethod(new_data_string);`
*/
state = {
decrypted_data: null,
edited: false,
};
componentDidMount() {
var decrypted_aaa = this.props.encrypted_aaa;
var decrypted_data = this.props.encrypted_data;
// check if password is correct
console_log(this.props.encrypted_aaa);
decrypted_aaa = decrypt(this.props.encrypted_aaa, this.props.password);
console_log("decrypted aaa is : "+decrypted_aaa);
if (decrypted_aaa=="aaa") {
// this.setState({passwordCorrect: true});
// password correct, proceed to decrypting
console_log("encrypted data: "+this.props.encrypted_data);
var decrypted = decrypt(this.props.encrypted_data, this.props.password);
console_log("decrypted data: "+decrypted);
this.setState({decrypted_data:decrypted});
}
else {
this.props.onWrongPassword();
console_log("wrong password: "+this.props.password);
}
};
render() {
const fVactive = (1^this.state.edited);
var saveButton = null;
if (this.state.edited) {
saveButton = (<View active={true}
style={styles.roomNoteSave}>
<TouchableOpacity
onPress={()=>{
this.props.saveMethod(this.state.decrypted_data);
this.setState({edited: false})
}}
style={styles.roomNoteSaveTouchable}
>
<Text
style={styles.roomNoteSaveTouchableText}>Save</Text>
</TouchableOpacity>
</View>);
}
return (
<KeyboardAvoidingView style={styles.roomNote} >
<TextInput
style={styles.roomNoteText}
editable={true}
multiline={true}
defaultValue={this.state.decrypted_data}
onChangeText={(t) => this.setState({edited: true, decrypted_data: t})}
/>
{saveButton}
</KeyboardAvoidingView>
);
};
};
class RoomPasswordSetNewData extends React.Component {
/**
* just make newDB called once
* this.props.password
* this.props.createNewData : method
*/
componentDidMount() {
this.props.createNewData();
}
render() {
return (
<View
style={{
flexDirection: 'row',
}}>
<Text>Password set {this.props.password}</Text>
</View>
);
};
};
export default class App extends React.Component {
state = {
password: 'loading',
data: 'loading',
passwordCorrect: false,
inputPasswordAdditionalMessage: '',
passwordWritten: [],
};
componentDidMount() {
// this.dbEmpty();
this.dbCreateTable();
};
onWrongPassword() {
this.setState(
(prevState, prop) => {
return ({
passwordCorrect: false,//redundant though
passwordWritten: prevState.password,
password: null,
inputPasswordAdditionalMessage: 'Wrong password',
});
}
);
};
render() {
if (this.state.password=='loading' && this.state.data=='loading') {
// wait while componentDidMount process transaction
return (
<View
style={styles.container}>
<Text>Loading data</Text>
</View>
);
}
else if (
this.state.password!==null
&& this.state.password!="loading"
&& this.state.data!==null
&& this.state.data.encrypted_aaa!=undefined
&& this.state.data.encrypted_data!=undefined
) {
// password set, data loaded
return (
<RoomNote
encrypted_aaa={this.state.data.encrypted_aaa}
encrypted_data={this.state.data.encrypted_data}
password={this.state.password}
saveMethod={(dataString) => {this.dbSaveData(dataString);}}
onWrongPassword={() => {this.onWrongPassword();}}
/>
);
}
else if (this.state.password!==null && this.state.data==null) {
//password set, use it to create data
return (
<RoomPasswordSetNewData
password={this.state.password}
createNewData={() => this.dbNewData()}
/>
);
}
else { //password is null
//no password set and no data, means db is empty, create password to generate data in db
if (this.state.data==null) {
return (
<RoomPassword passwordLength={6}
isNew={true}
additionalMessage={this.state.inputPasswordAdditionalMessage}
passwordWritten={this.state.passwordWritten}
setPassword={pw => this.setState({password:pw})}
/>
);
}
//data loaded but no password set, ask for password
return (
<RoomPassword passwordLength={6}
additionalMessage={this.state.inputPasswordAdditionalMessage}
passwordWritten={this.state.passwordWritten}
setPassword={pw => this.setState({password:pw})}
/>
);
}
};
dbCreateTable() {
console_log("create table called");
this.dbFetch();
}
dbEmpty() {
//dbempty called
AsyncStorage.setItem(db.encrypted_aaa, null);
};
dbFetch() {
console_log("dbFetch is called");
AsyncStorage.getItem(db.encrypted_aaa, (error, encrypted_aaa)=> {
if (encrypted_aaa!=null) {
console_log("data loaded, encrypted_aaa: "+encrypted_aaa);
AsyncStorage.getItem(db.encrypted_data, (error, encrypted_data) => {
if (encrypted_data!=null) {
console_log("data loaded, encrypted_data: "+encrypted_data);
this.setState({
data: {"encrypted_aaa":encrypted_aaa, "encrypted_data":encrypted_data}
});
}
else {
console_log("data kosong, bikin baru (tapi password kesimpen)");
this.setState({
password: null,
data: null
});
}
});
}
else {
console_log("data kosong, bikin baru");
this.setState({
password: null,
data: null
});
}
});
};
dbNewData() {
///password set but no data, generate and save in storage
var encrypted_aaa = encrypt("aaa", this.state.password);
var encrypted_data = encrypt("write data here", this.state.password);
AsyncStorage.setItem(db.encrypted_aaa, encrypted_aaa).then(() => {
AsyncStorage.setItem(db.encrypted_data, encrypted_data).then(()=>{
this.dbFetch();
});
});
};
dbSaveData(dataString) {
console_log("to encrypt: "+dataString);
var encrypted_hexstring = encrypt(dataString, this.state.password);
console_log("encrypted hexstring to save: "+encrypted_hexstring);
AsyncStorage.setItem(db.encrypted_data, encrypted_hexstring).then(()=>{
console_log("saved");
});
};
};
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
paddingTop: topBarHeight,
},
roomPassword: {
flex: 1,
flexDirection: 'row',
flexWrap: 'wrap',
backgroundColor: '#f0f0f0',
paddingTop: passwordViewHeight,
},
roomPasswordButton: {
width: windowW/3,
height: windowHmB/4,
backgroundColor: '#FD276C',
alignItems: 'center',
justifyContent: 'center',
borderStyle: 'solid',
borderWidth: 1,
borderColor: '#ffffff',
},
roomPasswordButton0: {
marginLeft: windowW/3
},
buttonText: {
color: '#ffffff',
},
roomNote: {
flex: 1,
flexDirection: 'column',
paddingTop: topBarHeight,
width: windowW,
backgroundColor: 'rgb(230,230,230)',
},
roomNoteText: {
flex: 50,
padding: 5,
},
roomNoteSave: {
// flex: 1
},
roomNoteSaveTouchable: {
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#8BC34A',
height: 40,
},
roomNoteSaveTouchableText: {
color: '#ffffff'
},
fadeViewContainer: {
...StyleSheet.absoluteFillObject,
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
}
});