File: cipher_test.go

package info (click to toggle)
rclone 1.65.0%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 38,352 kB
  • sloc: sh: 1,056; xml: 857; python: 693; javascript: 612; makefile: 289; ansic: 101; php: 74
file content (1645 lines) | stat: -rw-r--r-- 63,280 bytes parent folder | download | duplicates (4)
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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
package crypt

import (
	"bytes"
	"context"
	"encoding/base32"
	"encoding/base64"
	"errors"
	"fmt"
	"io"
	"strings"
	"testing"

	"github.com/Max-Sum/base32768"
	"github.com/rclone/rclone/backend/crypt/pkcs7"
	"github.com/rclone/rclone/lib/readers"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func TestNewNameEncryptionMode(t *testing.T) {
	for _, test := range []struct {
		in          string
		expected    NameEncryptionMode
		expectedErr string
	}{
		{"off", NameEncryptionOff, ""},
		{"standard", NameEncryptionStandard, ""},
		{"obfuscate", NameEncryptionObfuscated, ""},
		{"potato", NameEncryptionOff, "unknown file name encryption mode \"potato\""},
	} {
		actual, actualErr := NewNameEncryptionMode(test.in)
		assert.Equal(t, actual, test.expected)
		if test.expectedErr == "" {
			assert.NoError(t, actualErr)
		} else {
			assert.EqualError(t, actualErr, test.expectedErr)
		}
	}
}

func TestNewNameEncryptionModeString(t *testing.T) {
	assert.Equal(t, NameEncryptionOff.String(), "off")
	assert.Equal(t, NameEncryptionStandard.String(), "standard")
	assert.Equal(t, NameEncryptionObfuscated.String(), "obfuscate")
	assert.Equal(t, NameEncryptionMode(3).String(), "Unknown mode #3")
}

type EncodingTestCase struct {
	in       string
	expected string
}

func testEncodeFileName(t *testing.T, encoding string, testCases []EncodingTestCase, caseInsensitive bool) {
	for _, test := range testCases {
		enc, err := NewNameEncoding(encoding)
		assert.NoError(t, err, "There should be no error creating name encoder for base32.")
		actual := enc.EncodeToString([]byte(test.in))
		assert.Equal(t, actual, test.expected, fmt.Sprintf("in=%q", test.in))
		recovered, err := enc.DecodeString(test.expected)
		assert.NoError(t, err)
		assert.Equal(t, string(recovered), test.in, fmt.Sprintf("reverse=%q", test.expected))
		if caseInsensitive {
			in := strings.ToUpper(test.expected)
			recovered, err = enc.DecodeString(in)
			assert.NoError(t, err)
			assert.Equal(t, string(recovered), test.in, fmt.Sprintf("reverse=%q", in))
		}
	}
}

func TestEncodeFileNameBase32(t *testing.T) {
	testEncodeFileName(t, "base32", []EncodingTestCase{
		{"", ""},
		{"1", "64"},
		{"12", "64p0"},
		{"123", "64p36"},
		{"1234", "64p36d0"},
		{"12345", "64p36d1l"},
		{"123456", "64p36d1l6o"},
		{"1234567", "64p36d1l6org"},
		{"12345678", "64p36d1l6orjg"},
		{"123456789", "64p36d1l6orjge8"},
		{"1234567890", "64p36d1l6orjge9g"},
		{"12345678901", "64p36d1l6orjge9g64"},
		{"123456789012", "64p36d1l6orjge9g64p0"},
		{"1234567890123", "64p36d1l6orjge9g64p36"},
		{"12345678901234", "64p36d1l6orjge9g64p36d0"},
		{"123456789012345", "64p36d1l6orjge9g64p36d1l"},
		{"1234567890123456", "64p36d1l6orjge9g64p36d1l6o"},
	}, true)
}

func TestEncodeFileNameBase64(t *testing.T) {
	testEncodeFileName(t, "base64", []EncodingTestCase{
		{"", ""},
		{"1", "MQ"},
		{"12", "MTI"},
		{"123", "MTIz"},
		{"1234", "MTIzNA"},
		{"12345", "MTIzNDU"},
		{"123456", "MTIzNDU2"},
		{"1234567", "MTIzNDU2Nw"},
		{"12345678", "MTIzNDU2Nzg"},
		{"123456789", "MTIzNDU2Nzg5"},
		{"1234567890", "MTIzNDU2Nzg5MA"},
		{"12345678901", "MTIzNDU2Nzg5MDE"},
		{"123456789012", "MTIzNDU2Nzg5MDEy"},
		{"1234567890123", "MTIzNDU2Nzg5MDEyMw"},
		{"12345678901234", "MTIzNDU2Nzg5MDEyMzQ"},
		{"123456789012345", "MTIzNDU2Nzg5MDEyMzQ1"},
		{"1234567890123456", "MTIzNDU2Nzg5MDEyMzQ1Ng"},
	}, false)
}

func TestEncodeFileNameBase32768(t *testing.T) {
	testEncodeFileName(t, "base32768", []EncodingTestCase{
		{"", ""},
		{"1", "㼿"},
		{"12", "㻙ɟ"},
		{"123", "㻙ⲿ"},
		{"1234", "㻙ⲍƟ"},
		{"12345", "㻙ⲍ⍟"},
		{"123456", "㻙ⲍ⍆ʏ"},
		{"1234567", "㻙ⲍ⍆觟"},
		{"12345678", "㻙ⲍ⍆觓ɧ"},
		{"123456789", "㻙ⲍ⍆觓栯"},
		{"1234567890", "㻙ⲍ⍆觓栩ɣ"},
		{"12345678901", "㻙ⲍ⍆觓栩朧"},
		{"123456789012", "㻙ⲍ⍆觓栩朤ʅ"},
		{"1234567890123", "㻙ⲍ⍆觓栩朤談"},
		{"12345678901234", "㻙ⲍ⍆觓栩朤諆ɔ"},
		{"123456789012345", "㻙ⲍ⍆觓栩朤諆媕"},
		{"1234567890123456", "㻙ⲍ⍆觓栩朤諆媕䆿"},
	}, false)
}

func TestDecodeFileNameBase32(t *testing.T) {
	enc, err := NewNameEncoding("base32")
	assert.NoError(t, err, "There should be no error creating name encoder for base32.")
	// We've tested decoding the valid ones above, now concentrate on the invalid ones
	for _, test := range []struct {
		in          string
		expectedErr error
	}{
		{"64=", ErrorBadBase32Encoding},
		{"!", base32.CorruptInputError(0)},
		{"hello=hello", base32.CorruptInputError(5)},
	} {
		actual, actualErr := enc.DecodeString(test.in)
		assert.Equal(t, test.expectedErr, actualErr, fmt.Sprintf("in=%q got actual=%q, err = %v %T", test.in, actual, actualErr, actualErr))
	}
}

func TestDecodeFileNameBase64(t *testing.T) {
	enc, err := NewNameEncoding("base64")
	assert.NoError(t, err, "There should be no error creating name encoder for base32.")
	// We've tested decoding the valid ones above, now concentrate on the invalid ones
	for _, test := range []struct {
		in          string
		expectedErr error
	}{
		{"64=", base64.CorruptInputError(2)},
		{"!", base64.CorruptInputError(0)},
		{"Hello=Hello", base64.CorruptInputError(5)},
	} {
		actual, actualErr := enc.DecodeString(test.in)
		assert.Equal(t, test.expectedErr, actualErr, fmt.Sprintf("in=%q got actual=%q, err = %v %T", test.in, actual, actualErr, actualErr))
	}
}

func TestDecodeFileNameBase32768(t *testing.T) {
	enc, err := NewNameEncoding("base32768")
	assert.NoError(t, err, "There should be no error creating name encoder for base32.")
	// We've tested decoding the valid ones above, now concentrate on the invalid ones
	for _, test := range []struct {
		in          string
		expectedErr error
	}{
		{"㼿c", base32768.CorruptInputError(1)},
		{"!", base32768.CorruptInputError(0)},
		{"㻙ⲿ=㻙ⲿ", base32768.CorruptInputError(2)},
	} {
		actual, actualErr := enc.DecodeString(test.in)
		assert.Equal(t, test.expectedErr, actualErr, fmt.Sprintf("in=%q got actual=%q, err = %v %T", test.in, actual, actualErr, actualErr))
	}
}

func testEncryptSegment(t *testing.T, encoding string, testCases []EncodingTestCase, caseInsensitive bool) {
	enc, _ := NewNameEncoding(encoding)
	c, _ := newCipher(NameEncryptionStandard, "", "", true, enc)
	for _, test := range testCases {
		actual := c.encryptSegment(test.in)
		assert.Equal(t, test.expected, actual, fmt.Sprintf("Testing %q", test.in))
		recovered, err := c.decryptSegment(test.expected)
		assert.NoError(t, err, fmt.Sprintf("Testing reverse %q", test.expected))
		assert.Equal(t, test.in, recovered, fmt.Sprintf("Testing reverse %q", test.expected))
		if caseInsensitive {
			in := strings.ToUpper(test.expected)
			recovered, err = c.decryptSegment(in)
			assert.NoError(t, err, fmt.Sprintf("Testing reverse %q", in))
			assert.Equal(t, test.in, recovered, fmt.Sprintf("Testing reverse %q", in))
		}
	}
}

func TestEncryptSegmentBase32(t *testing.T) {
	testEncryptSegment(t, "base32", []EncodingTestCase{
		{"", ""},
		{"1", "p0e52nreeaj0a5ea7s64m4j72s"},
		{"12", "l42g6771hnv3an9cgc8cr2n1ng"},
		{"123", "qgm4avr35m5loi1th53ato71v0"},
		{"1234", "8ivr2e9plj3c3esisjpdisikos"},
		{"12345", "rh9vu63q3o29eqmj4bg6gg7s44"},
		{"123456", "bn717l3alepn75b2fb2ejmi4b4"},
		{"1234567", "n6bo9jmb1qe3b1ogtj5qkf19k8"},
		{"12345678", "u9t24j7uaq94dh5q53m3s4t9ok"},
		{"123456789", "37hn305g6j12d1g0kkrl7ekbs4"},
		{"1234567890", "ot8d91eplaglb62k2b1trm2qv0"},
		{"12345678901", "h168vvrgb53qnrtvvmb378qrcs"},
		{"123456789012", "s3hsdf9e29ithrqbjqu01t8q2s"},
		{"1234567890123", "cf3jimlv1q2oc553mv7s3mh3eo"},
		{"12345678901234", "moq0uqdlqrblrc5pa5u5c7hq9g"},
		{"123456789012345", "eeam3li4rnommi3a762h5n7meg"},
		{"1234567890123456", "mijbj0frqf6ms7frcr6bd9h0env53jv96pjaaoirk7forcgpt70g"},
	}, true)
}

func TestEncryptSegmentBase64(t *testing.T) {
	testEncryptSegment(t, "base64", []EncodingTestCase{
		{"", ""},
		{"1", "yBxRX25ypgUVyj8MSxJnFw"},
		{"12", "qQUDHOGN_jVdLIMQzYrhvA"},
		{"123", "1CxFf2Mti1xIPYlGruDh-A"},
		{"1234", "RL-xOTmsxsG7kuTy2XJUxw"},
		{"12345", "3FP_GHoeBJdq0yLgaED8IQ"},
		{"123456", "Xc4T1Gqrs3OVYnrE6dpEWQ"},
		{"1234567", "uZeEzssOnDWHEOzLqjwpog"},
		{"12345678", "8noiTP5WkkbEuijsPhOpxQ"},
		{"123456789", "GeNxgLA0wiaGAKU3U7qL4Q"},
		{"1234567890", "x1DUhdmqoVWYVBLD3dha-A"},
		{"12345678901", "iEyP_3BZR6vvv_2WM6NbZw"},
		{"123456789012", "4OPGvS4SZdjvS568APUaFw"},
		{"1234567890123", "Y8c5Wr8OhYYUo7fPwdojdg"},
		{"12345678901234", "tjQPabXW112wuVF8Vh46TA"},
		{"123456789012345", "c5Vh1kTd8WtIajmFEtz2dA"},
		{"1234567890123456", "tKa5gfvTzW4d-2bMtqYgdf5Rz-k2ZqViW6HfjbIZ6cE"},
	}, false)
}

func TestEncryptSegmentBase32768(t *testing.T) {
	testEncryptSegment(t, "base32768", []EncodingTestCase{
		{"", ""},
		{"1", "詮㪗鐮僀伎作㻖㢧⪟"},
		{"12", "竢朧䉱虃光塬䟛⣡蓟"},
		{"123", "遶㞟鋅缕袡鲅ⵝ蝁ꌟ"},
		{"1234", "䢟銮䵵狌㐜燳谒颴詟"},
		{"12345", "钉Ꞇ㖃蚩憶狫朰杜㜿"},
		{"123456", "啇ᚵⵕ憗䋫➫➓肤卟"},
		{"1234567", "茫螓翁連劘樓㶔抉矟"},
		{"12345678", "龝☳䘊辄岅較络㧩襟"},
		{"123456789", "ⲱ苀㱆犂媐Ꮤ锇惫靟"},
		{"1234567890", "計宁憕偵匢皫╛纺ꌟ"},
		{"12345678901", "檆䨿鑫㪺藝ꡖ勇䦛婟"},
		{"123456789012", "雑頏䰂䲝淚哚鹡魺⪟"},
		{"1234567890123", "塃璶繁躸圅㔟䗃肃懟"},
		{"12345678901234", "腺ᕚ崚鏕鏥讥鼌䑺䲿"},
		{"123456789012345", "怪绕滻蕶肣但⠥荖惟"},
		{"1234567890123456", "肳哀旚挶靏鏻㾭䱠慟㪳ꏆ賊兲铧敻塹魀ʟ"},
	}, false)
}

func TestDecryptSegmentBase32(t *testing.T) {
	// We've tested the forwards above, now concentrate on the errors
	longName := make([]byte, 3328)
	for i := range longName {
		longName[i] = 'a'
	}
	enc, _ := NewNameEncoding("base32")
	c, _ := newCipher(NameEncryptionStandard, "", "", true, enc)
	for _, test := range []struct {
		in          string
		expectedErr error
	}{
		{"64=", ErrorBadBase32Encoding},
		{"!", base32.CorruptInputError(0)},
		{string(longName), ErrorTooLongAfterDecode},
		{enc.EncodeToString([]byte("a")), ErrorNotAMultipleOfBlocksize},
		{enc.EncodeToString([]byte("123456789abcdef")), ErrorNotAMultipleOfBlocksize},
		{enc.EncodeToString([]byte("123456789abcdef0")), pkcs7.ErrorPaddingTooLong},
	} {
		actual, actualErr := c.decryptSegment(test.in)
		assert.Equal(t, test.expectedErr, actualErr, fmt.Sprintf("in=%q got actual=%q, err = %v %T", test.in, actual, actualErr, actualErr))
	}
}

func TestDecryptSegmentBase64(t *testing.T) {
	// We've tested the forwards above, now concentrate on the errors
	longName := make([]byte, 2816)
	for i := range longName {
		longName[i] = 'a'
	}
	enc, _ := NewNameEncoding("base64")
	c, _ := newCipher(NameEncryptionStandard, "", "", true, enc)
	for _, test := range []struct {
		in          string
		expectedErr error
	}{
		{"6H=", base64.CorruptInputError(2)},
		{"!", base64.CorruptInputError(0)},
		{string(longName), ErrorTooLongAfterDecode},
		{enc.EncodeToString([]byte("a")), ErrorNotAMultipleOfBlocksize},
		{enc.EncodeToString([]byte("123456789abcdef")), ErrorNotAMultipleOfBlocksize},
		{enc.EncodeToString([]byte("123456789abcdef0")), pkcs7.ErrorPaddingTooLong},
	} {
		actual, actualErr := c.decryptSegment(test.in)
		assert.Equal(t, test.expectedErr, actualErr, fmt.Sprintf("in=%q got actual=%q, err = %v %T", test.in, actual, actualErr, actualErr))
	}
}

func TestDecryptSegmentBase32768(t *testing.T) {
	// We've tested the forwards above, now concentrate on the errors
	longName := strings.Repeat("怪", 1280)
	enc, _ := NewNameEncoding("base32768")
	c, _ := newCipher(NameEncryptionStandard, "", "", true, enc)
	for _, test := range []struct {
		in          string
		expectedErr error
	}{
		{"怪=", base32768.CorruptInputError(1)},
		{"!", base32768.CorruptInputError(0)},
		{longName, ErrorTooLongAfterDecode},
		{enc.EncodeToString([]byte("a")), ErrorNotAMultipleOfBlocksize},
		{enc.EncodeToString([]byte("123456789abcdef")), ErrorNotAMultipleOfBlocksize},
		{enc.EncodeToString([]byte("123456789abcdef0")), pkcs7.ErrorPaddingTooLong},
	} {
		actual, actualErr := c.decryptSegment(test.in)
		assert.Equal(t, test.expectedErr, actualErr, fmt.Sprintf("in=%q got actual=%q, err = %v %T", test.in, actual, actualErr, actualErr))
	}
}

func testStandardEncryptFileName(t *testing.T, encoding string, testCasesEncryptDir []EncodingTestCase, testCasesNoEncryptDir []EncodingTestCase) {
	// First standard mode
	enc, _ := NewNameEncoding(encoding)
	c, _ := newCipher(NameEncryptionStandard, "", "", true, enc)
	for _, test := range testCasesEncryptDir {
		assert.Equal(t, test.expected, c.EncryptFileName(test.in))
	}
	// Standard mode with directory name encryption off
	c, _ = newCipher(NameEncryptionStandard, "", "", false, enc)
	for _, test := range testCasesNoEncryptDir {
		assert.Equal(t, test.expected, c.EncryptFileName(test.in))
	}
}

func TestStandardEncryptFileNameBase32(t *testing.T) {
	testStandardEncryptFileName(t, "base32", []EncodingTestCase{
		{"1", "p0e52nreeaj0a5ea7s64m4j72s"},
		{"1/12", "p0e52nreeaj0a5ea7s64m4j72s/l42g6771hnv3an9cgc8cr2n1ng"},
		{"1/12/123", "p0e52nreeaj0a5ea7s64m4j72s/l42g6771hnv3an9cgc8cr2n1ng/qgm4avr35m5loi1th53ato71v0"},
		{"1-v2001-02-03-040506-123", "p0e52nreeaj0a5ea7s64m4j72s-v2001-02-03-040506-123"},
		{"1/12-v2001-02-03-040506-123", "p0e52nreeaj0a5ea7s64m4j72s/l42g6771hnv3an9cgc8cr2n1ng-v2001-02-03-040506-123"},
	}, []EncodingTestCase{
		{"1", "p0e52nreeaj0a5ea7s64m4j72s"},
		{"1/12", "1/l42g6771hnv3an9cgc8cr2n1ng"},
		{"1/12/123", "1/12/qgm4avr35m5loi1th53ato71v0"},
		{"1-v2001-02-03-040506-123", "p0e52nreeaj0a5ea7s64m4j72s-v2001-02-03-040506-123"},
		{"1/12-v2001-02-03-040506-123", "1/l42g6771hnv3an9cgc8cr2n1ng-v2001-02-03-040506-123"},
	})
}

func TestStandardEncryptFileNameBase64(t *testing.T) {
	testStandardEncryptFileName(t, "base64", []EncodingTestCase{
		{"1", "yBxRX25ypgUVyj8MSxJnFw"},
		{"1/12", "yBxRX25ypgUVyj8MSxJnFw/qQUDHOGN_jVdLIMQzYrhvA"},
		{"1/12/123", "yBxRX25ypgUVyj8MSxJnFw/qQUDHOGN_jVdLIMQzYrhvA/1CxFf2Mti1xIPYlGruDh-A"},
		{"1-v2001-02-03-040506-123", "yBxRX25ypgUVyj8MSxJnFw-v2001-02-03-040506-123"},
		{"1/12-v2001-02-03-040506-123", "yBxRX25ypgUVyj8MSxJnFw/qQUDHOGN_jVdLIMQzYrhvA-v2001-02-03-040506-123"},
	}, []EncodingTestCase{
		{"1", "yBxRX25ypgUVyj8MSxJnFw"},
		{"1/12", "1/qQUDHOGN_jVdLIMQzYrhvA"},
		{"1/12/123", "1/12/1CxFf2Mti1xIPYlGruDh-A"},
		{"1-v2001-02-03-040506-123", "yBxRX25ypgUVyj8MSxJnFw-v2001-02-03-040506-123"},
		{"1/12-v2001-02-03-040506-123", "1/qQUDHOGN_jVdLIMQzYrhvA-v2001-02-03-040506-123"},
	})
}

func TestStandardEncryptFileNameBase32768(t *testing.T) {
	testStandardEncryptFileName(t, "base32768", []EncodingTestCase{
		{"1", "詮㪗鐮僀伎作㻖㢧⪟"},
		{"1/12", "詮㪗鐮僀伎作㻖㢧⪟/竢朧䉱虃光塬䟛⣡蓟"},
		{"1/12/123", "詮㪗鐮僀伎作㻖㢧⪟/竢朧䉱虃光塬䟛⣡蓟/遶㞟鋅缕袡鲅ⵝ蝁ꌟ"},
		{"1-v2001-02-03-040506-123", "詮㪗鐮僀伎作㻖㢧⪟-v2001-02-03-040506-123"},
		{"1/12-v2001-02-03-040506-123", "詮㪗鐮僀伎作㻖㢧⪟/竢朧䉱虃光塬䟛⣡蓟-v2001-02-03-040506-123"},
	}, []EncodingTestCase{
		{"1", "詮㪗鐮僀伎作㻖㢧⪟"},
		{"1/12", "1/竢朧䉱虃光塬䟛⣡蓟"},
		{"1/12/123", "1/12/遶㞟鋅缕袡鲅ⵝ蝁ꌟ"},
		{"1-v2001-02-03-040506-123", "詮㪗鐮僀伎作㻖㢧⪟-v2001-02-03-040506-123"},
		{"1/12-v2001-02-03-040506-123", "1/竢朧䉱虃光塬䟛⣡蓟-v2001-02-03-040506-123"},
	})
}

func TestNonStandardEncryptFileName(t *testing.T) {
	// Off mode
	c, _ := newCipher(NameEncryptionOff, "", "", true, nil)
	assert.Equal(t, "1/12/123.bin", c.EncryptFileName("1/12/123"))
	// Off mode with custom suffix
	c, _ = newCipher(NameEncryptionOff, "", "", true, nil)
	c.setEncryptedSuffix(".jpg")
	assert.Equal(t, "1/12/123.jpg", c.EncryptFileName("1/12/123"))
	// Off mode with empty suffix
	c.setEncryptedSuffix("none")
	assert.Equal(t, "1/12/123", c.EncryptFileName("1/12/123"))
	// Obfuscation mode
	c, _ = newCipher(NameEncryptionObfuscated, "", "", true, nil)
	assert.Equal(t, "49.6/99.23/150.890/53.!!lipps", c.EncryptFileName("1/12/123/!hello"))
	assert.Equal(t, "49.6/99.23/150.890/53-v2001-02-03-040506-123.!!lipps", c.EncryptFileName("1/12/123/!hello-v2001-02-03-040506-123"))
	assert.Equal(t, "49.6/99.23/150.890/162.uryyB-v2001-02-03-040506-123.GKG", c.EncryptFileName("1/12/123/hello-v2001-02-03-040506-123.txt"))
	assert.Equal(t, "161.\u00e4", c.EncryptFileName("\u00a1"))
	assert.Equal(t, "160.\u03c2", c.EncryptFileName("\u03a0"))
	// Obfuscation mode with directory name encryption off
	c, _ = newCipher(NameEncryptionObfuscated, "", "", false, nil)
	assert.Equal(t, "1/12/123/53.!!lipps", c.EncryptFileName("1/12/123/!hello"))
	assert.Equal(t, "1/12/123/53-v2001-02-03-040506-123.!!lipps", c.EncryptFileName("1/12/123/!hello-v2001-02-03-040506-123"))
	assert.Equal(t, "161.\u00e4", c.EncryptFileName("\u00a1"))
	assert.Equal(t, "160.\u03c2", c.EncryptFileName("\u03a0"))
}

func testStandardDecryptFileName(t *testing.T, encoding string, testCases []EncodingTestCase, caseInsensitive bool) {
	enc, _ := NewNameEncoding(encoding)
	for _, test := range testCases {
		// Test when dirNameEncrypt=true
		c, _ := newCipher(NameEncryptionStandard, "", "", true, enc)
		actual, actualErr := c.DecryptFileName(test.in)
		assert.NoError(t, actualErr)
		assert.Equal(t, test.expected, actual)
		if caseInsensitive {
			c, _ := newCipher(NameEncryptionStandard, "", "", true, enc)
			actual, actualErr := c.DecryptFileName(strings.ToUpper(test.in))
			assert.NoError(t, actualErr)
			assert.Equal(t, test.expected, actual)
		}
		// Add a character should raise ErrorNotAMultipleOfBlocksize
		actual, actualErr = c.DecryptFileName(enc.EncodeToString([]byte("1")) + test.in)
		assert.Equal(t, ErrorNotAMultipleOfBlocksize, actualErr)
		assert.Equal(t, "", actual)
		// Test when dirNameEncrypt=false
		noDirEncryptIn := test.in
		if strings.LastIndex(test.expected, "/") != -1 {
			noDirEncryptIn = test.expected[:strings.LastIndex(test.expected, "/")] + test.in[strings.LastIndex(test.in, "/"):]
		}
		c, _ = newCipher(NameEncryptionStandard, "", "", false, enc)
		actual, actualErr = c.DecryptFileName(noDirEncryptIn)
		assert.NoError(t, actualErr)
		assert.Equal(t, test.expected, actual)
	}
}

func TestStandardDecryptFileNameBase32(t *testing.T) {
	testStandardDecryptFileName(t, "base32", []EncodingTestCase{
		{"p0e52nreeaj0a5ea7s64m4j72s", "1"},
		{"p0e52nreeaj0a5ea7s64m4j72s/l42g6771hnv3an9cgc8cr2n1ng", "1/12"},
		{"p0e52nreeaj0a5ea7s64m4j72s/l42g6771hnv3an9cgc8cr2n1ng/qgm4avr35m5loi1th53ato71v0", "1/12/123"},
	}, true)
}

func TestStandardDecryptFileNameBase64(t *testing.T) {
	testStandardDecryptFileName(t, "base64", []EncodingTestCase{
		{"yBxRX25ypgUVyj8MSxJnFw", "1"},
		{"yBxRX25ypgUVyj8MSxJnFw/qQUDHOGN_jVdLIMQzYrhvA", "1/12"},
		{"yBxRX25ypgUVyj8MSxJnFw/qQUDHOGN_jVdLIMQzYrhvA/1CxFf2Mti1xIPYlGruDh-A", "1/12/123"},
	}, false)
}

func TestStandardDecryptFileNameBase32768(t *testing.T) {
	testStandardDecryptFileName(t, "base32768", []EncodingTestCase{
		{"詮㪗鐮僀伎作㻖㢧⪟", "1"},
		{"詮㪗鐮僀伎作㻖㢧⪟/竢朧䉱虃光塬䟛⣡蓟", "1/12"},
		{"詮㪗鐮僀伎作㻖㢧⪟/竢朧䉱虃光塬䟛⣡蓟/遶㞟鋅缕袡鲅ⵝ蝁ꌟ", "1/12/123"},
	}, false)
}

func TestNonStandardDecryptFileName(t *testing.T) {
	for _, encoding := range []string{"base32", "base64", "base32768"} {
		enc, _ := NewNameEncoding(encoding)
		for _, test := range []struct {
			mode           NameEncryptionMode
			dirNameEncrypt bool
			in             string
			expected       string
			expectedErr    error
			customSuffix   string
		}{
			{NameEncryptionOff, true, "1/12/123.bin", "1/12/123", nil, ""},
			{NameEncryptionOff, true, "1/12/123.bix", "", ErrorNotAnEncryptedFile, ""},
			{NameEncryptionOff, true, ".bin", "", ErrorNotAnEncryptedFile, ""},
			{NameEncryptionOff, true, "1/12/123-v2001-02-03-040506-123.bin", "1/12/123-v2001-02-03-040506-123", nil, ""},
			{NameEncryptionOff, true, "1/12/123-v1970-01-01-010101-123-v2001-02-03-040506-123.bin", "1/12/123-v1970-01-01-010101-123-v2001-02-03-040506-123", nil, ""},
			{NameEncryptionOff, true, "1/12/123-v1970-01-01-010101-123-v2001-02-03-040506-123.txt.bin", "1/12/123-v1970-01-01-010101-123-v2001-02-03-040506-123.txt", nil, ""},
			{NameEncryptionOff, true, "1/12/123.jpg", "1/12/123", nil, ".jpg"},
			{NameEncryptionOff, true, "1/12/123", "1/12/123", nil, "none"},
			{NameEncryptionObfuscated, true, "!.hello", "hello", nil, ""},
			{NameEncryptionObfuscated, true, "hello", "", ErrorNotAnEncryptedFile, ""},
			{NameEncryptionObfuscated, true, "161.\u00e4", "\u00a1", nil, ""},
			{NameEncryptionObfuscated, true, "160.\u03c2", "\u03a0", nil, ""},
			{NameEncryptionObfuscated, false, "1/12/123/53.!!lipps", "1/12/123/!hello", nil, ""},
			{NameEncryptionObfuscated, false, "1/12/123/53-v2001-02-03-040506-123.!!lipps", "1/12/123/!hello-v2001-02-03-040506-123", nil, ""},
		} {
			c, _ := newCipher(test.mode, "", "", test.dirNameEncrypt, enc)
			if test.customSuffix != "" {
				c.setEncryptedSuffix(test.customSuffix)
			}
			actual, actualErr := c.DecryptFileName(test.in)
			what := fmt.Sprintf("Testing %q (mode=%v)", test.in, test.mode)
			assert.Equal(t, test.expected, actual, what)
			assert.Equal(t, test.expectedErr, actualErr, what)
		}
	}
}

func TestEncDecMatches(t *testing.T) {
	for _, encoding := range []string{"base32", "base64", "base32768"} {
		enc, _ := NewNameEncoding(encoding)
		for _, test := range []struct {
			mode NameEncryptionMode
			in   string
		}{
			{NameEncryptionStandard, "1/2/3/4"},
			{NameEncryptionOff, "1/2/3/4"},
			{NameEncryptionObfuscated, "1/2/3/4/!hello\u03a0"},
			{NameEncryptionObfuscated, "Avatar The Last Airbender"},
		} {
			c, _ := newCipher(test.mode, "", "", true, enc)
			out, err := c.DecryptFileName(c.EncryptFileName(test.in))
			what := fmt.Sprintf("Testing %q (mode=%v)", test.in, test.mode)
			assert.Equal(t, out, test.in, what)
			assert.Equal(t, err, nil, what)
		}
	}
}

func testStandardEncryptDirName(t *testing.T, encoding string, testCases []EncodingTestCase) {
	enc, _ := NewNameEncoding(encoding)
	c, _ := newCipher(NameEncryptionStandard, "", "", true, enc)
	// First standard mode
	for _, test := range testCases {
		assert.Equal(t, test.expected, c.EncryptDirName(test.in))
	}
}

func TestStandardEncryptDirNameBase32(t *testing.T) {
	testStandardEncryptDirName(t, "base32", []EncodingTestCase{
		{"1", "p0e52nreeaj0a5ea7s64m4j72s"},
		{"1/12", "p0e52nreeaj0a5ea7s64m4j72s/l42g6771hnv3an9cgc8cr2n1ng"},
		{"1/12/123", "p0e52nreeaj0a5ea7s64m4j72s/l42g6771hnv3an9cgc8cr2n1ng/qgm4avr35m5loi1th53ato71v0"},
	})
}

func TestStandardEncryptDirNameBase64(t *testing.T) {
	testStandardEncryptDirName(t, "base64", []EncodingTestCase{
		{"1", "yBxRX25ypgUVyj8MSxJnFw"},
		{"1/12", "yBxRX25ypgUVyj8MSxJnFw/qQUDHOGN_jVdLIMQzYrhvA"},
		{"1/12/123", "yBxRX25ypgUVyj8MSxJnFw/qQUDHOGN_jVdLIMQzYrhvA/1CxFf2Mti1xIPYlGruDh-A"},
	})
}

func TestStandardEncryptDirNameBase32768(t *testing.T) {
	testStandardEncryptDirName(t, "base32768", []EncodingTestCase{
		{"1", "詮㪗鐮僀伎作㻖㢧⪟"},
		{"1/12", "詮㪗鐮僀伎作㻖㢧⪟/竢朧䉱虃光塬䟛⣡蓟"},
		{"1/12/123", "詮㪗鐮僀伎作㻖㢧⪟/竢朧䉱虃光塬䟛⣡蓟/遶㞟鋅缕袡鲅ⵝ蝁ꌟ"},
	})
}

func TestNonStandardEncryptDirName(t *testing.T) {
	for _, encoding := range []string{"base32", "base64", "base32768"} {
		enc, _ := NewNameEncoding(encoding)
		c, _ := newCipher(NameEncryptionStandard, "", "", false, enc)
		assert.Equal(t, "1/12", c.EncryptDirName("1/12"))
		assert.Equal(t, "1/12/123", c.EncryptDirName("1/12/123"))
		// Now off mode
		c, _ = newCipher(NameEncryptionOff, "", "", true, enc)
		assert.Equal(t, "1/12/123", c.EncryptDirName("1/12/123"))
	}
}

func testStandardDecryptDirName(t *testing.T, encoding string, testCases []EncodingTestCase, caseInsensitive bool) {
	enc, _ := NewNameEncoding(encoding)
	for _, test := range testCases {
		// Test dirNameEncrypt=true
		c, _ := newCipher(NameEncryptionStandard, "", "", true, enc)
		actual, actualErr := c.DecryptDirName(test.in)
		assert.Equal(t, test.expected, actual)
		assert.NoError(t, actualErr)
		if caseInsensitive {
			actual, actualErr := c.DecryptDirName(strings.ToUpper(test.in))
			assert.Equal(t, actual, test.expected)
			assert.NoError(t, actualErr)
		}
		actual, actualErr = c.DecryptDirName(enc.EncodeToString([]byte("1")) + test.in)
		assert.Equal(t, "", actual)
		assert.Equal(t, ErrorNotAMultipleOfBlocksize, actualErr)
		// Test dirNameEncrypt=false
		c, _ = newCipher(NameEncryptionStandard, "", "", false, enc)
		actual, actualErr = c.DecryptDirName(test.in)
		assert.Equal(t, test.in, actual)
		assert.NoError(t, actualErr)
		actual, actualErr = c.DecryptDirName(test.expected)
		assert.Equal(t, test.expected, actual)
		assert.NoError(t, actualErr)
		// Test dirNameEncrypt=false
	}
}

/*
enc, _ := NewNameEncoding(encoding)
for _, test := range []struct {
	mode           NameEncryptionMode
	dirNameEncrypt bool
	in             string
	expected       string
	expectedErr    error
}{
	{NameEncryptionStandard, true, "p0e52nreeaj0a5ea7s64m4j72s", "1", nil},
	{NameEncryptionStandard, true, "p0e52nreeaj0a5ea7s64m4j72s/l42g6771hnv3an9cgc8cr2n1ng", "1/12", nil},
	{NameEncryptionStandard, true, "p0e52nreeAJ0A5EA7S64M4J72S/L42G6771HNv3an9cgc8cr2n1ng", "1/12", nil},
	{NameEncryptionStandard, true, "p0e52nreeaj0a5ea7s64m4j72s/l42g6771hnv3an9cgc8cr2n1ng/qgm4avr35m5loi1th53ato71v0", "1/12/123", nil},
	{NameEncryptionStandard, true, "p0e52nreeaj0a5ea7s64m4j72s/l42g6771hnv3an9cgc8cr2n1/qgm4avr35m5loi1th53ato71v0", "", ErrorNotAMultipleOfBlocksize},
	{NameEncryptionStandard, false, "p0e52nreeaj0a5ea7s64m4j72s/l42g6771hnv3an9cgc8cr2n1ng", "p0e52nreeaj0a5ea7s64m4j72s/l42g6771hnv3an9cgc8cr2n1ng", nil},
	{NameEncryptionStandard, false, "1/12/123", "1/12/123", nil},
} {
	c, _ := newCipher(test.mode, "", "", test.dirNameEncrypt, enc)
	actual, actualErr := c.DecryptDirName(test.in)
	what := fmt.Sprintf("Testing %q (mode=%v)", test.in, test.mode)
	assert.Equal(t, test.expected, actual, what)
	assert.Equal(t, test.expectedErr, actualErr, what)
}
*/

func TestStandardDecryptDirNameBase32(t *testing.T) {
	testStandardDecryptDirName(t, "base32", []EncodingTestCase{
		{"p0e52nreeaj0a5ea7s64m4j72s", "1"},
		{"p0e52nreeaj0a5ea7s64m4j72s/l42g6771hnv3an9cgc8cr2n1ng", "1/12"},
		{"p0e52nreeaj0a5ea7s64m4j72s/l42g6771hnv3an9cgc8cr2n1ng/qgm4avr35m5loi1th53ato71v0", "1/12/123"},
	}, true)
}

func TestStandardDecryptDirNameBase64(t *testing.T) {
	testStandardDecryptDirName(t, "base64", []EncodingTestCase{
		{"yBxRX25ypgUVyj8MSxJnFw", "1"},
		{"yBxRX25ypgUVyj8MSxJnFw/qQUDHOGN_jVdLIMQzYrhvA", "1/12"},
		{"yBxRX25ypgUVyj8MSxJnFw/qQUDHOGN_jVdLIMQzYrhvA/1CxFf2Mti1xIPYlGruDh-A", "1/12/123"},
	}, false)
}

func TestStandardDecryptDirNameBase32768(t *testing.T) {
	testStandardDecryptDirName(t, "base32768", []EncodingTestCase{
		{"詮㪗鐮僀伎作㻖㢧⪟", "1"},
		{"詮㪗鐮僀伎作㻖㢧⪟/竢朧䉱虃光塬䟛⣡蓟", "1/12"},
		{"詮㪗鐮僀伎作㻖㢧⪟/竢朧䉱虃光塬䟛⣡蓟/遶㞟鋅缕袡鲅ⵝ蝁ꌟ", "1/12/123"},
	}, false)
}

func TestNonStandardDecryptDirName(t *testing.T) {
	for _, test := range []struct {
		mode           NameEncryptionMode
		dirNameEncrypt bool
		in             string
		expected       string
		expectedErr    error
	}{
		{NameEncryptionOff, true, "1/12/123.bin", "1/12/123.bin", nil},
		{NameEncryptionOff, true, "1/12/123", "1/12/123", nil},
		{NameEncryptionOff, true, ".bin", ".bin", nil},
	} {
		c, _ := newCipher(test.mode, "", "", test.dirNameEncrypt, nil)
		actual, actualErr := c.DecryptDirName(test.in)
		what := fmt.Sprintf("Testing %q (mode=%v)", test.in, test.mode)
		assert.Equal(t, test.expected, actual, what)
		assert.Equal(t, test.expectedErr, actualErr, what)
	}
}

func TestEncryptedSize(t *testing.T) {
	c, _ := newCipher(NameEncryptionStandard, "", "", true, nil)
	for _, test := range []struct {
		in       int64
		expected int64
	}{
		{0, 32},
		{1, 32 + 16 + 1},
		{65536, 32 + 16 + 65536},
		{65537, 32 + 16 + 65536 + 16 + 1},
		{1 << 20, 32 + 16*(16+65536)},
		{(1 << 20) + 65535, 32 + 16*(16+65536) + 16 + 65535},
		{1 << 30, 32 + 16384*(16+65536)},
		{(1 << 40) + 1, 32 + 16777216*(16+65536) + 16 + 1},
	} {
		actual := c.EncryptedSize(test.in)
		assert.Equal(t, test.expected, actual, fmt.Sprintf("Testing %d", test.in))
		recovered, err := c.DecryptedSize(test.expected)
		assert.NoError(t, err, fmt.Sprintf("Testing reverse %d", test.expected))
		assert.Equal(t, test.in, recovered, fmt.Sprintf("Testing reverse %d", test.expected))
	}
}

func TestDecryptedSize(t *testing.T) {
	// Test the errors since we tested the reverse above
	c, _ := newCipher(NameEncryptionStandard, "", "", true, nil)
	for _, test := range []struct {
		in          int64
		expectedErr error
	}{
		{0, ErrorEncryptedFileTooShort},
		{0, ErrorEncryptedFileTooShort},
		{1, ErrorEncryptedFileTooShort},
		{7, ErrorEncryptedFileTooShort},
		{32 + 1, ErrorEncryptedFileBadHeader},
		{32 + 16, ErrorEncryptedFileBadHeader},
		{32 + 16 + 65536 + 1, ErrorEncryptedFileBadHeader},
		{32 + 16 + 65536 + 16, ErrorEncryptedFileBadHeader},
	} {
		_, actualErr := c.DecryptedSize(test.in)
		assert.Equal(t, test.expectedErr, actualErr, fmt.Sprintf("Testing %d", test.in))
	}
}

func TestNoncePointer(t *testing.T) {
	var x nonce
	assert.Equal(t, (*[24]byte)(&x), x.pointer())
}

func TestNonceFromReader(t *testing.T) {
	var x nonce
	buf := bytes.NewBufferString("123456789abcdefghijklmno")
	err := x.fromReader(buf)
	assert.NoError(t, err)
	assert.Equal(t, nonce{'1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o'}, x)
	buf = bytes.NewBufferString("123456789abcdefghijklmn")
	err = x.fromReader(buf)
	assert.EqualError(t, err, "short read of nonce: EOF")
}

func TestNonceFromBuf(t *testing.T) {
	var x nonce
	buf := []byte("123456789abcdefghijklmnoXXXXXXXX")
	x.fromBuf(buf)
	assert.Equal(t, nonce{'1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o'}, x)
	buf = []byte("0123456789abcdefghijklmn")
	x.fromBuf(buf)
	assert.Equal(t, nonce{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n'}, x)
	buf = []byte("0123456789abcdefghijklm")
	assert.Panics(t, func() { x.fromBuf(buf) })
}

func TestNonceIncrement(t *testing.T) {
	for _, test := range []struct {
		in  nonce
		out nonce
	}{
		{
			nonce{0x00},
			nonce{0x01},
		},
		{
			nonce{0xFF},
			nonce{0x00, 0x01},
		},
		{
			nonce{0xFF, 0xFF},
			nonce{0x00, 0x00, 0x01},
		},
		{
			nonce{0xFF, 0xFF, 0xFF},
			nonce{0x00, 0x00, 0x00, 0x01},
		},
		{
			nonce{0xFF, 0xFF, 0xFF, 0xFF},
			nonce{0x00, 0x00, 0x00, 0x00, 0x01},
		},
		{
			nonce{0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
			nonce{0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
		},
		{
			nonce{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
			nonce{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
		},
		{
			nonce{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
			nonce{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
		},
		{
			nonce{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
			nonce{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
		},
		{
			nonce{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
			nonce{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
		},
		{
			nonce{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
			nonce{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
		},
		{
			nonce{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
			nonce{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
		},
		{
			nonce{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
			nonce{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
		},
		{
			nonce{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
			nonce{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
		},
		{
			nonce{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
			nonce{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
		},
		{
			nonce{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
			nonce{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
		},
		{
			nonce{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
			nonce{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
		},
		{
			nonce{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
			nonce{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
		},
		{
			nonce{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
			nonce{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
		},
		{
			nonce{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
			nonce{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
		},
		{
			nonce{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
			nonce{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
		},
		{
			nonce{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
			nonce{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
		},
		{
			nonce{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
			nonce{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
		},
		{
			nonce{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
			nonce{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
		},
		{
			nonce{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
			nonce{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
		},
	} {
		x := test.in
		x.increment()
		assert.Equal(t, test.out, x)
	}
}

func TestNonceAdd(t *testing.T) {
	for _, test := range []struct {
		add uint64
		in  nonce
		out nonce
	}{
		{
			0x01,
			nonce{0x00},
			nonce{0x01},
		},
		{
			0xFF,
			nonce{0xFF},
			nonce{0xFE, 0x01},
		},
		{
			0xFFFF,
			nonce{0xFF, 0xFF},
			nonce{0xFE, 0xFF, 0x01},
		},
		{
			0xFFFFFF,
			nonce{0xFF, 0xFF, 0xFF},
			nonce{0xFE, 0xFF, 0xFF, 0x01},
		},
		{
			0xFFFFFFFF,
			nonce{0xFF, 0xFF, 0xFF, 0xFF},
			nonce{0xFe, 0xFF, 0xFF, 0xFF, 0x01},
		},
		{
			0xFFFFFFFFFF,
			nonce{0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
			nonce{0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0x01},
		},
		{
			0xFFFFFFFFFFFF,
			nonce{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
			nonce{0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01},
		},
		{
			0xFFFFFFFFFFFFFF,
			nonce{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
			nonce{0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01},
		},
		{
			0xFFFFFFFFFFFFFFFF,
			nonce{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
			nonce{0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01},
		},
		{
			0xFFFFFFFFFFFFFFFF,
			nonce{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
			nonce{0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x01},
		},
		{
			0xFFFFFFFFFFFFFFFF,
			nonce{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
			nonce{0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x01},
		},
		{
			0xFFFFFFFFFFFFFFFF,
			nonce{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
			nonce{0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x01},
		},
		{
			0xFFFFFFFFFFFFFFFF,
			nonce{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
			nonce{0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x01},
		},
		{
			0xFFFFFFFFFFFFFFFF,
			nonce{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
			nonce{0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
		},
		{
			0xFFFFFFFFFFFFFFFF,
			nonce{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
			nonce{0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
		},
		{
			0xFFFFFFFFFFFFFFFF,
			nonce{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
			nonce{0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
		},
		{
			0xFFFFFFFFFFFFFFFF,
			nonce{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
			nonce{0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
		},
		{
			0xFFFFFFFFFFFFFFFF,
			nonce{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
			nonce{0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
		},
		{
			0xFFFFFFFFFFFFFFFF,
			nonce{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
			nonce{0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
		},
		{
			0xFFFFFFFFFFFFFFFF,
			nonce{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
			nonce{0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
		},
		{
			0xFFFFFFFFFFFFFFFF,
			nonce{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
			nonce{0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
		},
		{
			0xFFFFFFFFFFFFFFFF,
			nonce{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
			nonce{0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
		},
		{
			0xFFFFFFFFFFFFFFFF,
			nonce{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
			nonce{0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
		},
		{
			0xFFFFFFFFFFFFFFFF,
			nonce{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
			nonce{0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
		},
		{
			0xFFFFFFFFFFFFFFFF,
			nonce{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
			nonce{0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
		},
	} {
		x := test.in
		x.add(test.add)
		assert.Equal(t, test.out, x)
	}
}

// randomSource can read or write a random sequence
type randomSource struct {
	counter int64
	size    int64
}

func newRandomSource(size int64) *randomSource {
	return &randomSource{
		size: size,
	}
}

func (r *randomSource) next() byte {
	r.counter++
	return byte(r.counter % 257)
}

func (r *randomSource) Read(p []byte) (n int, err error) {
	for i := range p {
		if r.counter >= r.size {
			err = io.EOF
			break
		}
		p[i] = r.next()
		n++
	}
	return n, err
}

func (r *randomSource) Write(p []byte) (n int, err error) {
	for i := range p {
		if p[i] != r.next() {
			return 0, fmt.Errorf("Error in stream at %d", r.counter)
		}
	}
	return len(p), nil
}

func (r *randomSource) Close() error { return nil }

// Check interfaces
var (
	_ io.ReadCloser  = (*randomSource)(nil)
	_ io.WriteCloser = (*randomSource)(nil)
)

// Test test infrastructure first!
func TestRandomSource(t *testing.T) {
	source := newRandomSource(1e8)
	sink := newRandomSource(1e8)
	n, err := io.Copy(sink, source)
	assert.NoError(t, err)
	assert.Equal(t, int64(1e8), n)

	source = newRandomSource(1e8)
	buf := make([]byte, 16)
	_, _ = source.Read(buf)
	sink = newRandomSource(1e8)
	_, err = io.Copy(sink, source)
	assert.EqualError(t, err, "Error in stream at 1")
}

type zeroes struct{}

func (z *zeroes) Read(p []byte) (n int, err error) {
	for i := range p {
		p[i] = 0
		n++
	}
	return n, nil
}

// Test encrypt decrypt with different buffer sizes
func testEncryptDecrypt(t *testing.T, bufSize int, copySize int64) {
	c, err := newCipher(NameEncryptionStandard, "", "", true, nil)
	assert.NoError(t, err)
	c.cryptoRand = &zeroes{} // zero out the nonce
	buf := make([]byte, bufSize)
	source := newRandomSource(copySize)
	encrypted, err := c.newEncrypter(source, nil)
	assert.NoError(t, err)
	decrypted, err := c.newDecrypter(io.NopCloser(encrypted))
	assert.NoError(t, err)
	sink := newRandomSource(copySize)
	n, err := io.CopyBuffer(sink, decrypted, buf)
	assert.NoError(t, err)
	assert.Equal(t, copySize, n)
	blocks := copySize / blockSize
	if (copySize % blockSize) != 0 {
		blocks++
	}
	var expectedNonce = nonce{byte(blocks), byte(blocks >> 8), byte(blocks >> 16), byte(blocks >> 32)}
	assert.Equal(t, expectedNonce, encrypted.nonce)
	assert.Equal(t, expectedNonce, decrypted.nonce)
}

func TestEncryptDecrypt1(t *testing.T) {
	testEncryptDecrypt(t, 1, 1e7)
}

func TestEncryptDecrypt32(t *testing.T) {
	testEncryptDecrypt(t, 32, 1e8)
}

func TestEncryptDecrypt4096(t *testing.T) {
	testEncryptDecrypt(t, 4096, 1e8)
}

func TestEncryptDecrypt65536(t *testing.T) {
	testEncryptDecrypt(t, 65536, 1e8)
}

func TestEncryptDecrypt65537(t *testing.T) {
	testEncryptDecrypt(t, 65537, 1e8)
}

var (
	file0 = []byte{
		0x52, 0x43, 0x4c, 0x4f, 0x4e, 0x45, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
		0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,
	}
	file1 = []byte{
		0x52, 0x43, 0x4c, 0x4f, 0x4e, 0x45, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
		0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,
		0x09, 0x5b, 0x44, 0x6c, 0xd6, 0x23, 0x7b, 0xbc, 0xb0, 0x8d, 0x09, 0xfb, 0x52, 0x4c, 0xe5, 0x65,
		0xAA,
	}
	file16 = []byte{
		0x52, 0x43, 0x4c, 0x4f, 0x4e, 0x45, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
		0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,
		0xb9, 0xc4, 0x55, 0x2a, 0x27, 0x10, 0x06, 0x29, 0x18, 0x96, 0x0a, 0x3e, 0x60, 0x8c, 0x29, 0xb9,
		0xaa, 0x8a, 0x5e, 0x1e, 0x16, 0x5b, 0x6d, 0x07, 0x5d, 0xe4, 0xe9, 0xbb, 0x36, 0x7f, 0xd6, 0xd4,
	}
)

func TestEncryptData(t *testing.T) {
	for _, test := range []struct {
		in       []byte
		expected []byte
	}{
		{[]byte{}, file0},
		{[]byte{1}, file1},
		{[]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}, file16},
	} {
		c, err := newCipher(NameEncryptionStandard, "", "", true, nil)
		assert.NoError(t, err)
		c.cryptoRand = newRandomSource(1e8) // nodge the crypto rand generator

		// Check encode works
		buf := bytes.NewBuffer(test.in)
		encrypted, err := c.EncryptData(buf)
		assert.NoError(t, err)
		out, err := io.ReadAll(encrypted)
		assert.NoError(t, err)
		assert.Equal(t, test.expected, out)

		// Check we can decode the data properly too...
		buf = bytes.NewBuffer(out)
		decrypted, err := c.DecryptData(io.NopCloser(buf))
		assert.NoError(t, err)
		out, err = io.ReadAll(decrypted)
		assert.NoError(t, err)
		assert.Equal(t, test.in, out)
	}
}

func TestNewEncrypter(t *testing.T) {
	c, err := newCipher(NameEncryptionStandard, "", "", true, nil)
	assert.NoError(t, err)
	c.cryptoRand = newRandomSource(1e8) // nodge the crypto rand generator

	z := &zeroes{}

	fh, err := c.newEncrypter(z, nil)
	assert.NoError(t, err)
	assert.Equal(t, nonce{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18}, fh.nonce)
	assert.Equal(t, []byte{'R', 'C', 'L', 'O', 'N', 'E', 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18}, (*fh.buf)[:32])

	// Test error path
	c.cryptoRand = bytes.NewBufferString("123456789abcdefghijklmn")
	fh, err = c.newEncrypter(z, nil)
	assert.Nil(t, fh)
	assert.EqualError(t, err, "short read of nonce: EOF")
}

// Test the stream returning 0, io.ErrUnexpectedEOF - this used to
// cause a fatal loop
func TestNewEncrypterErrUnexpectedEOF(t *testing.T) {
	c, err := newCipher(NameEncryptionStandard, "", "", true, nil)
	assert.NoError(t, err)

	in := &readers.ErrorReader{Err: io.ErrUnexpectedEOF}
	fh, err := c.newEncrypter(in, nil)
	assert.NoError(t, err)

	n, err := io.CopyN(io.Discard, fh, 1e6)
	assert.Equal(t, io.ErrUnexpectedEOF, err)
	assert.Equal(t, int64(32), n)
}

type closeDetector struct {
	io.Reader
	closed int
}

func newCloseDetector(in io.Reader) *closeDetector {
	return &closeDetector{
		Reader: in,
	}
}

func (c *closeDetector) Close() error {
	c.closed++
	return nil
}

func TestNewDecrypter(t *testing.T) {
	c, err := newCipher(NameEncryptionStandard, "", "", true, nil)
	assert.NoError(t, err)
	c.cryptoRand = newRandomSource(1e8) // nodge the crypto rand generator

	cd := newCloseDetector(bytes.NewBuffer(file0))
	fh, err := c.newDecrypter(cd)
	assert.NoError(t, err)
	// check nonce is in place
	assert.Equal(t, file0[8:32], fh.nonce[:])
	assert.Equal(t, 0, cd.closed)

	// Test error paths
	for i := range file0 {
		cd := newCloseDetector(bytes.NewBuffer(file0[:i]))
		fh, err = c.newDecrypter(cd)
		assert.Nil(t, fh)
		assert.EqualError(t, err, ErrorEncryptedFileTooShort.Error())
		assert.Equal(t, 1, cd.closed)
	}

	er := &readers.ErrorReader{Err: errors.New("potato")}
	cd = newCloseDetector(er)
	fh, err = c.newDecrypter(cd)
	assert.Nil(t, fh)
	assert.EqualError(t, err, "potato")
	assert.Equal(t, 1, cd.closed)

	// bad magic
	file0copy := make([]byte, len(file0))
	copy(file0copy, file0)
	for i := range fileMagic {
		file0copy[i] ^= 0x1
		cd := newCloseDetector(bytes.NewBuffer(file0copy))
		fh, err := c.newDecrypter(cd)
		assert.Nil(t, fh)
		assert.EqualError(t, err, ErrorEncryptedBadMagic.Error())
		file0copy[i] ^= 0x1
		assert.Equal(t, 1, cd.closed)
	}
}

// Test the stream returning 0, io.ErrUnexpectedEOF
func TestNewDecrypterErrUnexpectedEOF(t *testing.T) {
	c, err := newCipher(NameEncryptionStandard, "", "", true, nil)
	assert.NoError(t, err)

	in2 := &readers.ErrorReader{Err: io.ErrUnexpectedEOF}
	in1 := bytes.NewBuffer(file16)
	in := io.NopCloser(io.MultiReader(in1, in2))

	fh, err := c.newDecrypter(in)
	assert.NoError(t, err)

	n, err := io.CopyN(io.Discard, fh, 1e6)
	assert.Equal(t, io.ErrUnexpectedEOF, err)
	assert.Equal(t, int64(16), n)
}

func TestNewDecrypterSeekLimit(t *testing.T) {
	c, err := newCipher(NameEncryptionStandard, "", "", true, nil)
	assert.NoError(t, err)
	c.cryptoRand = &zeroes{} // nodge the crypto rand generator

	// Make random data
	const dataSize = 150000
	plaintext, err := io.ReadAll(newRandomSource(dataSize))
	assert.NoError(t, err)

	// Encrypt the data
	buf := bytes.NewBuffer(plaintext)
	encrypted, err := c.EncryptData(buf)
	assert.NoError(t, err)
	ciphertext, err := io.ReadAll(encrypted)
	assert.NoError(t, err)

	trials := []int{0, 1, 2, 3, 4, 5, 7, 8, 9, 15, 16, 17, 31, 32, 33, 63, 64, 65,
		127, 128, 129, 255, 256, 257, 511, 512, 513, 1023, 1024, 1025, 2047, 2048, 2049,
		4095, 4096, 4097, 8191, 8192, 8193, 16383, 16384, 16385, 32767, 32768, 32769,
		65535, 65536, 65537, 131071, 131072, 131073, dataSize - 1, dataSize}
	limits := []int{-1, 0, 1, 65535, 65536, 65537, 131071, 131072, 131073}

	// Open stream with a seek of underlyingOffset
	var reader io.ReadCloser
	open := func(ctx context.Context, underlyingOffset, underlyingLimit int64) (io.ReadCloser, error) {
		end := len(ciphertext)
		if underlyingLimit >= 0 {
			end = int(underlyingOffset + underlyingLimit)
			if end > len(ciphertext) {
				end = len(ciphertext)
			}
		}
		reader = io.NopCloser(bytes.NewBuffer(ciphertext[int(underlyingOffset):end]))
		return reader, nil
	}

	inBlock := make([]byte, dataSize)

	// Check the seek worked by reading a block and checking it
	// against what it should be
	check := func(rc io.Reader, offset, limit int) {
		n, err := io.ReadFull(rc, inBlock)
		if err != nil && err != io.EOF && err != io.ErrUnexpectedEOF {
			require.NoError(t, err)
		}
		seekedDecrypted := inBlock[:n]

		what := fmt.Sprintf("offset = %d, limit = %d", offset, limit)
		if limit >= 0 {
			assert.Equal(t, limit, n, what)
		}
		require.Equal(t, plaintext[offset:offset+n], seekedDecrypted, what)

		// We should have completely emptied the reader at this point
		n, err = reader.Read(inBlock)
		assert.Equal(t, io.EOF, err)
		assert.Equal(t, 0, n)
	}

	// Now try decoding it with an open/seek
	for _, offset := range trials {
		for _, limit := range limits {
			if offset+limit > len(plaintext) {
				continue
			}
			rc, err := c.DecryptDataSeek(context.Background(), open, int64(offset), int64(limit))
			assert.NoError(t, err)

			check(rc, offset, limit)
		}
	}

	// Try decoding it with a single open and lots of seeks
	fh, err := c.DecryptDataSeek(context.Background(), open, 0, -1)
	assert.NoError(t, err)
	for _, offset := range trials {
		for _, limit := range limits {
			if offset+limit > len(plaintext) {
				continue
			}
			_, err := fh.RangeSeek(context.Background(), int64(offset), io.SeekStart, int64(limit))
			assert.NoError(t, err)

			check(fh, offset, limit)
		}
	}

	// Do some checks on the open callback
	for _, test := range []struct {
		offset, limit         int64
		wantOffset, wantLimit int64
	}{
		// unlimited
		{0, -1, int64(fileHeaderSize), -1},
		{1, -1, int64(fileHeaderSize), -1},
		{blockDataSize - 1, -1, int64(fileHeaderSize), -1},
		{blockDataSize, -1, int64(fileHeaderSize) + blockSize, -1},
		{blockDataSize + 1, -1, int64(fileHeaderSize) + blockSize, -1},
		// limit=1
		{0, 1, int64(fileHeaderSize), blockSize},
		{1, 1, int64(fileHeaderSize), blockSize},
		{blockDataSize - 1, 1, int64(fileHeaderSize), blockSize},
		{blockDataSize, 1, int64(fileHeaderSize) + blockSize, blockSize},
		{blockDataSize + 1, 1, int64(fileHeaderSize) + blockSize, blockSize},
		// limit=100
		{0, 100, int64(fileHeaderSize), blockSize},
		{1, 100, int64(fileHeaderSize), blockSize},
		{blockDataSize - 1, 100, int64(fileHeaderSize), 2 * blockSize},
		{blockDataSize, 100, int64(fileHeaderSize) + blockSize, blockSize},
		{blockDataSize + 1, 100, int64(fileHeaderSize) + blockSize, blockSize},
		// limit=blockDataSize-1
		{0, blockDataSize - 1, int64(fileHeaderSize), blockSize},
		{1, blockDataSize - 1, int64(fileHeaderSize), blockSize},
		{blockDataSize - 1, blockDataSize - 1, int64(fileHeaderSize), 2 * blockSize},
		{blockDataSize, blockDataSize - 1, int64(fileHeaderSize) + blockSize, blockSize},
		{blockDataSize + 1, blockDataSize - 1, int64(fileHeaderSize) + blockSize, blockSize},
		// limit=blockDataSize
		{0, blockDataSize, int64(fileHeaderSize), blockSize},
		{1, blockDataSize, int64(fileHeaderSize), 2 * blockSize},
		{blockDataSize - 1, blockDataSize, int64(fileHeaderSize), 2 * blockSize},
		{blockDataSize, blockDataSize, int64(fileHeaderSize) + blockSize, blockSize},
		{blockDataSize + 1, blockDataSize, int64(fileHeaderSize) + blockSize, 2 * blockSize},
		// limit=blockDataSize+1
		{0, blockDataSize + 1, int64(fileHeaderSize), 2 * blockSize},
		{1, blockDataSize + 1, int64(fileHeaderSize), 2 * blockSize},
		{blockDataSize - 1, blockDataSize + 1, int64(fileHeaderSize), 2 * blockSize},
		{blockDataSize, blockDataSize + 1, int64(fileHeaderSize) + blockSize, 2 * blockSize},
		{blockDataSize + 1, blockDataSize + 1, int64(fileHeaderSize) + blockSize, 2 * blockSize},
	} {
		what := fmt.Sprintf("offset = %d, limit = %d", test.offset, test.limit)
		callCount := 0
		testOpen := func(ctx context.Context, underlyingOffset, underlyingLimit int64) (io.ReadCloser, error) {
			switch callCount {
			case 0:
				assert.Equal(t, int64(0), underlyingOffset, what)
				assert.Equal(t, int64(-1), underlyingLimit, what)
			case 1:
				assert.Equal(t, test.wantOffset, underlyingOffset, what)
				assert.Equal(t, test.wantLimit, underlyingLimit, what)
			default:
				t.Errorf("Too many calls %d for %s", callCount+1, what)
			}
			callCount++
			return open(ctx, underlyingOffset, underlyingLimit)
		}
		fh, err := c.DecryptDataSeek(context.Background(), testOpen, 0, -1)
		assert.NoError(t, err)
		gotOffset, err := fh.RangeSeek(context.Background(), test.offset, io.SeekStart, test.limit)
		assert.NoError(t, err)
		assert.Equal(t, gotOffset, test.offset)
	}
}

func TestDecrypterCalculateUnderlying(t *testing.T) {
	for _, test := range []struct {
		offset, limit           int64
		wantOffset, wantLimit   int64
		wantDiscard, wantBlocks int64
	}{
		// unlimited
		{0, -1, int64(fileHeaderSize), -1, 0, 0},
		{1, -1, int64(fileHeaderSize), -1, 1, 0},
		{blockDataSize - 1, -1, int64(fileHeaderSize), -1, blockDataSize - 1, 0},
		{blockDataSize, -1, int64(fileHeaderSize) + blockSize, -1, 0, 1},
		{blockDataSize + 1, -1, int64(fileHeaderSize) + blockSize, -1, 1, 1},
		// limit=1
		{0, 1, int64(fileHeaderSize), blockSize, 0, 0},
		{1, 1, int64(fileHeaderSize), blockSize, 1, 0},
		{blockDataSize - 1, 1, int64(fileHeaderSize), blockSize, blockDataSize - 1, 0},
		{blockDataSize, 1, int64(fileHeaderSize) + blockSize, blockSize, 0, 1},
		{blockDataSize + 1, 1, int64(fileHeaderSize) + blockSize, blockSize, 1, 1},
		// limit=100
		{0, 100, int64(fileHeaderSize), blockSize, 0, 0},
		{1, 100, int64(fileHeaderSize), blockSize, 1, 0},
		{blockDataSize - 1, 100, int64(fileHeaderSize), 2 * blockSize, blockDataSize - 1, 0},
		{blockDataSize, 100, int64(fileHeaderSize) + blockSize, blockSize, 0, 1},
		{blockDataSize + 1, 100, int64(fileHeaderSize) + blockSize, blockSize, 1, 1},
		// limit=blockDataSize-1
		{0, blockDataSize - 1, int64(fileHeaderSize), blockSize, 0, 0},
		{1, blockDataSize - 1, int64(fileHeaderSize), blockSize, 1, 0},
		{blockDataSize - 1, blockDataSize - 1, int64(fileHeaderSize), 2 * blockSize, blockDataSize - 1, 0},
		{blockDataSize, blockDataSize - 1, int64(fileHeaderSize) + blockSize, blockSize, 0, 1},
		{blockDataSize + 1, blockDataSize - 1, int64(fileHeaderSize) + blockSize, blockSize, 1, 1},
		// limit=blockDataSize
		{0, blockDataSize, int64(fileHeaderSize), blockSize, 0, 0},
		{1, blockDataSize, int64(fileHeaderSize), 2 * blockSize, 1, 0},
		{blockDataSize - 1, blockDataSize, int64(fileHeaderSize), 2 * blockSize, blockDataSize - 1, 0},
		{blockDataSize, blockDataSize, int64(fileHeaderSize) + blockSize, blockSize, 0, 1},
		{blockDataSize + 1, blockDataSize, int64(fileHeaderSize) + blockSize, 2 * blockSize, 1, 1},
		// limit=blockDataSize+1
		{0, blockDataSize + 1, int64(fileHeaderSize), 2 * blockSize, 0, 0},
		{1, blockDataSize + 1, int64(fileHeaderSize), 2 * blockSize, 1, 0},
		{blockDataSize - 1, blockDataSize + 1, int64(fileHeaderSize), 2 * blockSize, blockDataSize - 1, 0},
		{blockDataSize, blockDataSize + 1, int64(fileHeaderSize) + blockSize, 2 * blockSize, 0, 1},
		{blockDataSize + 1, blockDataSize + 1, int64(fileHeaderSize) + blockSize, 2 * blockSize, 1, 1},
	} {
		what := fmt.Sprintf("offset = %d, limit = %d", test.offset, test.limit)
		underlyingOffset, underlyingLimit, discard, blocks := calculateUnderlying(test.offset, test.limit)
		assert.Equal(t, test.wantOffset, underlyingOffset, what)
		assert.Equal(t, test.wantLimit, underlyingLimit, what)
		assert.Equal(t, test.wantDiscard, discard, what)
		assert.Equal(t, test.wantBlocks, blocks, what)
	}
}

func TestDecrypterRead(t *testing.T) {
	c, err := newCipher(NameEncryptionStandard, "", "", true, nil)
	assert.NoError(t, err)

	// Test truncating the file at each possible point
	for i := 0; i < len(file16)-1; i++ {
		what := fmt.Sprintf("truncating to %d/%d", i, len(file16))
		cd := newCloseDetector(bytes.NewBuffer(file16[:i]))
		fh, err := c.newDecrypter(cd)
		if i < fileHeaderSize {
			assert.EqualError(t, err, ErrorEncryptedFileTooShort.Error(), what)
			continue
		}
		if err != nil {
			assert.NoError(t, err, what)
			continue
		}
		_, err = io.ReadAll(fh)
		var expectedErr error
		switch {
		case i == fileHeaderSize:
			// This would normally produce an error *except* on the first block
			expectedErr = nil
		case i <= fileHeaderSize+blockHeaderSize:
			expectedErr = ErrorEncryptedFileBadHeader
		default:
			expectedErr = ErrorEncryptedBadBlock
		}
		if expectedErr != nil {
			assert.EqualError(t, err, expectedErr.Error(), what)
		} else {
			assert.NoError(t, err, what)
		}
		assert.Equal(t, 0, cd.closed, what)
	}

	// Test producing an error on the file on Read the underlying file
	in1 := bytes.NewBuffer(file1)
	in2 := &readers.ErrorReader{Err: errors.New("potato")}
	in := io.MultiReader(in1, in2)
	cd := newCloseDetector(in)
	fh, err := c.newDecrypter(cd)
	assert.NoError(t, err)
	_, err = io.ReadAll(fh)
	assert.EqualError(t, err, "potato")
	assert.Equal(t, 0, cd.closed)

	// Test corrupting the input
	// shouldn't be able to corrupt any byte without some sort of error
	file16copy := make([]byte, len(file16))
	copy(file16copy, file16)
	for i := range file16copy {
		file16copy[i] ^= 0xFF
		fh, err := c.newDecrypter(io.NopCloser(bytes.NewBuffer(file16copy)))
		if i < fileMagicSize {
			assert.EqualError(t, err, ErrorEncryptedBadMagic.Error())
			assert.Nil(t, fh)
		} else {
			assert.NoError(t, err)
			_, err = io.ReadAll(fh)
			assert.EqualError(t, err, ErrorEncryptedBadBlock.Error())
		}
		file16copy[i] ^= 0xFF
	}

	// Test that we can corrupt a byte and read zeroes if
	// passBadBlocks is set
	copy(file16copy, file16)
	file16copy[len(file16copy)-1] ^= 0xFF
	c.passBadBlocks = true
	fh, err = c.newDecrypter(io.NopCloser(bytes.NewBuffer(file16copy)))
	assert.NoError(t, err)
	buf, err := io.ReadAll(fh)
	assert.NoError(t, err)
	assert.Equal(t, make([]byte, 16), buf)
}

func TestDecrypterClose(t *testing.T) {
	c, err := newCipher(NameEncryptionStandard, "", "", true, nil)
	assert.NoError(t, err)

	cd := newCloseDetector(bytes.NewBuffer(file16))
	fh, err := c.newDecrypter(cd)
	assert.NoError(t, err)
	assert.Equal(t, 0, cd.closed)

	// close before reading
	assert.Equal(t, nil, fh.err)
	err = fh.Close()
	assert.NoError(t, err)
	assert.Equal(t, ErrorFileClosed, fh.err)
	assert.Equal(t, 1, cd.closed)

	// double close
	err = fh.Close()
	assert.EqualError(t, err, ErrorFileClosed.Error())
	assert.Equal(t, 1, cd.closed)

	// try again reading the file this time
	cd = newCloseDetector(bytes.NewBuffer(file1))
	fh, err = c.newDecrypter(cd)
	assert.NoError(t, err)
	assert.Equal(t, 0, cd.closed)

	// close after reading
	out, err := io.ReadAll(fh)
	assert.NoError(t, err)
	assert.Equal(t, []byte{1}, out)
	assert.Equal(t, io.EOF, fh.err)
	err = fh.Close()
	assert.NoError(t, err)
	assert.Equal(t, ErrorFileClosed, fh.err)
	assert.Equal(t, 1, cd.closed)
}

func TestPutGetBlock(t *testing.T) {
	c, err := newCipher(NameEncryptionStandard, "", "", true, nil)
	assert.NoError(t, err)

	block := c.getBlock()
	c.putBlock(block)
	c.putBlock(block)
}

func TestKey(t *testing.T) {
	c, err := newCipher(NameEncryptionStandard, "", "", true, nil)
	assert.NoError(t, err)

	// Check zero keys OK
	assert.Equal(t, [32]byte{}, c.dataKey)
	assert.Equal(t, [32]byte{}, c.nameKey)
	assert.Equal(t, [16]byte{}, c.nameTweak)

	require.NoError(t, c.Key("potato", ""))
	assert.Equal(t, [32]byte{0x74, 0x55, 0xC7, 0x1A, 0xB1, 0x7C, 0x86, 0x5B, 0x84, 0x71, 0xF4, 0x7B, 0x79, 0xAC, 0xB0, 0x7E, 0xB3, 0x1D, 0x56, 0x78, 0xB8, 0x0C, 0x7E, 0x2E, 0xAF, 0x4F, 0xC8, 0x06, 0x6A, 0x9E, 0xE4, 0x68}, c.dataKey)
	assert.Equal(t, [32]byte{0x76, 0x5D, 0xA2, 0x7A, 0xB1, 0x5D, 0x77, 0xF9, 0x57, 0x96, 0x71, 0x1F, 0x7B, 0x93, 0xAD, 0x63, 0xBB, 0xB4, 0x84, 0x07, 0x2E, 0x71, 0x80, 0xA8, 0xD1, 0x7A, 0x9B, 0xBE, 0xC1, 0x42, 0x70, 0xD0}, c.nameKey)
	assert.Equal(t, [16]byte{0xC1, 0x8D, 0x59, 0x32, 0xF5, 0x5B, 0x28, 0x28, 0xC5, 0xE1, 0xE8, 0x72, 0x15, 0x52, 0x03, 0x10}, c.nameTweak)

	require.NoError(t, c.Key("Potato", ""))
	assert.Equal(t, [32]byte{0xAE, 0xEA, 0x6A, 0xD3, 0x47, 0xDF, 0x75, 0xB9, 0x63, 0xCE, 0x12, 0xF5, 0x76, 0x23, 0xE9, 0x46, 0xD4, 0x2E, 0xD8, 0xBF, 0x3E, 0x92, 0x8B, 0x39, 0x24, 0x37, 0x94, 0x13, 0x3E, 0x5E, 0xF7, 0x5E}, c.dataKey)
	assert.Equal(t, [32]byte{0x54, 0xF7, 0x02, 0x6E, 0x8A, 0xFC, 0x56, 0x0A, 0x86, 0x63, 0x6A, 0xAB, 0x2C, 0x9C, 0x51, 0x62, 0xE5, 0x1A, 0x12, 0x23, 0x51, 0x83, 0x6E, 0xAF, 0x50, 0x42, 0x0F, 0x98, 0x1C, 0x86, 0x0A, 0x19}, c.nameKey)
	assert.Equal(t, [16]byte{0xF8, 0xC1, 0xB6, 0x27, 0x2D, 0x52, 0x9B, 0x4A, 0x8F, 0xDA, 0xEB, 0x42, 0x4A, 0x28, 0xDD, 0xF3}, c.nameTweak)

	require.NoError(t, c.Key("potato", "sausage"))
	assert.Equal(t, [32]uint8{0x8e, 0x9b, 0x6b, 0x99, 0xf8, 0x69, 0x4, 0x67, 0xa0, 0x71, 0xf9, 0xcb, 0x92, 0xd0, 0xaa, 0x78, 0x7f, 0x8f, 0xf1, 0x78, 0xbe, 0xc9, 0x6f, 0x99, 0x9f, 0xd5, 0x20, 0x6e, 0x64, 0x4a, 0x1b, 0x50}, c.dataKey)
	assert.Equal(t, [32]uint8{0x3e, 0xa9, 0x5e, 0xf6, 0x81, 0x78, 0x2d, 0xc9, 0xd9, 0x95, 0x5d, 0x22, 0x5b, 0xfd, 0x44, 0x2c, 0x6f, 0x5d, 0x68, 0x97, 0xb0, 0x29, 0x1, 0x5c, 0x6f, 0x46, 0x2e, 0x2a, 0x9d, 0xae, 0x2c, 0xe3}, c.nameKey)
	assert.Equal(t, [16]uint8{0xf1, 0x7f, 0xd7, 0x14, 0x1d, 0x65, 0x27, 0x4f, 0x36, 0x3f, 0xc2, 0xa0, 0x4d, 0xd2, 0x14, 0x8a}, c.nameTweak)

	require.NoError(t, c.Key("potato", "Sausage"))
	assert.Equal(t, [32]uint8{0xda, 0x81, 0x8c, 0x67, 0xef, 0x11, 0xf, 0xc8, 0xd5, 0xc8, 0x62, 0x4b, 0x7f, 0xe2, 0x9e, 0x35, 0x35, 0xb0, 0x8d, 0x79, 0x84, 0x89, 0xac, 0xcb, 0xa0, 0xff, 0x2, 0x72, 0x3, 0x1a, 0x5e, 0x64}, c.dataKey)
	assert.Equal(t, [32]uint8{0x2, 0x81, 0x7e, 0x7b, 0xea, 0x99, 0x81, 0x5a, 0xd0, 0x2d, 0xb9, 0x64, 0x48, 0xb0, 0x28, 0x27, 0x7c, 0x20, 0xb4, 0xd4, 0xa4, 0x68, 0xad, 0x4e, 0x5c, 0x29, 0xf, 0x79, 0xef, 0xee, 0xdb, 0x3b}, c.nameKey)
	assert.Equal(t, [16]uint8{0x9a, 0xb5, 0xb, 0x3d, 0xcb, 0x60, 0x59, 0x55, 0xa5, 0x4d, 0xe6, 0xb6, 0x47, 0x3, 0x23, 0xe2}, c.nameTweak)

	require.NoError(t, c.Key("", ""))
	assert.Equal(t, [32]byte{}, c.dataKey)
	assert.Equal(t, [32]byte{}, c.nameKey)
	assert.Equal(t, [16]byte{}, c.nameTweak)
}