Compare commits

...

124 Commits

Author SHA1 Message Date
Neucrack
540e9435a1 read pannel from /boot/board 2024-11-29 11:41:01 +08:00
lxowalle
fe0d6c8413 * fix uvc bug 2024-11-28 14:38:53 +08:00
Neucrack
441888b5bf fix make_logo script error 2024-11-26 10:28:05 +08:00
Neucrack
3042208f78 read panel from /boot/board instead of uEnv.txt 2024-11-25 16:35:52 +08:00
Neucrack
c99d1839c6 Merge pull request #63 from MK16kawai/main
update panels for sample_dsi
2024-11-21 15:23:50 +08:00
Mk16kawai
26beec94d8 update panels for sample_dsi 2024-11-21 11:18:17 +08:00
Neucrack
1d5c76c297 Merge pull request #61 from 916BGAI/main
enable uinput driver and update AXP2101 firmware.
2024-11-08 15:22:45 +08:00
916BGAI
a652cdf214 enable uinput driver to simulate input events in user space 2024-11-08 15:10:53 +08:00
916BGAI
8ad8100af7 update AXP2101 firmware, enable POWERON IRQ 2024-11-08 15:10:40 +08:00
BuGu
2588dd8dec Merge pull request #58 from 916BGAI/main
add spi lcd support
2024-10-22 16:36:28 +08:00
916BGAI
0fd87890d8 add spi lcd support 2024-10-22 16:29:46 +08:00
Neucrack
1dd70fb86b Merge pull request #57 from 916BGAI/main
fix lct024bsi20 mipi porch
2024-10-18 14:26:13 +08:00
916BGAI
fab2c7e9ec fix lct024bsi20 mipi porch 2024-10-18 11:30:23 +08:00
916BGAI
45fffd0c2d add -latomic to linker flags for scene_auto sample 2024-10-17 13:37:32 +08:00
BuGu
e0118303d0 Merge pull request #56 from 916BGAI/main
boost sc035gs fps to 180
2024-10-16 16:17:08 +08:00
916BGAI
835cae07f3 boost sc035gs fps to 180 2024-10-16 16:09:13 +08:00
BuGu
75fc0b5f72 Merge pull request #53 from 916BGAI/main
Add AIC8800DC support and add axp2101 0x47 version support
2024-10-15 19:08:42 +08:00
lxowalle
d6ba0b0a9e * disable vi_dbg_handler 2 2024-10-14 17:35:14 +08:00
lxowalle
b639458b1c * disable vi_dbg_handler 2024-10-14 15:21:27 +08:00
916BGAI
c5e7bd8e8a add axp2101 0x47 version support 2024-10-12 16:47:41 +08:00
916BGAI
6aa6f6005a Merge branch 'sipeed:main' into main 2024-10-12 16:10:14 +08:00
Neucrack
a0dd574a11 add change rootfs missing file 2024-09-26 19:11:22 +08:00
Neucrack
632a76b919 fix tp for maixcampro 2024-09-26 18:46:49 +08:00
Neucrack
245a5827da change 2.4 inch pannel name 2024-09-26 18:12:06 +08:00
Neucrack
aa8b82b114 add quarks for hikcamera 2024-09-26 11:05:10 +08:00
916BGAI
60994cf636 Add AIC8800DC support 2024-09-23 14:21:25 +08:00
lxowalle
9c961a8be6 * fix can't snap 12bpp raw 2024-09-20 14:00:01 +08:00
BuGu
6f4aafa54e Merge pull request #49 from 916BGAI/main
Optimize S05tp and hyn touch driver
2024-09-19 14:15:36 +08:00
lxowalle
2e8ca21757 * update ov2685 isp config 2024-09-19 09:42:59 +08:00
916BGAI
0a7a27260d Optimize S05tp and hyn touch driver 2024-09-14 09:46:34 +08:00
BuGu
40170c1672 Merge pull request #46 from 916BGAI/main
Optimize AXP2101 PMU
2024-09-06 10:24:13 +08:00
BuGu
752683e13b Merge branch 'main' of https://github.com/sipeed/LicheeRV-Nano-Build 2024-09-05 10:28:06 +08:00
BuGu
67c7a6c36f Update support for HID
Keyboard, mouse, touchpad
2024-09-05 10:27:47 +08:00
916BGAI
d116757f47 Optimize AXP2101 PMU 2024-09-04 11:38:11 +08:00
lxowalle
cde77bdacb * add os04a10 and ov2685 config of isp 2024-08-30 16:14:14 +08:00
lxowalle
93c2fb99d4 * optimize ov2685 2024-08-26 13:56:14 +08:00
BuGu
db210284e6 Update rootfs resize
rootfs can be scaled only in the boot script
2024-08-22 15:52:24 +08:00
BuGu
cb7a562241 Merge pull request #42 from TheRainstorm/main
fix ipv4 policy routing kernel config and enable other useful kernel options
2024-08-22 15:34:08 +08:00
BuGu
cbdd1ceee5 Merge pull request #41 from 916BGAI/main
Add axp2101 pmu support and reverse cst7xx touchscreen pos
2024-08-20 17:19:41 +08:00
916BGAI
e26614ad36 Optimize cst7xx touch accuracy 2024-08-20 17:17:25 +08:00
BuGu
82012f20c2 Fixed the eth cable detection issue 2024-08-19 09:43:31 +08:00
Fuyan Yuan
d80ada2d6f buildroot: enable netcat, mtr utils 2024-08-18 21:35:18 +08:00
Fuyan Yuan
38156d546e kernel config: enable net namespace, TCP BBR, GRE and VXLAN tunnel protocol 2024-08-18 21:35:18 +08:00
Fuyan Yuan
4836f6e127 kernel config: fix ipv4 policy routing 2024-08-18 21:35:17 +08:00
Neucrack
713161599e add rndis for basesystem and change ion size to 105MB 2024-08-16 10:27:36 +08:00
916BGAI
ebfa11ffba Add AXP2101 PMU support 2024-08-15 16:32:37 +08:00
916BGAI
a2d9fd0f6a Reverse cst7xx touchscreen posx and posy 2024-08-15 15:59:27 +08:00
Neucrack
0de38f39d1 support gadget ncm and rndis at the same time 2024-08-12 19:28:54 +08:00
BuGu
ab3c5d9329 Merge pull request #39 from TheRainstorm/main
add support for policy routing and others
2024-08-12 15:50:14 +08:00
Fuyan Yuan
bb26cf2bc6 buildroot config: add package bash 2024-08-09 20:41:27 +08:00
Fuyan Yuan
fc359c8a6d kernel config: add support for policy routing, veth 2024-08-09 20:41:02 +08:00
lxowalle
dfe981e5e1 * delete unused picture 2024-08-09 09:54:48 +08:00
lxowalle
9f330c8b83 * support ov2685 2024-08-08 18:53:18 +08:00
BuGu
d6a1a42ae4 Merge pull request #37 from 916BGAI/main
Fix the D240SI31 Panel and add support for cst7xx touchscreen
2024-08-08 14:36:11 +08:00
Neucrack
b0a69a2853 set default to ncm 2024-08-07 15:57:37 +08:00
Neucrack
33e46c1109 add USB gadget NCM driver 2024-08-07 14:44:46 +08:00
916BGAI
bd92529ed8 Fix the D240SI31 Panel and add support for cst7xx touchscreen 2024-08-06 15:37:24 +08:00
Neucrack
378a06730f optimize USB RNDIS driver, now windows can recognize it 2024-08-06 15:09:58 +08:00
某杰同学
bef2ca41ab Revision LicheeRV Nano USB PID 2024-08-05 21:07:49 -07:00
某杰同学
c048db4984 Merge branch 'main' of https://github.com/sipeed/LicheeRV-Nano-Build 2024-08-05 20:58:00 -07:00
某杰同学
6be3e66437 Improve the identification rate of ETH cables 2024-08-05 20:47:02 -07:00
某杰同学
4bb531573b Boost the SC035 FPS
30 - 60fps
2024-08-05 20:45:14 -07:00
Neucrack
abccc497e3 optimize usb script 2024-08-05 17:32:30 +08:00
Neucrack
e5bd5a8b7f wifi script support ap mode 2024-08-05 16:04:06 +08:00
某杰同学
fc2bb198df Fix the time zone setting 2024-07-24 19:19:26 -07:00
某杰同学
587710af28 Add support for WIREGUARD, RNDIS HOST, USB ACM HOST 2024-07-19 20:08:18 -07:00
某杰同学
65b0a63ff1 Merge branch 'main' of https://github.com/sipeed/LicheeRV-Nano-Build 2024-07-16 18:47:14 -07:00
某杰同学
3541f19a68 Add support for D240SI31 Panel 2024-07-16 18:41:43 -07:00
Neucrack
2459349f47 remove soph_mipi_tx.ko load 2024-07-09 18:09:44 +08:00
Neucrack
165c13fc1e Merge pull request #24 from 981213/main
delete libraries copied/built from middleware/v2/modules
2024-07-09 10:28:02 +08:00
Neucrack
6f65fa1025 Merge branch 'main' into main 2024-07-09 10:27:52 +08:00
Neucrack
e4064b1b99 add python pkgs 2024-07-09 10:25:52 +08:00
某杰同学
cbe64d6240 Added support for IPMITOOL 2024-06-24 18:50:41 -07:00
某杰同学
2d2bfb11f9 Added support for USB remote wakeup 2024-06-19 03:04:18 -07:00
某杰同学
a4c7ee1b6c Added support for LCD(MTD70092b) 2024-06-19 03:02:45 -07:00
某杰同学
f85d122178 Added support for firewall 2024-06-19 03:01:12 -07:00
某杰同学
077f1019a6 Added support for ExFAT 2024-06-12 20:35:54 -07:00
某杰同学
56ffe4346a Update sg2002_licheervnano_sd.dts 2024-06-12 02:06:46 -07:00
Lu
538654eec2 fix pwm backlight pinmux 2024-06-03 10:33:32 +08:00
Lu
608df819e8 add rtl8733 support, add logo support 2024-05-31 17:39:15 +08:00
Lu
82a0b70d86 some update 2024-05-28 17:26:25 +08:00
Chuanhong Guo
53e80a481f delete libraries copied/built from middleware/v2/modules
These are either built from source or prebuilt files copied from elsewhere.
Delete them from git repo, and add middleware/v2/lib to .gitignore.
2024-05-28 12:45:45 +08:00
某杰同学
58f1952f91 Fix the problem of GC4653 color anomaly 2024-05-27 19:38:37 -07:00
某杰同学
e4c87a6db0 Update KVM Demo
Update KVM Demo
2024-05-22 01:38:53 -07:00
某杰同学
f88933c279 Update sample_vio_main.c 2024-05-22 01:07:59 -07:00
BuGu
17ac2f04de Upadate KVM sample 2024-05-22 14:37:19 +08:00
BuGu
35bcba4669 Upadate KVM sample 2024-05-22 14:37:05 +08:00
某杰同学
892cddc08e Update kvm sample 2024-05-21 23:27:13 -07:00
某杰同学
05f0c9ec27 Added i2c-3 PinMux
Added i2c-3 PinMux
2024-05-16 02:17:45 -07:00
某杰同学
3c0a81cf90 Merge branch 'main' of https://github.com/sipeed/LicheeRV-Nano-Build 2024-05-16 02:01:57 -07:00
某杰同学
758bfac682 Added support for OLED display of RTSP addresses
Added support for OLED display of RTSP addresses
2024-05-16 01:58:01 -07:00
Lu
9af3db7d4d add bitbang i2c5 & bitbang spi4 2024-05-15 16:38:27 +08:00
某杰同学
20a606bbdb Added support for OA04A10, SC035GS, LT6911, and the new 5-inch LCD
Added support for OA04A10, SC035GS, LT6911, and the new 5-inch display
2024-05-15 00:00:53 -07:00
Lu
646bd60447 initramfs: fix when /dev/console is missing 2024-05-14 09:54:23 +08:00
Lu
f3ea496a1a fix pwm driver, thank sophgo 2024-05-13 18:03:29 +08:00
Lu
83ed7eae08 resize part & file system in initramfs 2024-05-13 17:13:24 +08:00
Lu
e73f5de35d allow user custom dns server 2024-05-13 15:30:26 +08:00
Lu
b9dd20e9e2 buildroot: tpudemo upgrade 2024-05-10 10:11:18 +08:00
Lu
3ee0bd6338 licheervnano: some fix 2024-05-10 10:10:42 +08:00
Lu
90f973b98b ramdisk: add fsck in initramfs 2024-05-10 10:10:05 +08:00
Lu Hui
66fedc1a27 add some userful demo 2024-04-26 09:33:17 +08:00
Lu Hui
6cbfa16a22 genimage: default enable fb & gt9xx 2024-04-25 15:31:16 +08:00
Lu Hui
f9348c4b1c S04fb: show fbpattern on bootup 2024-04-25 15:19:28 +08:00
Lu Hui
eb7c808497 buildroot: lcdtest: upgrade 2024-04-25 15:18:57 +08:00
Lu Hui
81dc709f99 cvitek_SG200X_musl_riscv64_defconfig: remove unused pygame 2024-04-25 15:18:40 +08:00
Lu Hui
5c35c86ea5 S04backlight: hd2280 20% duty 2024-04-25 15:18:10 +08:00
Lu Hui
2f25198422 S02config: fix typo 2024-04-23 10:22:21 +08:00
Lu Hui
c65a118dfd bootargs: default disable console log level, because it too slow 2024-04-23 10:02:28 +08:00
Lu Hui
1eee814e78 README.md: add fat 2024-04-22 18:25:55 +08:00
Lu Hui
03abdfe495 buildroot: opencv4 upgrade 2024-04-22 15:53:52 +08:00
Lu Hui
f9fe939c24 S02config: if sensor config file is empty, rebuild it from default 2024-04-22 15:53:31 +08:00
Lu Hui
d18e19c362 buildroot: cvitek_SG200X_musl_riscv64_defconfig: disable qt 2024-04-22 11:20:20 +08:00
Lu Hui
89c2b52bbd add utils for image modify 2024-04-22 11:19:46 +08:00
Lu Hui
cb03057336 S30wifi: we need compat with old program 2024-04-19 14:17:06 +08:00
Lu Hui
1daa602f32 S30wifi: we need compat with old program 2024-04-19 14:16:07 +08:00
Lu Hui
8d286613a2 fix doc, fix typo 2024-04-18 18:32:21 +08:00
Lu Hui
16d76badff licheervnano: fix S02config, enable spi master 2024-04-10 14:11:38 +08:00
Lu Hui
ecbcc0e374 licheervnano: default enable uart2 controller 2024-04-09 14:08:45 +08:00
Lu Hui
61ecf59b8b 2024 04 08 2024-04-08 13:53:11 +08:00
Lu Hui
232f2234ff update 2024-04-07 09:41:20 +08:00
Lu Hui
ddd40cd715 doc: update 2024-04-07 09:37:53 +08:00
Lu Hui
77980ffd0c merge upstream 2024-04-02 09:14:01 +08:00
Lu Hui
55a54911f7 20240401 2024-04-01 15:38:13 +08:00
Lu Hui
7497e5bc7e gc4653 isp config update 2024-03-27 09:35:26 +08:00
2660 changed files with 227920 additions and 245296 deletions

239
.gitignore vendored
View File

@@ -1,5 +1,8 @@
*~
*.swp
*.o
*.ko
*.d
host-tools/
*.sqfs
build/tools/common/sd_tools/genimage.cfg.tmp
@@ -180,3 +183,239 @@ buildroot/board/cvitek/SG200X/overlay/mnt/system/sdk-release
buildroot/board/cvitek/SG200X/overlay/mnt/system/auto.sh
middleware/v2/mod_tmp/*
cscope.out
middleware/v2/3rdparty/inih/ini.d
middleware/v2/3rdparty/inih/ini.o
middleware/v2/component/isp/sensor/cv182x/gcore_gc4653/gc4653_cmos.d
middleware/v2/component/isp/sensor/cv182x/gcore_gc4653/gc4653_cmos.o
middleware/v2/component/isp/sensor/cv182x/gcore_gc4653/gc4653_sensor_ctl.d
middleware/v2/component/isp/sensor/cv182x/gcore_gc4653/gc4653_sensor_ctl.o
middleware/v2/component/isp/sensor/cv182x/ov_os04a10/os04a10_cmos.d
middleware/v2/component/isp/sensor/cv182x/ov_os04a10/os04a10_cmos.o
middleware/v2/component/isp/sensor/cv182x/ov_os04a10/os04a10_sensor_ctl.d
middleware/v2/component/isp/sensor/cv182x/ov_os04a10/os04a10_sensor_ctl.o
middleware/v2/lib/libsns_os04a10.a
middleware/v2/lib/libsns_os04a10.so
middleware/v2/modules/bin/src/cvi_bin.d
middleware/v2/modules/bin/src/cvi_bin.o
middleware/v2/modules/bin/src/md5.d
middleware/v2/modules/bin/src/md5.o
middleware/v2/modules/bin/src/rw_json.d
middleware/v2/modules/bin/src/rw_json.o
middleware/v2/modules/bin/src/vo_bin.d
middleware/v2/modules/bin/src/vo_bin.o
middleware/v2/modules/bin/src/vo_json_struct.d
middleware/v2/modules/bin/src/vo_json_struct.o
middleware/v2/modules/bin/src/vpss_bin.d
middleware/v2/modules/bin/src/vpss_bin.o
middleware/v2/modules/bin/src/vpss_json_struct.d
middleware/v2/modules/bin/src/vpss_json_struct.o
middleware/v2/modules/ive/src/cvi_ive.d
middleware/v2/modules/ive/src/cvi_ive.o
middleware/v2/modules/mipi_tx/src/mipi_tx.d
middleware/v2/modules/mipi_tx/src/mipi_tx.o
middleware/v2/modules/misc/src/cvi_misc.d
middleware/v2/modules/misc/src/cvi_misc.o
middleware/v2/modules/osdc/src/cmpr_canvas.d
middleware/v2/modules/osdc/src/cmpr_canvas.o
middleware/v2/modules/osdc/src/cvi_osdc.d
middleware/v2/modules/osdc/src/cvi_osdc.o
middleware/v2/modules/osdc/src/osd_cmpr.d
middleware/v2/modules/osdc/src/osd_cmpr.o
middleware/v2/modules/sys/src/cvi_base.d
middleware/v2/modules/sys/src/cvi_base.o
middleware/v2/modules/sys/src/cvi_sys.d
middleware/v2/modules/sys/src/cvi_sys.o
middleware/v2/modules/sys/src/cvi_thermal.d
middleware/v2/modules/sys/src/cvi_thermal.o
middleware/v2/modules/sys/src/cvi_tracer.d
middleware/v2/modules/sys/src/cvi_tracer.o
middleware/v2/modules/sys/src/cvi_vb.d
middleware/v2/modules/sys/src/cvi_vb.o
middleware/v2/modules/sys/src/devmem.d
middleware/v2/modules/sys/src/devmem.o
middleware/v2/modules/sys/src/hashmap.d
middleware/v2/modules/sys/src/hashmap.o
middleware/v2/modules/sys/src/peri.d
middleware/v2/modules/sys/src/peri.o
middleware/v2/modules/sys/src/sys_ioctl.d
middleware/v2/modules/sys/src/sys_ioctl.o
middleware/v2/modules/sys/src/vb_ioctl.d
middleware/v2/modules/sys/src/vb_ioctl.o
middleware/v2/modules/vdec/src/cvi_vdec.d
middleware/v2/modules/vdec/src/cvi_vdec.o
middleware/v2/modules/venc/src/cvi_venc.d
middleware/v2/modules/venc/src/cvi_venc.o
middleware/v2/modules/vpu/src/cvi_gdc_1822.d
middleware/v2/modules/vpu/src/cvi_gdc_1822.o
middleware/v2/modules/vpu/src/cvi_region.d
middleware/v2/modules/vpu/src/cvi_region.o
middleware/v2/modules/vpu/src/cvi_vi.d
middleware/v2/modules/vpu/src/cvi_vi.o
middleware/v2/modules/vpu/src/cvi_vo.d
middleware/v2/modules/vpu/src/cvi_vo.o
middleware/v2/modules/vpu/src/cvi_vpss.d
middleware/v2/modules/vpu/src/cvi_vpss.o
middleware/v2/modules/vpu/src/dump_register.d
middleware/v2/modules/vpu/src/dump_register.o
middleware/v2/modules/vpu/src/dwa_ioctl.d
middleware/v2/modules/vpu/src/dwa_ioctl.o
middleware/v2/modules/vpu/src/gdc_mesh_1822.d
middleware/v2/modules/vpu/src/gdc_mesh_1822.o
middleware/v2/modules/vpu/src/rgn_ioctl.d
middleware/v2/modules/vpu/src/rgn_ioctl.o
middleware/v2/modules/vpu/src/vi_ioctl.d
middleware/v2/modules/vpu/src/vi_ioctl.o
middleware/v2/modules/vpu/src/vo_ioctl.d
middleware/v2/modules/vpu/src/vo_ioctl.o
middleware/v2/modules/vpu/src/vpss_ioctl.d
middleware/v2/modules/vpu/src/vpss_ioctl.o
middleware/v2/sample/audio/aac_sample/cvi_audio_aac_adp.d
middleware/v2/sample/audio/aac_sample/cvi_audio_aac_adp.o
middleware/v2/sample/audio/cvi_audio_dl_adp.d
middleware/v2/sample/audio/cvi_audio_dl_adp.o
middleware/v2/sample/audio/cvi_audio_parse_param.d
middleware/v2/sample/audio/cvi_audio_parse_param.o
middleware/v2/sample/audio/cvi_sample_audio.d
middleware/v2/sample/audio/cvi_sample_audio.o
middleware/v2/sample/audio/sample_audio
middleware/v2/sample/common/loadbmp.d
middleware/v2/sample/common/loadbmp.o
middleware/v2/sample/common/md5sum.d
middleware/v2/sample/common/md5sum.o
middleware/v2/sample/common/sample_common_bin.d
middleware/v2/sample/common/sample_common_bin.o
middleware/v2/sample/common/sample_common_isp.d
middleware/v2/sample/common/sample_common_isp.o
middleware/v2/sample/common/sample_common_peripheral.d
middleware/v2/sample/common/sample_common_peripheral.o
middleware/v2/sample/common/sample_common_platform.d
middleware/v2/sample/common/sample_common_platform.o
middleware/v2/sample/common/sample_common_region.d
middleware/v2/sample/common/sample_common_region.o
middleware/v2/sample/common/sample_common_sensor.d
middleware/v2/sample/common/sample_common_sensor.o
middleware/v2/sample/common/sample_common_sys.d
middleware/v2/sample/common/sample_common_sys.o
middleware/v2/sample/common/sample_common_vdec.d
middleware/v2/sample/common/sample_common_vdec.o
middleware/v2/sample/common/sample_common_venc.d
middleware/v2/sample/common/sample_common_venc.o
middleware/v2/sample/common/sample_common_vi.d
middleware/v2/sample/common/sample_common_vi.o
middleware/v2/sample/common/sample_common_vo.d
middleware/v2/sample/common/sample_common_vo.o
middleware/v2/sample/common/sample_common_vpss.d
middleware/v2/sample/common/sample_common_vpss.o
middleware/v2/sample/fisheye/sample_fisheye
middleware/v2/sample/fisheye/sample_fisheye.d
middleware/v2/sample/fisheye/sample_fisheye.o
middleware/v2/sample/ir_auto/ir_auto
middleware/v2/sample/ir_auto/ir_auto.d
middleware/v2/sample/ir_auto/ir_auto.o
middleware/v2/sample/ive/sample_16bitto8bit
middleware/v2/sample/ive/sample_add
middleware/v2/sample/ive/sample_and
middleware/v2/sample/ive/sample_bernsen
middleware/v2/sample/ive/sample_bgmodel
middleware/v2/sample/ive/sample_cannyedge
middleware/v2/sample/ive/sample_cannyhysedge
middleware/v2/sample/ive/sample_csc
middleware/v2/sample/ive/sample_dilate
middleware/v2/sample/ive/sample_dma
middleware/v2/sample/ive/sample_erode
middleware/v2/sample/ive/sample_filter
middleware/v2/sample/ive/sample_filterandcsc
middleware/v2/sample/ive/sample_framediffmotion
middleware/v2/sample/ive/sample_gmm
middleware/v2/sample/ive/sample_gmm2
middleware/v2/sample/ive/sample_gradfg
middleware/v2/sample/ive/sample_hist
middleware/v2/sample/ive/sample_integ
middleware/v2/sample/ive/sample_lbp
middleware/v2/sample/ive/sample_magandang
middleware/v2/sample/ive/sample_map
middleware/v2/sample/ive/sample_ncc
middleware/v2/sample/ive/sample_normgrad
middleware/v2/sample/ive/sample_or
middleware/v2/sample/ive/sample_ordstatfilter
middleware/v2/sample/ive/sample_query
middleware/v2/sample/ive/sample_resize
middleware/v2/sample/ive/sample_sad
middleware/v2/sample/ive/sample_sobel
middleware/v2/sample/ive/sample_stcandicorner
middleware/v2/sample/ive/sample_sub
middleware/v2/sample/ive/sample_thresh
middleware/v2/sample/ive/sample_thresh_S16
middleware/v2/sample/ive/sample_thresh_U16
middleware/v2/sample/ive/sample_xor
middleware/v2/sample/mipi_tx/lt9611/lt9611
middleware/v2/sample/mipi_tx/lt9611/lt9611.d
middleware/v2/sample/mipi_tx/lt9611/lt9611.o
middleware/v2/sample/mipi_tx/sample_dsi
middleware/v2/sample/mipi_tx/sample_dsi.d
middleware/v2/sample/mipi_tx/sample_dsi.o
middleware/v2/sample/osdc/sample_osdc
middleware/v2/sample/osdc/sample_osdc.d
middleware/v2/sample/osdc/sample_osdc.o
middleware/v2/sample/overlay/sample_overlay
middleware/v2/sample/overlay/sample_overlay.d
middleware/v2/sample/overlay/sample_overlay.o
middleware/v2/sample/region/sample_region
middleware/v2/sample/region/sample_region.d
middleware/v2/sample/region/sample_region.o
middleware/v2/sample/sample_panel/sample_panel.d
middleware/v2/sample/sample_panel/sample_panel.o
middleware/v2/sample/scene_auto/sample_scene_auto
middleware/v2/sample/scene_auto/src/core/cvi_scene.d
middleware/v2/sample/scene_auto/src/core/cvi_scene.o
middleware/v2/sample/scene_auto/src/core/cvi_scene_setparam.d
middleware/v2/sample/scene_auto/src/core/cvi_scene_setparam.o
middleware/v2/sample/scene_auto/src/sample/cvi_scene_decode.d
middleware/v2/sample/scene_auto/src/sample/cvi_scene_decode.o
middleware/v2/sample/scene_auto/src/sample/cvi_scene_loadparam.d
middleware/v2/sample/scene_auto/src/sample/cvi_scene_loadparam.o
middleware/v2/sample/scene_auto/src/sample/sample_scene.d
middleware/v2/sample/scene_auto/src/sample/sample_scene.o
middleware/v2/sample/scene_auto/src/sample/sample_scene_main.d
middleware/v2/sample/scene_auto/src/sample/sample_scene_main.o
middleware/v2/sample/scene_auto/tools/iniparser/src/dictionary.d
middleware/v2/sample/scene_auto/tools/iniparser/src/dictionary.o
middleware/v2/sample/scene_auto/tools/iniparser/src/iniparser.d
middleware/v2/sample/scene_auto/tools/iniparser/src/iniparser.o
middleware/v2/sample/sensor_test/sensor_test
middleware/v2/sample/sensor_test/sensor_test.d
middleware/v2/sample/sensor_test/sensor_test.o
middleware/v2/sample/sensor_test/src/ae_test.d
middleware/v2/sample/sensor_test/src/ae_test.o
middleware/v2/sample/vdec/sample_vdec
middleware/v2/sample/vdec/sample_vdec.d
middleware/v2/sample/vdec/sample_vdec.o
middleware/v2/sample/vdec/sample_vdec_asan
middleware/v2/sample/vdec/src/sample_vdec_lib.d
middleware/v2/sample/vdec/src/sample_vdec_lib.o
middleware/v2/sample/vdec/src/sample_vdec_testcase.d
middleware/v2/sample/vdec/src/sample_vdec_testcase.o
middleware/v2/sample/vdecvo/sample_vdecvo
middleware/v2/sample/vdecvo/sample_vdecvo.d
middleware/v2/sample/vdecvo/sample_vdecvo.o
middleware/v2/sample/venc/sample_vcodec
middleware/v2/sample/venc/sample_vcodec.d
middleware/v2/sample/venc/sample_vcodec.o
middleware/v2/sample/venc/sample_vcodec_asan
middleware/v2/sample/venc/sample_venc
middleware/v2/sample/venc/sample_venc.d
middleware/v2/sample/venc/sample_venc.o
middleware/v2/sample/venc/sample_venc_asan
middleware/v2/sample/venc/src/sample_venc_lib.d
middleware/v2/sample/venc/src/sample_venc_lib.o
middleware/v2/sample/venc/src/sample_venc_testcase.d
middleware/v2/sample/venc/src/sample_venc_testcase.o
middleware/v2/sample/vio/sample_vio
middleware/v2/sample/vio/sample_vio.d
middleware/v2/sample/vio/sample_vio.o
middleware/v2/sample/vio/sample_vio_main.d
middleware/v2/sample/vio/sample_vio_main.o
osdrv/extdrv/wireless/.tmp_4261/
middleware/v2/lib
host-tools/
kvm/

View File

@@ -3,7 +3,7 @@
# download source
```
git clone https://github.com/LicheeRV-Nano-Build --depth=1
git clone https://github.com/sipeed/LicheeRV-Nano-Build --depth=1
cd LicheeRV-Nano-Build
git clone https://github.com/sophgo/host-tools --depth=1
```
@@ -15,8 +15,8 @@ you can use container:
```
cd host/ubuntu
docker build -t licheervnano-build-ubuntu .
docker run --name licheervnano-build-ubuntu
docker export | sqfstar licheervnano-build-ubuntu.sqfs
docker run --name licheervnano-build-ubuntu licheervnano-build-ubuntu
docker export licheervnano-build-ubuntu | sqfstar licheervnano-build-ubuntu.sqfs
singularity shell -e licheervnano-build-ubuntu.sqfs
```
@@ -30,3 +30,31 @@ defconfig sg2002_licheervnano_sd
# defconfig sg2002_licheea53nano_sd
build_all
```
# build fail
on some system, qt5svg or qt5base will build failed on first build, please retry command:
```
build_all
```
# how to modify image after build:
```
# first partition
touch wifi.sta
mcopy -i install/xxx/xxx.img@@1s wifi.sta ::/
# second partition
./host/mount_ext4.sh install/xxx/xxx.img mountpoint
cd mountpoint
touch xxx
```
# logo
```
./host/make_logo.sh input.jpeg logo.jpeg
mcopy -i install/xxx/xxx.img@@1s logo.jpeg ::/
```

View File

@@ -156,21 +156,21 @@
compatible = "cvitek,cvi-pwm";
reg = <0x0 0x3060000 0x0 0x1000>;
clocks = <&clk CV181X_CLK_PWM>;
#pwm-cells = <1>;
#pwm-cells = <4>;
};
pwm1: pwm@3061000 {
compatible = "cvitek,cvi-pwm";
reg = <0x0 0x3061000 0x0 0x1000>;
clocks = <&clk CV181X_CLK_PWM>;
#pwm-cells = <2>;
#pwm-cells = <4>;
};
pwm2: pwm@3062000 {
compatible = "cvitek,cvi-pwm";
reg = <0x0 0x3062000 0x0 0x1000>;
clocks = <&clk CV181X_CLK_PWM>;
#pwm-cells = <3>;
#pwm-cells = <4>;
};
pwm3: pwm@3063000 {
@@ -233,6 +233,7 @@
clocks = <&clk CV181X_CLK_SPI>;
#address-cells = <1>;
#size-cells = <0>;
bias-pull-up;
};
spi3:spi3@041B0000 {
@@ -865,13 +866,13 @@
trips {
soc_thermal_trip_0: soc_thermal_trip_0 {
temperature = <100000>; /* millicelsius */
temperature = <110000>; /* millicelsius */
hysteresis = <5000>; /* millicelsius */
type = "passive";
};
soc_thermal_trip_1: soc_thermal_trip_1 {
temperature = <110000>; /* millicelsius */
temperature = <120000>; /* millicelsius */
hysteresis = <5000>; /* millicelsius */
type = "passive";
};

View File

@@ -8,7 +8,7 @@
#include <dt-bindings/gpio/gpio.h>
&i2c0 {
status = "disabled";
status = "okay";
/delete-property/ scl-pinmux;
/delete-property/ sda-pinmux;
/delete-property/ scl-gpios;
@@ -16,7 +16,7 @@
};
&i2c1 {
status = "disabled";
status = "okay";
/delete-property/ scl-pinmux;
/delete-property/ sda-pinmux;
/delete-property/ scl-gpios;
@@ -57,10 +57,29 @@
status = "okay";
};
&uart0 {
clocks = <&clk CV181X_CLK_UART0>;
/delete-property/ clock-frequency;
};
&uart1 {
clocks = <&clk CV181X_CLK_UART1>;
/delete-property/ clock-frequency;
status = "okay";
};
&uart2 {
clocks = <&clk CV181X_CLK_UART2>;
/delete-property/ clock-frequency;
status = "okay";
};
&uart3 {
clocks = <&clk CV181X_CLK_UART3>;
/delete-property/ clock-frequency;
status = "okay";
};
&pwm0 {
status = "okay";
};
@@ -82,7 +101,7 @@
};
&i2c3 {
status = "disabled";
status = "okay";
/delete-property/ scl-pinmux;
/delete-property/ sda-pinmux;
/delete-property/ scl-gpios;
@@ -90,7 +109,7 @@
};
&i2c4 {
statuc = "okay";
status = "okay";
gt9xx: gt9xx@14 {
compatible = "goodix,gt9xx";
reg = <0x14>;
@@ -98,17 +117,57 @@
goodix,rst-gpio = <&porte 4 0>;
status = "okay";
};
hytr: hynitron@5a {
compatible = "hynitron,hyn_ts";
reg = <0x5a>;
hynitron,irq-gpio = <&porte 3 0>;
hynitron,reset-gpio = <&porte 4 0>;
hynitron,max-touch-number = <5>;
hynitron,display-coords = <368 552>;
hynitron: hynitron@5a {
compatible = "hynitron,hyn_ts", "hyn,7xx";
reg = <0x5a>;
irq-gpio = <&porte 3 0>;
hynitron,irq-gpio = <&porte 3 0>;
reset-gpio = <&porte 4 0>;
hynitron,reset-gpio = <&porte 4 0>;
max-touch-number = <5>;
hynitron,max-touch-number = <5>;
display-coords = <0 0 480 640>;
hynitron,display-coords = <368 552>;
pos-swap = <0>;
posx-reverse = <1>;
posy-reverse = <1>;
status = "okay";
};
};
&spi0 {
status = "okay";
};
&spi1 {
status = "okay";
};
&spi2 {
status = "okay";
// /delete-node/ spidev@0;
st7789: st7789@0{
compatible = "sitronix,st7789";
reg = <0>;
status = "disabled";
spi-max-frequency = <80000000>;
spi-cpol;
spi-cpha;
rotate = <0>;
fps = <60>;
rgb;
buswidth = <8>;
dc = <&porte 20 GPIO_ACTIVE_HIGH>;
reset = <&porta 14 GPIO_ACTIVE_LOW>;
debug = <0>;
};
};
&spi3 {
status = "okay";
};
&dac {
status = "okay";
/delete-property/ mute-gpio-r;
@@ -129,6 +188,29 @@
/ {
model = "LicheeRv Nano";
spi4: spi4@gpio {
compatible = "spi-gpio";
sck-gpio = <&porta 22 0>;
miso-gpio = <&porta 23 0>;
mosi-gpio = <&porta 25 0>;
cs-gpio = <&porta 24 GPIO_ACTIVE_LOW>;
num-chipselects = <1>;
status = "okay";
spidev@0 {
compatible = "spidev";
reg = <0>;
};
};
i2c5: i2c5@gpio {
compatible = "i2c-gpio";
scl-gpios = <&porta 15 (GPIO_ACTIVE_HIGH | GPIO_OPEN_DRAIN)>;
sda-gpios = <&porta 27 (GPIO_ACTIVE_HIGH | GPIO_OPEN_DRAIN)>;
i2c-gpio,delay-us = <5>;
status = "okay";
};
gpio-keys {
compatible = "gpio-keys";
key-user {
@@ -148,12 +230,16 @@
};
};
// buggy pwm driver, not working, please use userspace pwm api
/*
lcd0_backlight: pwm-backlight@0 {
compatible = "pwm-backlight";
pwm-names = "backlight";
pwms = <&pwm2 2 50000000>; // 20Khz
brightness-levels = <0 2 4 8 16 32 64 128 255>;
default-brightness-level = <4>;
};
*/
wifisd:wifi-sd@4320000 {
compatible = "cvitek,cv181x-sdio";

View File

@@ -8,7 +8,7 @@ CONFIG_PREEMPT=y
CONFIG_IKCONFIG=y
CONFIG_IKCONFIG_PROC=y
CONFIG_LOG_BUF_SHIFT=15
CONFIG_BLK_DEV_INITRD=n
CONFIG_BLK_DEV_INITRD=y
# CONFIG_SYSFS_SYSCALL is not set
# CONFIG_FHANDLE is not set
# CONFIG_BASE_FULL is not set
@@ -117,9 +117,13 @@ CONFIG_SERIAL_8250_DW=y
CONFIG_SERIAL_EARLYCON_RISCV_SBI=y
CONFIG_HW_RANDOM=y
CONFIG_I2C=y
CONFIG_I2C_SLAVE=y
CONFIG_I2C_SLAVE_EEPROM=y
CONFIG_I2C_DESIGNWARE_SLAVE=y
CONFIG_I2C_CHARDEV=y
CONFIG_I2C_MUX=y
CONFIG_I2C_DESIGNWARE_PLATFORM=y
CONFIG_I2C_GPIO=m
# CONFIG_PTP_1588_CLOCK is not set
CONFIG_PINCTRL=y
CONFIG_CVITEK_PINCTRL_CV1835=y
@@ -353,6 +357,8 @@ CONFIG_VIDEO_CVITEK_MIPI_TX=m
# end of Digital TV options
CONFIG_FB=y
# CONFIG_FB_TFT is not set
# CONFIG_FB_TFT_ST7789 is not set
CONFIG_FB_CVITEK=m
CONFIG_SOUND=y
CONFIG_SND=y
@@ -474,7 +480,7 @@ CONFIG_USB_CONFIGFS=y
CONFIG_USB_CONFIGFS_SERIAL=y
CONFIG_USB_CONFIGFS_ACM=y
# CONFIG_USB_CONFIGFS_OBEX is not set
# CONFIG_USB_CONFIGFS_NCM is not set
CONFIG_USB_CONFIGFS_NCM=y
CONFIG_USB_CONFIGFS_ECM=y
# CONFIG_USB_CONFIGFS_ECM_SUBSET is not set
CONFIG_USB_CONFIGFS_RNDIS=y
@@ -487,11 +493,11 @@ CONFIG_USB_CONFIGFS_F_UAC1=y
# CONFIG_USB_CONFIGFS_F_UAC1_LEGACY is not set
# CONFIG_USB_CONFIGFS_F_UAC2 is not set
# CONFIG_USB_CONFIGFS_F_MIDI is not set
# CONFIG_USB_CONFIGFS_F_HID is not set
CONFIG_USB_CONFIGFS_F_HID=y
CONFIG_USB_CONFIGFS_F_UVC=y
CONFIG_BUG=n
CONFIG_ADVISE_SYSCALLS=n
CONFIG_TIMERFD=n
CONFIG_TIMERFD=y
# for licheervnano
CONFIG_FB_SIMPLE=y
@@ -507,6 +513,9 @@ CONFIG_BT_HS=y
CONFIG_BT_LE=y
CONFIG_BT_HCIUART=y
CONFIG_BT_HCIUART_BCSP=y
CONFIG_BT_HCIUART_H4=y
CONFIG_BT_HCIUART_3WIRE=y
CONFIG_BT_HCIUART_RTL=y
CONFIG_SERIAL_DEV_BUS=y
CONFIG_SERIAL_DEV_CTRL_TTYPORT=y
CONFIG_SWAP=y
@@ -527,6 +536,8 @@ CONFIG_KEYBOARD_GPIO=y
CONFIG_INPUT_TOUCHSCREEN=y
CONFIG_TOUCHSCREEN_HYNITRON_TS=y
CONFIG_MAGIC_SYSRQ=y
CONFIG_INPUT_MISC=y
CONFIG_INPUT_UINPUT=y
# CONFIG_MAGIC_SYSRQ_SERIAL is not set
CONFIG_NEW_LEDS=y
CONFIG_LEDS_CLASS=y
@@ -548,17 +559,23 @@ CONFIG_VT=y
# CONFIG_LEGACY_PTYS is not set
CONFIG_BACKLIGHT_CLASS_DEVICE=m
CONFIG_BACKLIGHT_PWM=m
CONFIG_SPI=y
CONFIG_SPI_MASTER=y
CONFIG_SPI_DESIGNWARE=y
CONFIG_SPI_DW_MMIO=y
CONFIG_SPI_GPIO=m
CONFIG_SPI_SPIDEV=y
# these driver may broken codec driver
# CONFIG_FUSE_FS is not set
# CONFIG_CUSE is not set
# CONFIG_OVERLAY_FS is not set
# CONFIG_NAMESPACES is not set
CONFIG_NAMESPACES=y
# CONFIG_UTS_NS is not set
# CONFIG_IPC_NS is not set
# CONFIG_USER_NS is not set
CONFIG_USER_NS=y
# CONFIG_PID_NS is not set
# CONFIG_NET_NS is not set
CONFIG_NET_NS=y
# CONFIG_CGROUPS is not set
# CONFIG_MEMCG is not set
# CONFIG_BLK_CGROUP is not set
@@ -572,3 +589,422 @@ CONFIG_BACKLIGHT_PWM=m
CONFIG_EPOLL=y
CONFIG_IO_URING=y
CONFIG_SIGNALFD=y
CONFIG_EXFAT_FS=y
#
# Networking options
#
CONFIG_PACKET=y
CONFIG_PACKET_DIAG=y
CONFIG_UNIX=y
CONFIG_UNIX_SCM=y
CONFIG_UNIX_DIAG=y
# CONFIG_TLS is not set
# CONFIG_XFRM_USER is not set
# CONFIG_NET_KEY is not set
CONFIG_INET=y
CONFIG_IP_MULTICAST=y
CONFIG_IP_ADVANCED_ROUTER=y
CONFIG_IP_ROUTE_CLASSID=y
# CONFIG_IP_PNP is not set
# CONFIG_NET_IPIP is not set
CONFIG_NET_IPGRE=y
# CONFIG_NET_IPGRE_DEMUX is not set
CONFIG_IP_MULTIPLE_TABLES=y
# CONFIG_IP_MROUTE is not set
CONFIG_SYN_COOKIES=y
# CONFIG_NET_IPVTI is not set
# CONFIG_NET_FOU is not set
# CONFIG_INET_AH is not set
# CONFIG_INET_ESP is not set
# CONFIG_INET_IPCOMP is not set
# CONFIG_INET_DIAG is not set
CONFIG_TCP_CONG_ADVANCED=y
CONFIG_TCP_CONG_CUBIC=y
CONFIG_TCP_CONG_BBR=y
CONFIG_DEFAULT_TCP_CONG="cubic"
# CONFIG_TCP_MD5SIG is not set
CONFIG_IPV6=y
# CONFIG_IPV6_ROUTER_PREF is not set
# CONFIG_IPV6_OPTIMISTIC_DAD is not set
# CONFIG_INET6_AH is not set
# CONFIG_INET6_ESP is not set
# CONFIG_INET6_IPCOMP is not set
# CONFIG_IPV6_MIP6 is not set
# CONFIG_IPV6_ILA is not set
# CONFIG_IPV6_VTI is not set
# CONFIG_IPV6_SIT is not set
CONFIG_IPV6_TUNNEL=y
CONFIG_IPV6_GRE=y
CONFIG_IPV6_MULTIPLE_TABLES=y
# CONFIG_IPV6_MROUTE is not set
# CONFIG_IPV6_SEG6_LWTUNNEL is not set
# CONFIG_IPV6_SEG6_HMAC is not set
# CONFIG_IPV6_RPL_LWTUNNEL is not set
# CONFIG_MPTCP is not set
# CONFIG_NETWORK_SECMARK is not set
# CONFIG_NETWORK_PHY_TIMESTAMPING is not set
CONFIG_NETFILTER=y
CONFIG_NETFILTER_ADVANCED=y
#
# Core Netfilter Configuration
#
CONFIG_NETFILTER_INGRESS=y
CONFIG_NETFILTER_NETLINK=y
CONFIG_NETFILTER_FAMILY_ARP=y
CONFIG_NETFILTER_NETLINK_ACCT=y
CONFIG_NETFILTER_NETLINK_QUEUE=y
CONFIG_NETFILTER_NETLINK_LOG=y
CONFIG_NETFILTER_NETLINK_OSF=y
CONFIG_NF_CONNTRACK=y
CONFIG_NF_LOG_COMMON=y
CONFIG_NF_LOG_NETDEV=y
CONFIG_NETFILTER_CONNCOUNT=y
CONFIG_NF_CONNTRACK_MARK=y
CONFIG_NF_CONNTRACK_ZONES=y
CONFIG_NF_CONNTRACK_PROCFS=y
CONFIG_NF_CONNTRACK_EVENTS=y
CONFIG_NF_CONNTRACK_TIMEOUT=y
CONFIG_NF_CONNTRACK_TIMESTAMP=y
CONFIG_NF_CONNTRACK_LABELS=y
CONFIG_NF_CT_PROTO_DCCP=y
CONFIG_NF_CT_PROTO_GRE=y
CONFIG_NF_CT_PROTO_SCTP=y
CONFIG_NF_CT_PROTO_UDPLITE=y
CONFIG_NF_CONNTRACK_AMANDA=y
CONFIG_NF_CONNTRACK_FTP=y
CONFIG_NF_CONNTRACK_H323=y
CONFIG_NF_CONNTRACK_IRC=y
CONFIG_NF_CONNTRACK_BROADCAST=y
CONFIG_NF_CONNTRACK_NETBIOS_NS=y
CONFIG_NF_CONNTRACK_SNMP=y
CONFIG_NF_CONNTRACK_PPTP=y
CONFIG_NF_CONNTRACK_SANE=y
CONFIG_NF_CONNTRACK_SIP=y
CONFIG_NF_CONNTRACK_TFTP=y
CONFIG_NF_CT_NETLINK=y
CONFIG_NF_CT_NETLINK_TIMEOUT=y
CONFIG_NF_CT_NETLINK_HELPER=y
CONFIG_NETFILTER_NETLINK_GLUE_CT=y
CONFIG_NF_NAT=y
CONFIG_NF_NAT_AMANDA=y
CONFIG_NF_NAT_FTP=y
CONFIG_NF_NAT_IRC=y
CONFIG_NF_NAT_SIP=y
CONFIG_NF_NAT_TFTP=y
CONFIG_NF_NAT_REDIRECT=y
CONFIG_NF_NAT_MASQUERADE=y
CONFIG_NETFILTER_SYNPROXY=y
CONFIG_NF_TABLES=y
CONFIG_NF_TABLES_INET=y
CONFIG_NF_TABLES_NETDEV=y
CONFIG_NFT_NUMGEN=y
CONFIG_NFT_CT=y
# CONFIG_NFT_FLOW_OFFLOAD is not set
CONFIG_NFT_COUNTER=y
CONFIG_NFT_CONNLIMIT=y
CONFIG_NFT_LOG=y
CONFIG_NFT_LIMIT=y
CONFIG_NFT_MASQ=y
CONFIG_NFT_REDIR=y
CONFIG_NFT_NAT=y
CONFIG_NFT_TUNNEL=y
CONFIG_NFT_OBJREF=y
CONFIG_NFT_QUEUE=y
CONFIG_NFT_QUOTA=y
CONFIG_NFT_REJECT=y
CONFIG_NFT_REJECT_INET=y
CONFIG_NFT_COMPAT=y
CONFIG_NFT_HASH=y
CONFIG_NFT_FIB=y
# CONFIG_NFT_FIB_INET is not set
CONFIG_NFT_SOCKET=y
CONFIG_NFT_OSF=y
CONFIG_NFT_TPROXY=y
CONFIG_NFT_SYNPROXY=y
CONFIG_NF_DUP_NETDEV=y
CONFIG_NFT_DUP_NETDEV=y
CONFIG_NFT_FWD_NETDEV=y
# CONFIG_NFT_FIB_NETDEV is not set
CONFIG_NF_FLOW_TABLE_INET=y
CONFIG_NF_FLOW_TABLE=y
CONFIG_NETFILTER_XTABLES=y
#
# Xtables combined modules
#
CONFIG_NETFILTER_XT_MARK=y
CONFIG_NETFILTER_XT_CONNMARK=y
CONFIG_NETFILTER_XT_SET=y
#
# Xtables targets
#
# CONFIG_NETFILTER_XT_TARGET_CHECKSUM is not set
CONFIG_NETFILTER_XT_TARGET_CLASSIFY=y
CONFIG_NETFILTER_XT_TARGET_CONNMARK=y
# CONFIG_NETFILTER_XT_TARGET_CT is not set
# CONFIG_NETFILTER_XT_TARGET_DSCP is not set
CONFIG_NETFILTER_XT_TARGET_HL=y
CONFIG_NETFILTER_XT_TARGET_HMARK=y
CONFIG_NETFILTER_XT_TARGET_IDLETIMER=y
CONFIG_NETFILTER_XT_TARGET_LED=y
CONFIG_NETFILTER_XT_TARGET_LOG=y
CONFIG_NETFILTER_XT_TARGET_MARK=y
CONFIG_NETFILTER_XT_NAT=y
CONFIG_NETFILTER_XT_TARGET_NETMAP=y
CONFIG_NETFILTER_XT_TARGET_NFLOG=y
CONFIG_NETFILTER_XT_TARGET_NFQUEUE=y
# CONFIG_NETFILTER_XT_TARGET_NOTRACK is not set
CONFIG_NETFILTER_XT_TARGET_RATEEST=y
CONFIG_NETFILTER_XT_TARGET_REDIRECT=y
CONFIG_NETFILTER_XT_TARGET_MASQUERADE=y
CONFIG_NETFILTER_XT_TARGET_TEE=y
# CONFIG_NETFILTER_XT_TARGET_TPROXY is not set
# CONFIG_NETFILTER_XT_TARGET_TRACE is not set
CONFIG_NETFILTER_XT_TARGET_TCPMSS=y
# CONFIG_NETFILTER_XT_TARGET_TCPOPTSTRIP is not set
#
# Xtables matches
#
CONFIG_NETFILTER_XT_MATCH_ADDRTYPE=y
CONFIG_NETFILTER_XT_MATCH_BPF=y
CONFIG_NETFILTER_XT_MATCH_CLUSTER=y
CONFIG_NETFILTER_XT_MATCH_COMMENT=y
CONFIG_NETFILTER_XT_MATCH_CONNBYTES=y
CONFIG_NETFILTER_XT_MATCH_CONNLABEL=y
CONFIG_NETFILTER_XT_MATCH_CONNLIMIT=y
CONFIG_NETFILTER_XT_MATCH_CONNMARK=y
CONFIG_NETFILTER_XT_MATCH_CONNTRACK=y
CONFIG_NETFILTER_XT_MATCH_CPU=y
CONFIG_NETFILTER_XT_MATCH_DCCP=y
CONFIG_NETFILTER_XT_MATCH_DEVGROUP=y
CONFIG_NETFILTER_XT_MATCH_DSCP=y
CONFIG_NETFILTER_XT_MATCH_ECN=y
CONFIG_NETFILTER_XT_MATCH_ESP=y
CONFIG_NETFILTER_XT_MATCH_HASHLIMIT=y
CONFIG_NETFILTER_XT_MATCH_HELPER=y
CONFIG_NETFILTER_XT_MATCH_HL=y
CONFIG_NETFILTER_XT_MATCH_IPCOMP=y
CONFIG_NETFILTER_XT_MATCH_IPRANGE=y
CONFIG_NETFILTER_XT_MATCH_IPVS=y
CONFIG_NETFILTER_XT_MATCH_L2TP=y
CONFIG_NETFILTER_XT_MATCH_LENGTH=y
CONFIG_NETFILTER_XT_MATCH_LIMIT=y
CONFIG_NETFILTER_XT_MATCH_MAC=y
CONFIG_NETFILTER_XT_MATCH_MARK=y
CONFIG_NETFILTER_XT_MATCH_MULTIPORT=y
CONFIG_NETFILTER_XT_MATCH_NFACCT=y
CONFIG_NETFILTER_XT_MATCH_OSF=y
CONFIG_NETFILTER_XT_MATCH_OWNER=y
CONFIG_NETFILTER_XT_MATCH_PKTTYPE=y
CONFIG_NETFILTER_XT_MATCH_QUOTA=y
CONFIG_NETFILTER_XT_MATCH_RATEEST=y
CONFIG_NETFILTER_XT_MATCH_REALM=y
CONFIG_NETFILTER_XT_MATCH_RECENT=y
CONFIG_NETFILTER_XT_MATCH_SCTP=y
CONFIG_NETFILTER_XT_MATCH_SOCKET=y
CONFIG_NETFILTER_XT_MATCH_STATE=y
CONFIG_NETFILTER_XT_MATCH_STATISTIC=y
CONFIG_NETFILTER_XT_MATCH_STRING=y
CONFIG_NETFILTER_XT_MATCH_TCPMSS=y
CONFIG_NETFILTER_XT_MATCH_TIME=y
CONFIG_NETFILTER_XT_MATCH_U32=y
# end of Core Netfilter Configuration
CONFIG_IP_SET=y
CONFIG_IP_SET_MAX=256
# CONFIG_IP_SET_BITMAP_IP is not set
# CONFIG_IP_SET_BITMAP_IPMAC is not set
# CONFIG_IP_SET_BITMAP_PORT is not set
# CONFIG_IP_SET_HASH_IP is not set
# CONFIG_IP_SET_HASH_IPMARK is not set
# CONFIG_IP_SET_HASH_IPPORT is not set
# CONFIG_IP_SET_HASH_IPPORTIP is not set
# CONFIG_IP_SET_HASH_IPPORTNET is not set
# CONFIG_IP_SET_HASH_IPMAC is not set
# CONFIG_IP_SET_HASH_MAC is not set
# CONFIG_IP_SET_HASH_NETPORTNET is not set
# CONFIG_IP_SET_HASH_NET is not set
# CONFIG_IP_SET_HASH_NETNET is not set
# CONFIG_IP_SET_HASH_NETPORT is not set
# CONFIG_IP_SET_HASH_NETIFACE is not set
# CONFIG_IP_SET_LIST_SET is not set
CONFIG_IP_VS=y
# CONFIG_IP_VS_IPV6 is not set
# CONFIG_IP_VS_DEBUG is not set
CONFIG_IP_VS_TAB_BITS=12
#
# IPVS transport protocol load balancing support
#
# CONFIG_IP_VS_PROTO_TCP is not set
# CONFIG_IP_VS_PROTO_UDP is not set
# CONFIG_IP_VS_PROTO_ESP is not set
# CONFIG_IP_VS_PROTO_AH is not set
# CONFIG_IP_VS_PROTO_SCTP is not set
#
# IPVS scheduler
#
# CONFIG_IP_VS_RR is not set
# CONFIG_IP_VS_WRR is not set
# CONFIG_IP_VS_LC is not set
# CONFIG_IP_VS_WLC is not set
# CONFIG_IP_VS_FO is not set
# CONFIG_IP_VS_OVF is not set
# CONFIG_IP_VS_LBLC is not set
# CONFIG_IP_VS_LBLCR is not set
# CONFIG_IP_VS_DH is not set
# CONFIG_IP_VS_SH is not set
# CONFIG_IP_VS_MH is not set
# CONFIG_IP_VS_SED is not set
# CONFIG_IP_VS_NQ is not set
#
# IPVS SH scheduler
#
CONFIG_IP_VS_SH_TAB_BITS=8
#
# IPVS MH scheduler
#
CONFIG_IP_VS_MH_TAB_INDEX=12
#
# IPVS application helper
#
# CONFIG_IP_VS_NFCT is not set
#
# IP: Netfilter Configuration
#
CONFIG_NF_DEFRAG_IPV4=y
CONFIG_NF_SOCKET_IPV4=y
CONFIG_NF_TPROXY_IPV4=y
CONFIG_NF_TABLES_IPV4=y
CONFIG_NFT_REJECT_IPV4=y
CONFIG_NFT_DUP_IPV4=y
CONFIG_NFT_FIB_IPV4=y
CONFIG_NF_TABLES_ARP=y
CONFIG_NF_FLOW_TABLE_IPV4=y
CONFIG_NF_DUP_IPV4=y
CONFIG_NF_LOG_ARP=y
CONFIG_NF_LOG_IPV4=y
CONFIG_NF_REJECT_IPV4=y
CONFIG_NF_NAT_SNMP_BASIC=y
CONFIG_NF_NAT_PPTP=y
CONFIG_NF_NAT_H323=y
CONFIG_IP_NF_IPTABLES=y
CONFIG_IP_NF_MATCH_AH=y
CONFIG_IP_NF_MATCH_ECN=y
# CONFIG_IP_NF_MATCH_RPFILTER is not set
CONFIG_IP_NF_MATCH_TTL=y
CONFIG_IP_NF_FILTER=y
CONFIG_IP_NF_TARGET_REJECT=y
CONFIG_IP_NF_TARGET_SYNPROXY=y
CONFIG_IP_NF_NAT=y
CONFIG_IP_NF_TARGET_MASQUERADE=y
CONFIG_IP_NF_TARGET_NETMAP=y
CONFIG_IP_NF_TARGET_REDIRECT=y
CONFIG_IP_NF_MANGLE=y
CONFIG_IP_NF_TARGET_CLUSTERIP=y
CONFIG_IP_NF_TARGET_ECN=y
CONFIG_IP_NF_TARGET_TTL=y
CONFIG_IP_NF_RAW=y
CONFIG_IP_NF_ARPTABLES=y
CONFIG_IP_NF_ARPFILTER=y
CONFIG_IP_NF_ARP_MANGLE=y
# end of IP: Netfilter Configuration
#
# IPv6: Netfilter Configuration
#
CONFIG_NF_SOCKET_IPV6=y
CONFIG_NF_TPROXY_IPV6=y
CONFIG_NF_TABLES_IPV6=y
CONFIG_NFT_REJECT_IPV6=y
CONFIG_NFT_DUP_IPV6=y
CONFIG_NFT_FIB_IPV6=y
CONFIG_NF_FLOW_TABLE_IPV6=y
CONFIG_NF_DUP_IPV6=y
CONFIG_NF_REJECT_IPV6=y
CONFIG_NF_LOG_IPV6=y
CONFIG_IP6_NF_IPTABLES=y
CONFIG_IP6_NF_MATCH_AH=y
CONFIG_IP6_NF_MATCH_EUI64=y
CONFIG_IP6_NF_MATCH_FRAG=y
CONFIG_IP6_NF_MATCH_OPTS=y
CONFIG_IP6_NF_MATCH_HL=y
CONFIG_IP6_NF_MATCH_IPV6HEADER=y
CONFIG_IP6_NF_MATCH_MH=y
# CONFIG_IP6_NF_MATCH_RPFILTER is not set
CONFIG_IP6_NF_MATCH_RT=y
CONFIG_IP6_NF_MATCH_SRH=y
# CONFIG_IP6_NF_TARGET_HL is not set
CONFIG_IP6_NF_FILTER=y
CONFIG_IP6_NF_TARGET_REJECT=y
CONFIG_IP6_NF_TARGET_SYNPROXY=y
CONFIG_IP6_NF_MANGLE=y
CONFIG_IP6_NF_RAW=y
CONFIG_IP6_NF_NAT=y
CONFIG_IP6_NF_TARGET_MASQUERADE=y
CONFIG_IP6_NF_TARGET_NPT=y
# end of IPv6: Netfilter Configuration
CONFIG_NF_DEFRAG_IPV6=y
CONFIG_NF_CONNTRACK_BRIDGE=y
# CONFIG_BPFILTER is not set
# CONFIG_IP_DCCP is not set
# CONFIG_IP_SCTP is not set
# CONFIG_RDS is not set
# CONFIG_TIPC is not set
# CONFIG_ATM is not set
# CONFIG_L2TP is not set
# CONFIG_BRIDGE is not set
CONFIG_HAVE_NET_DSA=y
# CONFIG_NET_DSA is not set
# CONFIG_VLAN_8021Q is not set
# CONFIG_DECNET is not set
# CONFIG_LLC2 is not set
# CONFIG_ATALK is not set
# CONFIG_X25 is not set
# CONFIG_LAPB is not set
# CONFIG_PHONET is not set
# CONFIG_6LOWPAN is not set
# CONFIG_IEEE802154 is not set
# CONFIG_NET_SCHED is not set
# CONFIG_DCB is not set
# CONFIG_DNS_RESOLVER is not set
# CONFIG_BATMAN_ADV is not set
# CONFIG_OPENVSWITCH is not set
# CONFIG_VSOCKETS is not set
CONFIG_NETLINK_DIAG=y
# CONFIG_MPLS is not set
# CONFIG_NET_NSH is not set
# CONFIG_HSR is not set
# CONFIG_NET_SWITCHDEV is not set
# CONFIG_NET_L3_MASTER_DEV is not set
# CONFIG_QRTR is not set
# CONFIG_NET_NCSI is not set
CONFIG_NET_RX_BUSY_POLL=y
CONFIG_BQL=y
# CONFIG_BPF_JIT is not set
CONFIG_NETDEVICES=y
CONFIG_MII=y
CONFIG_NET_CORE=y
CONFIG_WIREGUARD=y
CONFIG_TUN=y
CONFIG_NET_IP_TUNNEL=y
CONFIG_NET_UDP_TUNNEL=y
CONFIG_VXLAN=y
CONFIG_USB_NET_RNDIS_WLAN=m
CONFIG_USB_SERIAL=y
CONFIG_USB_SERIAL_OPTION=y
CONFIG_USB_ACM=y
CONFIG_VETH=y

View File

@@ -40,7 +40,7 @@ class MemoryMap:
# =================
# Multimedia buffer. Used by u-boot/kernel/FreeRTOS
# =================
ION_SIZE = 75 * SIZE_1M
ION_SIZE = 105 * SIZE_1M
H26X_BITSTREAM_SIZE = 2 * SIZE_1M
H26X_ENC_BUFF_SIZE = 0
ISP_MEM_BASE_SIZE = 20 * SIZE_1M

View File

@@ -1,4 +1,4 @@
<physical_partition type="sd">
<partition label="BOOT" size_in_kb="80960" readonly="false" file="boot.sd"/>
<partition label="ROOTFS" size_in_kb="1048576" readonly="false" file="rootfs.sd" />
<partition label="ROOTFS" size_in_kb="1126400" readonly="false" file="rootfs.sd" />
</physical_partition>

View File

@@ -14,11 +14,16 @@ CONFIG_CP_EXT_WIRELESS=y
CONFIG_STORAGE_TYPE_sd=y
CONFIG_MIPI_PANEL_ZCT2133V1=y
CONFIG_SENSOR_GCORE_GC4653=y
CONFIG_SENSOR_OV_OV2685=y
CONFIG_SENSOR_OV_OS04A10=y
CONFIG_SENSOR_LONTIUM_LT6911=y
CONFIG_SENSOR_SMS_SC035GS=y
CONFIG_UBOOT_2021_10=y
CONFIG_KERNEL_SRC_5.10=y
CONFIG_KERNEL_UNCOMPRESSED=y
CONFIG_SKIP_RAMDISK=y
# CONFIG_SKIP_RAMDISK is not set
CONFIG_SENSOR_TUNING_PARAM_cv181x_src_gcore_gc4653=y
# CONFIG_SENSOR_TUNING_PARAM_sg200x_src_ov_os04a10=y
# CONFIG_ROOTFS_OVERLAYFS is not set
CONFIG_ENABLE_FREERTOS=y
# CONFIG_ENABLE_FREERTOS=y
# CONFIG_TARGET_PACKAGE_GATORD is not set

View File

@@ -88,6 +88,14 @@ int cvi_board_init(void)
mmio_write_32(0x030010E0, 0x0); // CMD
mmio_write_32(0x030010E4, 0x0); // CLK
// spi2 pinmux
// mmio_write_32(0x030010D0, 0x1); // CS
// mmio_write_32(0x030010DC, 0x1); // MISO
// mmio_write_32(0x030010E0, 0x1); // MOSI
// mmio_write_32(0x030010E4, 0x1); // SCK
// mmio_write_32(0x030010D8, 0x3); // DC
// mmio_write_32(0x03001038, 0x3); // RESET
// uart bluetooth
mmio_write_32(0x03001070, 0x1); // GPIOA 28 UART1 TX
mmio_write_32(0x03001074, 0x1); // GPIOA 29 UART1 RX
@@ -120,6 +128,15 @@ int cvi_board_init(void)
//mmio_write_32(0x0300116C, 0x5); // RX4N CAM_MCLK0 for alpha
mmio_write_32(0x0300118C, 0x5); // RX0N CAM_MCLK1 for beta
// spi1 on mipi csi
/*
mmio_write_32(0x0300116C, 0x7); // spi1 clk GPIOC2 MIPI_RX4N
mmio_write_32(0x03001170, 0x7); // spi1 cs GPIOC3 MIPI_RX4P
mmio_write_32(0x03001174, 0x7); // spi1 miso GPIOC4 MIPI_RX3N
mmio_write_32(0x03001178, 0x7); // spi1 mosi GPIOC5 MIPI_RX3P
*/
// camera/tp i2c
mmio_write_32(0x03001090, 0x5); // PWR_GPIO6 IIC4_SCL
mmio_write_32(0x03001098, 0x5); // PWR_GPIO8 IIC4_SDA
@@ -130,6 +147,16 @@ int cvi_board_init(void)
mmio_write_32(0x05027078, 0x11);// Unlock PWR_GPIO[3]
mmio_write_32(0x0502707c, 0x11);// Unlock PWR_GPIO[4]
// bitbang i2c
mmio_write_32(0x0300103C, 0x03); // GPIOA 15 GPIO_MODE
mmio_write_32(0x03001058, 0x03); // GPIOA 27 GPIO_MODE
// bitbang spi
mmio_write_32(0x03001060, 0x03); // GPIOA 24 GPIO_MODE
mmio_write_32(0x0300105C, 0x03); // GPIOA 23 GPIO_MODE
mmio_write_32(0x03001054, 0x03); // GPIOA 25 GPIO_MODE
mmio_write_32(0x03001050, 0x03); // GPIOA 22 GPIO_MODE
// wait hardware bootup
suck_loop(50);
user_led_off();

View File

@@ -63,3 +63,4 @@ CONFIG_BMP_32BPP=y
CONFIG_BOOTLOGO=y
CONFIG_CMD_CVI_VO=y
CONFIG_CMD_GPIO=y
CONFIG_CMD_MBR=y

View File

@@ -242,6 +242,28 @@ function pack_burn_image
popd
)}
function pack_usbdl_image
{(
pushd "$OUTPUT_DIR"
[ -d tmp ] && rm -rf tmp
set -eux
cp -rf $TOOLS_PATH/cv181x/usb_dl $OUTPUT_DIR
cd usb_dl
unzip -o $OUTPUT_DIR/upgrade.zip
cp $OUTPUT_DIR/fip.bin ./
set +eux
echo "========================================="
echo ""
echo "usb flash command:"
echo ""
echo "cd $OUTPUT_DIR/usb_dl && python3 cv181x_dl.py"
echo ""
echo ""
echo "========================================="
popd
)}
function pack_prog_img
{(
local tmp_dir

View File

@@ -621,6 +621,7 @@ function build_all()
pack_data || return $?
pack_system || return $?
pack_upgrade || return $?
pack_usbdl_image || return $?
pack_burn_image || return $?
)}

View File

@@ -25,6 +25,7 @@ fsbl%: export FSBL_SECURE_BOOT_SUPPORT=${CONFIG_FSBL_SECURE_BOOT_SUPPORT}
fsbl%: export ARCH=$(call qstrip,${CONFIG_ARCH})
fsbl%: export OD_CLK_SEL=${CONFIG_OD_CLK_SEL}
fsbl%: export VC_CLK_OVERDRIVE=${CONFIG_VC_CLK_OVERDRIVE}
fsbl%: export TPU_PERF_MODE=$(shell if [ "${CONFIG_CHIP_cv1812cp}" = "y" ] || [ "${CONFIG_CHIP_sg2002}" = "y" ]; then echo "y";else echo "n";fi)
fsbl-build: u-boot-build memory-map
$(call print_target)
${Q}mkdir -p ${FSBL_PATH}/build

View File

@@ -31,6 +31,7 @@
"OV_OS04C10_SLAVE",
"OV_OS08A20",
"OV_OS08A20_SLAVE",
"OV_OV2685",
"OV_OV4689",
"OV_OV5647",
"OV_OV6211",

View File

@@ -5,8 +5,12 @@ image boot.vfat {
"fip.bin",
"rawimages/boot.sd",
"usb.dev",
"usb.rndis0",
"usb.ncm",
"usb.rndis",
"wifi.sta",
"gt9xx",
"logo.jpeg",
"ver",
}
}
size = 16M

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

View File

@@ -16,7 +16,8 @@ fi
output_dir=$1
echo ${output_dir}
set -eu
image=`LC_ALL=C date +%F-%R | sed -e 's/:/-/g' | tr -d '( ):'`.img
git_id=$(git rev-parse HEAD | head -c 6)
image=$(LC_ALL=C date +%F-%R | sed -e 's/:/-/g' | tr -d '( ):')-${git_id}.img
THISDIR=$(dirname $(realpath $0))
mkdir -pv ${output_dir}/tmp/
mkdir -pv ${output_dir}/root/
@@ -26,10 +27,14 @@ cp -fv ${output_dir}/fip.bin ${output_dir}/input/
cp -fv ${output_dir}/rawimages/boot.sd ${output_dir}/input/rawimages/
cp -fv ${output_dir}/rawimages/rootfs.sd ${output_dir}/input/
touch ${output_dir}/input/usb.dev
touch ${output_dir}/input/usb.rndis0
touch ${output_dir}/input/usb.ncm
touch ${output_dir}/input/usb.rndis
touch ${output_dir}/input/wifi.sta
touch ${output_dir}/input/gt9xx
touch ${output_dir}/input/fb
echo ${image} > ${output_dir}/input/ver
cp -fv ${THISDIR}/genimage_rootless.cfg ${output_dir}/genimage.cfg
cp -fv ${THISDIR}/logo.jpeg ${output_dir}/input/logo.jpeg
sed -i -e "s/duo.img/${image}/g" ${output_dir}/genimage.cfg
cd ${output_dir}/
${THISDIR}/genimage

View File

@@ -83,6 +83,8 @@ class XmlParser:
if self.storage == "emmc":
self.__calEmmcOffset(parts)
if self.storage == "sd":
self.__calEmmcOffset(parts)
elif self.storage == "spinor":
self.__calNorOffset(parts)
elif self.storage == "spinand":

View File

@@ -41,8 +41,8 @@ def parse_Args():
type=str)
parser.add_argument(
'--pid',
metavar='1001',
default='1001',
metavar='1000',
default='1000',
type=str)
parser.add_argument(
"-v",

View File

@@ -0,0 +1,69 @@
# This file is part of avahi.
#
# avahi is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# avahi is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
# License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with avahi; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
# USA.
# See avahi-daemon.conf(5) for more information on this configuration
# file!
[server]
#host-name=foo
#domain-name=local
#browse-domains=0pointer.de, zeroconf.org
use-ipv4=yes
use-ipv6=yes
#allow-interfaces=eth0
#deny-interfaces=eth1
#check-response-ttl=no
#use-iff-running=no
#enable-dbus=yes
#disallow-other-stacks=no
#allow-point-to-point=no
#cache-entries-max=4096
#clients-max=4096
#objects-per-client-max=1024
#entries-per-entry-group-max=32
ratelimit-interval-usec=1000000
ratelimit-burst=1000
[wide-area]
enable-wide-area=yes
[publish]
#disable-publishing=no
#disable-user-service-publishing=no
#add-service-cookie=no
publish-addresses=yes
publish-hinfo=yes
publish-workstation=yes
#publish-domain=yes
#publish-dns-servers=192.168.50.1, 192.168.50.2
#publish-resolv-conf-dns-servers=yes
#publish-aaaa-on-ipv4=yes
#publish-a-on-ipv6=no
[reflector]
#enable-reflector=no
#reflect-ipv=no
#reflect-filters=_airplay._tcp.local,_raop._tcp.local
[rlimits]
#rlimit-as=
#rlimit-core=0
#rlimit-data=8388608
#rlimit-fsize=0
#rlimit-nofile=768
#rlimit-stack=8388608
#rlimit-nproc=3

View File

@@ -15,7 +15,7 @@ then
insmod soph_vpss.ko
insmod soph_dwa.ko
insmod soph_vo.ko
insmod soph_mipi_tx.ko
# insmod soph_mipi_tx.ko
insmod soph_rgn.ko
insmod soph_wdt.ko
insmod soph_clock_cooling.ko

View File

@@ -0,0 +1,31 @@
#!/bin/sh
if ! command -v i2cget &> /dev/null
then
echo "i2cdetect not find, please install i2c-tools"
exit 1
fi
pmu_version=$(i2cget -y 4 0x34 0x03)
pmu_version=$((pmu_version & 0xCF))
chip_id_1=$(printf "%d" 0x47)
chip_id_2=$(printf "%d" 0x4a)
if [ "$pmu_version" -eq "$chip_id_1" ] || [ "$pmu_version" -eq "$chip_id_2" ]; then
case "$1" in
start)
exec /usr/bin/axp2101
echo "Starting PMU: OK\n"
;;
stop)
runlevel=$(cat /run/runlevel | awk '{ print $1 }')
if [ "$runlevel" = "0" ]; then
printf "Stopping PMU\n"
value=$(i2cget -y 4 0x34 0x10)
value=$((value | 0x01))
i2cset -y 4 0x34 0x10 $value
fi
;;
esac
fi

View File

@@ -8,11 +8,23 @@ then
then
cp -vf /boot/sshd_config /etc/ssh/sshd_config
fi
if [ -e /boot/resolv.conf ]
then
rm -rf /etc/resolv.conf
cp -vf /boot/resolv.conf /etc/resolv.conf
fi
if [ -e /boot/input-event-daemon ]
then
chmod 0644 /etc/input-event-daemon.conf
if [ ! -e /etc/input-event-daemon.conf ]
then
cp /etc/input-event-daemon.conf.bak /etc/input-event-daemon.conf
fi
else
chmod 0000 /etc/input-event-daemon.conf
if [ -e /etc/input-event-daemon.conf ]
then
cp /etc/input-event-daemon.conf /etc/input-event-daemon.conf.bak
rm /etc/input-event-daemon.conf
fi
fi
if [ -e /boot/rc.local ]
then
@@ -24,7 +36,7 @@ then
fi
if [ -e /boot/console_handler.sh ]
then
cp /boot/ttyGS0_handler.sh /etc/ttyGS0_handler.sh
cp /boot/console_handler.sh /etc/console_handler.sh
fi
if [ -e /boot/alpha ]
then
@@ -32,6 +44,10 @@ then
then
cp /mnt/data/sensor_cfg.ini.alpha /mnt/data/sensor_cfg.ini
fi
if [ $(cat /mnt/data/sensor_cfg.ini | wc -l) -eq 0 ]
then
cp /mnt/data/sensor_cfg.ini.beta /mnt/data/sensor_cfg.ini
fi
# MIPI RX 4N PINMUX MCLK0
devmem 0x0300116C 32 0x5
# MIPI RX 0N PINMUX MIPIP RX 0N
@@ -42,11 +58,19 @@ then
then
cp /mnt/data/sensor_cfg.ini.beta /mnt/data/sensor_cfg.ini
fi
if [ $(cat /mnt/data/sensor_cfg.ini | wc -l) -eq 0 ]
then
cp /mnt/data/sensor_cfg.ini.beta /mnt/data/sensor_cfg.ini
fi
# MIPI RX 4N PINMUX MIPI RX 4N
devmem 0x0300116C 32 0x3
# MIPI RX 0N PINMUX MCLK1
devmem 0x0300118C 32 0x5
echo -n " beta "
fi
if [ -e /boot/kvmtest ]
then
cp /mnt/data/sensor_cfg.ini.LT /mnt/data/sensor_cfg.ini
fi
echo "OK"
fi

View File

@@ -1,5 +1,6 @@
#!/bin/sh
if [ "$1" = "start" ]
then
. /etc/profile
@@ -11,26 +12,56 @@ then
then
echo "usb mode: device"
cd /sys/kernel/config/usb_gadget
mkdir g0
mkdir -p g0
cd g0
if [ -e /boot/usb.idVendor ]
then
cat /boot/usb.idVendor > idVendor
else
echo 0x3346 > idVendor
echo 0x359F > idVendor
fi
if [ -e /boot/usb.idProduct ]
then
cat /boot/usb.idProduct > idProduct
else
echo 0x1009 > idProduct
echo 0x2120 > idProduct
fi
mkdir strings/0x409
if [ -e /boot/usb.bcdDevice ]
then
cat /boot/usb.bcdDevice > bcdDevice
else
echo 0x0300 > bcdDevice
fi
if [ -e /boot/usb.bcdUSB ]
then
cat /boot/usb.bcdUSB > bcdUSB
else
echo 0x0200 > bcdUSB
fi
if [ -e /boot/usb.bDeviceClass ]
then
cat /boot/usb.bDeviceClass > bDeviceClass
else
echo 0xef > bDeviceClass
fi
if [ -e /boot/usb.bDeviceSubClass ]
then
cat /boot/usb.bDeviceSubClass > bDeviceSubClass
else
echo 0x02 > bDeviceSubClass
fi
if [ -e /boot/usb.bDeviceProtocol ]
then
cat /boot/usb.bDeviceProtocol > bDeviceProtocol
else
echo 0x01 > bDeviceProtocol
fi
mkdir -p strings/0x409
if [ -e /boot/usb.serialnumber ]
then
cat /boot/usb.serialnumber > strings/0x409/serialnumber
else
echo '0123456789ABCDEF' > strings/0x409/serialnumber
cat /device_key > strings/0x409/serialnumber
fi
if [ -e /boot/usb.manufacturer ]
then
@@ -44,20 +75,18 @@ then
else
echo 'licheervnano' > strings/0x409/product
fi
mkdir configs/c.1
mkdir -p configs/c.1
if [ -e /boot/usb.GS0 ]
then
mkdir functions/acm.GS0
mkdir -p functions/acm.GS0
rm -rf configs/c.1/acm.GS0
ln -s functions/acm.GS0 configs/c.1/
fi
if [ -e /boot/usb.rndis0 ]
then
mkdir functions/rndis.usb0
ln -s functions/rndis.usb0 configs/c.1/
fi
if [ -e /boot/usb.disk0 ]
then
mkdir functions/mass_storage.disk0
mkdir -p functions/mass_storage.disk0
rm -rf configs/c.1/mass_storage.disk0
ln -s functions/mass_storage.disk0 configs/c.1/
echo 1 > functions/mass_storage.disk0/lun.0/removable
if [ -e /boot/usb.disk0.ro ]
@@ -78,6 +107,60 @@ then
cat /boot/usb.disk0 > functions/mass_storage.disk0/lun.0/file
fi
fi
# rndis
if [ -e /boot/usb.rndis ]
then
mkdir -p functions/rndis.usb0
ln -s functions/rndis.usb0 configs/c.1/
echo e0 > functions/rndis.usb0/class
echo 01 > functions/rndis.usb0/subclass
echo 03 > functions/rndis.usb0/protocol
fi
# ncm
if [ -e /boot/usb.ncm ]
then
mkdir -p functions/ncm.usb0
ln -s functions/ncm.usb0 configs/c.1/
fi
# keyboard
if [ -e /boot/usb.keyboard ]
then
mkdir functions/hid.GS0
# echo 1 > functions/hid.GS0/subclass
echo 1 > functions/hid.GS0/wakeup_on_write
echo 1 > functions/hid.GS0/protocol
echo 6 > functions/hid.GS0/report_length
echo -ne \\x05\\x01\\x09\\x06\\xa1\\x01\\x05\\x07\\x19\\xe0\\x29\\xe7\\x15\\x00\\x25\\x01\\x75\\x01\\x95\\x08\\x81\\x02\\x95\\x01\\x75\\x08\\x81\\x03\\x95\\x05\\x75\\x01\\x05\\x08\\x19\\x01\\x29\\x05\\x91\\x02\\x95\\x01\\x75\\x03\\x91\\x03\\x95\\x06\\x75\\x08\\x15\\x00\\x25\\x65\\x05\\x07\\x19\\x00\\x29\\x65\\x81\\x00\\xc0 > functions/hid.GS0/report_desc
ln -s functions/hid.GS0 configs/c.1
fi
# mouse
if [ -e /boot/usb.mouse ]
then
mkdir functions/hid.GS1
# echo 1 > functions/hid.GS1/subclass
echo 1 > functions/hid.GS1/wakeup_on_write
echo 2 > functions/hid.GS1/protocol
echo -ne \\x34 > functions/hid.GS1/report_length
echo -ne \\x5\\x1\\x9\\x2\\xa1\\x1\\x9\\x1\\xa1\\x0\\x5\\x9\\x19\\x1\\x29\\x3\\x15\\x0\\x25\\x1\\x95\\x3\\x75\\x1\\x81\\x2\\x95\\x1\\x75\\x5\\x81\\x3\\x5\\x1\\x9\\x30\\x9\\x31\\x9\\x38\\x15\\x81\\x25\\x7f\\x75\\x8\\x95\\x3\\x81\\x6\\xc0\\xc0 > functions/hid.GS1/report_desc
ln -s functions/hid.GS1 configs/c.1
fi
# touchpad
if [ -e /boot/usb.touchpad ]
then
mkdir functions/hid.GS2
# echo 1 > functions/hid.GS2/subclass
echo 1 > functions/hid.GS2/wakeup_on_write
echo 2 > functions/hid.GS2/protocol
echo 6 > functions/hid.GS2/report_length
echo -ne \\x05\\x01\\x09\\x02\\xa1\\x01\\x09\\x01\\xa1\\x00\\x05\\x09\\x19\\x01\\x29\\x03\\x15\\x00\\x25\\x01\\x95\\x03\\x75\\x01\\x81\\x02\\x95\\x01\\x75\\x05\\x81\\x01\\x05\\x01\\x09\\x30\\x09\\x31\\x15\\x00\\x26\\xff\\x7f\\x35\\x00\\x46\\xff\\x7f\\x75\\x10\\x95\\x02\\x81\\x02\\x05\\x01\\x09\\x38\\x15\\x81\\x25\\x7f\\x35\\x00\\x45\\x00\\x75\\x08\\x95\\x01\\x81\\x06\\xc0\\xc0 > functions/hid.GS2/report_desc
ln -s functions/hid.GS2 configs/c.1
fi
ls /sys/class/udc/ | cat > UDC
echo device > /proc/cviusb/otg_role
fi
@@ -85,6 +168,20 @@ fi
if [ "$1" = "stop" ]
then
# rndis
if [ -e /sys/kernel/config/usb_gadget/g0/configs/c.1/rndis.usb0 ]
then
unlink /sys/kernel/config/usb_gadget/g0/configs/c.1/rndis.usb0
rmdir /sys/kernel/config/usb_gadget/g0/functions/rndis.usb0
fi
# ncm
if [ -e /sys/kernel/config/usb_gadget/g0/configs/c.1/ncm.usb0 ]
then
unlink /sys/kernel/config/usb_gadget/g0/configs/c.1/ncm.usb0
rmdir /sys/kernel/config/usb_gadget/g0/functions/ncm.usb0
fi
echo '' > /sys/kernel/config/usb_gadget/g0/UDC
echo host > /proc/cviusb/otg_role
fi

View File

@@ -0,0 +1,33 @@
#!/bin/sh
if [ "$1" = "start" ]
then
. /etc/profile
if [ ! -e /boot/alpha ]
then
devmem 0x030010AC 32 0x04 # PINMUX PWM10
blpwm="/sys/class/pwm/pwmchip8/pwm2/"
if [ ! -e "${blpwm}" ]
then
echo 2 > /sys/class/pwm/pwmchip8/export
fi
echo 0 > $blpwm/enable
echo "10000" > ${blpwm}/period # 100KHZ
panel_value=""
if [ -e /boot/board ]
then
panel_value=$(grep '^panel=' /boot/board | cut -d '=' -f 2)
elif [ -e /boot/uEnv.txt ]
then
panel_value=$(grep '^panel=' /boot/uEnv.txt | cut -d '=' -f 2)
fi
if [ "$panel_value" = "st7701_hd228001c31" ]
then
echo "2000" > ${blpwm}/duty_cycle # 20%
else
echo "9000" > ${blpwm}/duty_cycle
fi
echo 1 > $blpwm/enable
fi
exit 0
fi

View File

@@ -3,6 +3,23 @@
if [ "$1" = "start" ]
then
. /etc/profile
panel_value=""
if [ -e /boot/board ]
then
panel_value=$(grep '^panel=' /boot/board | cut -d '=' -f 2)
elif [ -e /boot/uEnv.txt ]
then
panel_value=$(grep '^panel=' /boot/uEnv.txt | cut -d '=' -f 2)
fi
if [ "$panel_value" = "st7701_lct024bsi20" ]
then
echo "load cst7xx touchscreen driver"
insmod /mnt/system/ko/hynitron_touch_new.ko
elif [ "$panel_value" = "st7701_hd228001c31" ]
then
echo "load cst3xx touchscreen driver"
insmod /mnt/system/ko/hynitron_touch.ko
fi
if [ -e /boot/gt9xx ]
then
echo "load gt9xx touchscreen driver"

View File

@@ -45,18 +45,4 @@ then
ip link set eth0 address ${new_ethmac}
ifconfig eth0 up
echo "ethernet mac address: ${new_ethmac}"
if [ -e /boot/usb.rndis0 ]
then
if [ -e /boot/usb.rndis0.mac ]
then
new_rndismac=$(cat /boot/usb.rndis0.mac)
else
new_rndismac=$(hex2mac 48da356e$(sha512sum /sys/class/cvi-base/base_uid | head -c 4))
fi
ifconfig usb0 down
ip link set usb0 address ${new_rndismac}
ifconfig usb0 up
echo "rndis mac address: ${new_rndismac}"
fi
fi

View File

@@ -8,6 +8,7 @@ then
insmod cfg80211.ko
insmod 3rd/aic8800_bsp.ko
insmod 3rd/aic8800_fdrv.ko
insmod 3rd/8733bs.ko
echo "OK"
exit 0
fi

View File

@@ -1,70 +0,0 @@
#!/bin/sh
. /etc/profile
gen_udhcpd_conf() {
interface=${1}
ipv4_prefix=${2}
echo "start ${ipv4_prefix}.100"
echo "end ${ipv4_prefix}.200"
echo "interface ${interface}"
echo "pidfile /var/run/udhcpd.${interface}.pid"
echo "lease_file /var/lib/misc/udhcpd.${interface}.leases"
echo "option subnet 255.255.255.0"
echo "option lease 864000"
}
start() {
if [ -e /boot/usb.rndis0 ]
then
printf "start usb rndis: "
if [ ! -e /boot/rndis.nodhcpd ]
then
if [ -e /boot/rndis.ipv4_prefix ]
then
ipv4_prefix=`cat /boot/rndis.ipv4_prefix`
else
id2=$(printf "%d" 0x$(sha512sum /sys/class/cvi-base/base_uid | head -c 2))
id3=$(printf "%d" 0x$(sha512sum /sys/class/cvi-base/base_uid | head -c 4 | tail -c 2))
if [ "$id2" = "$id3" ]
then
id2=$((id2 + 1))
fi
if [ "$id2" -ge 255 ]
then
id2=253
fi
if [ "$id3" -ge 255 ]
then
id3=254
fi
ipv4_prefix=10.$id2.$id3
fi
gen_udhcpd_conf usb0 "${ipv4_prefix}" > /etc/udhcpd.usb0.conf
ip addr add $ipv4_prefix.1/24 dev usb0
udhcpd -S /etc/udhcpd.usb0.conf
fi
echo "ok"
fi
}
stop() {
kill `cat /var/run/udhcpd.usb0.pid`
rm /var/run/udhcpd.usb0.pid
}
restart() {
start
stop
}
if [ "${1}" = "start" ]
then
start
elif [ "${1}" = "stop" ]
then
stop
elif [ "${1}" = "restart" ]
then
restart
fi

View File

@@ -39,13 +39,13 @@ gen_udhcpd_conf() {
start() {
if [ -e /boot/wifi.sta ]
then
echo "wifi mode: sta"
if [ -e /boot/wpa_supplicant.conf ]
then
cp /boot/wpa_supplicant.conf /etc/wpa_supplicant.conf
else
echo "wifi mode: sta"
ssid="licheervnano"
pass="licheervnano"
ssid=""
pass=""
if [ -e /boot/wifi.ssid ]
then
echo -n "ssid: "
@@ -58,8 +58,11 @@ start() {
cat /boot/wifi.pass
pass=`cat /boot/wifi.pass`
fi
echo "ctrl_interface=/var/run/wpa_supplicant" > /etc/wpa_supplicant.conf
wpa_passphrase "$ssid" "$pass" >> /etc/wpa_supplicant.conf
if [ ! -z "${ssid}${pass}" ]
then
echo "ctrl_interface=/var/run/wpa_supplicant" > /etc/wpa_supplicant.conf
wpa_passphrase "$ssid" "$pass" >> /etc/wpa_supplicant.conf
fi
fi
wpa_supplicant -B -i wlan0 -c /etc/wpa_supplicant.conf
if [ ! -e /boot/wifi.nodhcp ]
@@ -68,11 +71,11 @@ start() {
fi
elif [ -e /boot/wifi.ap ]
then
echo "wifi mode: ap"
if [ -e /boot/hostapd.conf ]
then
cp /boot/hostapd.conf /etc/hostapd.conf
else
echo "wifi mode: ap"
id2=$(printf "%d" 0x$(sha512sum /sys/class/cvi-base/base_uid | head -c 2))
id3=$(printf "%d" 0x$(sha512sum /sys/class/cvi-base/base_uid | head -c 4 | tail -c 2))
if [ "$id2" = "$id3" ]
@@ -88,30 +91,40 @@ start() {
id3=254
fi
ssid="licheervnano-${id2}${id3}"
pass="licheervnano"
if [ -e /boot/wifi.ssid ]
then
echo -n "ssid: "
cat /boot/wifi.ssid
ssid=`cat /boot/wifi.ssid`
fi
if [ -e /boot/wifi.pass ]
then
echo -n "wifi.pass: "
cat /boot/wifi.pass
pass=`cat /boot/wifi.pass`
fi
gen_hostapd_conf "$ssid" "$pass" > /etc/hostapd.conf
if [ -e /boot/wifi.ipv4_prefix ]
pass="licheervnano"
if [ -e /boot/wifi.ssid ]
then
ipv4_prefix=`cat /boot/rndis.ipv4_prefix`
else
ipv4_prefix=10.$id3.$id2
echo -n "ssid: "
cat /boot/wifi.ssid
ssid=`cat /boot/wifi.ssid`
fi
gen_udhcpd_conf wlan0 "${ipv4_prefix}" > /etc/udhcpd.wlan0.conf
ifconfig wlan0 up
ip addr add $ipv4_prefix.1/24 dev wlan0
if [ -e /boot/wifi.pass ]
then
echo -n "wifi.pass: "
cat /boot/wifi.pass
pass=`cat /boot/wifi.pass`
fi
gen_hostapd_conf "$ssid" "$pass" > /etc/hostapd.conf
fi
if [ -e /boot/wifi.ipv4_prefix ]
then
ipv4_prefix=`cat /boot/wifi.ipv4_prefix`
else
ipv4_prefix=10.$id3.$id2
fi
if [ ! -e /etc/udhcpd.wlan0.conf ]
then
gen_udhcpd_conf wlan0 "${ipv4_prefix}" > /etc/udhcpd.wlan0.conf
fi
ifconfig wlan0 up
ip route del default || true
# routes=$(ip route show | grep 'dev wlan0' | awk '{print $1}')
# for route in $routes; do
# ip route del $route dev wlan0
# echo "Deleted route $route dev wlan0"
# done
ip add flush dev wlan0
ip addr add $ipv4_prefix.1/24 dev wlan0
hostapd -B -i wlan0 /etc/hostapd.conf
udhcpd -S /etc/udhcpd.wlan0.conf
elif [ -e /boot/wifi.mon ]
@@ -122,17 +135,25 @@ start() {
}
stop() {
killall wpa_supplicant
kill `cat /run/udhcpc.wlan0.pid`
rm /run/udhcpc.wlan0.pid
kill `cat /var/run/udhcpd.wlan0.pid`
rm /var/run/udhcpd.wlan0.pid
airmon-ng stop wlan0mon
ps -ef|grep hostapd|grep -v grep|awk '{print $1}'|xargs kill -2 || true
ps -ef|grep "udhcpd -S /etc/udhcpd.wlan0.conf" |grep -v grep|awk '{print $1}'|xargs kill -2 || true
killall wpa_supplicant || true
if [ -e /run/udhcpc.wlan0.pid ]
then
kill `cat /run/udhcpc.wlan0.pid` || true
rm -f /run/udhcpc.wlan0.pid
fi
if [ -e /var/run/udhcpd.wlan0.pid ]
then
kill `cat /var/run/udhcpd.wlan0.pid` || true
rm -f /var/run/udhcpd.wlan0.pid
fi
airmon-ng stop wlan0mon || true
}
restart() {
start
stop
start
}
if [ "${1}" = "start" ]

View File

@@ -10,5 +10,5 @@ then
100%
" | parted ---pretend-input-tty /dev/mmcblk0 "resizepart 2 100%"
# resize data filesystem
(resize2fs /dev/mmcblk0p2 &> /dev/console) &
(resize2fs /dev/mmcblk0p2) &
fi

View File

@@ -2,7 +2,7 @@
echo "HELLO WORLD"
if [ -e /boot/maxicam ]
if [ -e /boot/maixcam ]
then
/maixapp/apps/launcher/launcher &
fi

View File

@@ -15,10 +15,9 @@
#ListenAddress 0.0.0.0
#ListenAddress ::
#HostKey /etc/ssh/ssh_host_rsa_key
#HostKey /etc/ssh/ssh_host_ecdsa_key
# generate rsa & ecdsa use a lot of time, so disable it
# some old ssh utils need rsa & ecdsa
HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
HostKey /etc/ssh/ssh_host_ed25519_key
# Ciphers and keying

View File

@@ -4,7 +4,13 @@
[ -z "$1" ] && echo "Error: should be called from udhcpc" && exit 1
ACTION="$1"
RESOLV_CONF="/etc/resolv.conf"
if [ -e /boot/resolv.conf ]
then
RESOLV_CONF="/etc/resolv.conf.dhcp"
fi
[ -e $RESOLV_CONF ] || touch $RESOLV_CONF
[ -n "$broadcast" ] && BROADCAST="broadcast $broadcast"
[ -n "$subnet" ] && NETMASK="netmask $subnet"
@@ -18,7 +24,7 @@ fi
wait_for_ipv6_default_route() {
printf "Waiting for IPv6 default route to appear"
while [ $IF_WAIT_DELAY -gt 0 ]; do
if [ -z "$(ip -6 route list | grep default)" ]; then
if ip -6 route list | grep -q default; then
printf "\n"
return
fi
@@ -29,7 +35,7 @@ wait_for_ipv6_default_route() {
printf " timeout!\n"
}
case "$1" in
case "$ACTION" in
deconfig)
/sbin/ifconfig $interface up
/sbin/ifconfig $interface 0.0.0.0
@@ -115,7 +121,7 @@ esac
HOOK_DIR="$0.d"
for hook in "${HOOK_DIR}/"*; do
[ -f "${hook}" -a -x "${hook}" ] || continue
"${hook}" "${@}"
"${hook}" "$ACTION"
done
exit 0

View File

@@ -60,6 +60,12 @@ BR2_PACKAGE_WIRELESS_TOOLS_LIB=y
BR2_PACKAGE_AIRCRACK_NG=y
BR2_PACKAGE_UTIL_LINUX_RFKILL=y
BR2_PACKAGE_IPERF3=y
BR2_PACKAGE_IPMITOOL=y
BR2_PACKAGE_IPMITOOL_PEN_REG_URI=y
BR2_PACKAGE_IPMITOOL_LANPLUS=y
BR2_PACKAGE_IPMITOOL_USB=y
BR2_PACKAGE_IPMITOOL_IPMIEVD=y
BR2_PACKAGE_IPMITOOL_IPMISHELL=y
BR2_PACKAGE_ETHTOOL=y
BR2_PACKAGE_DNSMASQ=y
BR2_PACKAGE_DNSMASQ_DHCP=y
@@ -70,7 +76,9 @@ BR2_PACKAGE_WIRELESS_REGDB=y
BR2_PACKAGE_MOSH=y
BR2_PACKAGE_LRZSZ=y
BR2_PACKAGE_IW=y
# BR2_PACKAGE_WIREGUARD=y
BR2_PACKAGE_WIREGUARD_TOOLS=y
# BR2_PACKAGE_WIREGUARD_LINUX_COMPAT=y
BR2_PACKAGE_WPA_SUPPLICANT=y
BR2_PACKAGE_WPA_SUPPLICANT_NL80211=y
BR2_PACKAGE_WPA_SUPPLICANT_WPA3=y
@@ -138,6 +146,7 @@ BR2_PACKAGE_CA_CERTIFICATES=y
BR2_PACKAGE_EVTEST=y
BR2_PACKAGE_FILE=y
BR2_PACKAGE_EMPTY=y
BR2_PACKAGE_EXFATPROGS=y
BR2_PACKAGE_E2FSPROGS=y
BR2_PACKAGE_E2FSPROGS_RESIZE2FS=y
BR2_PACKAGE_TMUX=y
@@ -172,21 +181,26 @@ BR2_PACKAGE_TCPDUMP=y
BR2_PACKAGE_SSDP_RESPONDER=y
BR2_PACKAGE_PPPD=y
BR2_PACKAGE_NFTABLES=y
BR2_PACKAGE_BIND=y
BR2_PACKAGE_SYSSTAT=y
BR2_PACKAGE_TRACEROUTE=y
BR2_PACKAGE_IPUTILS=y
BR2_PACKAGE_IPROUTE2=y
BR2_PACKAGE_IPTABLES=y
BR2_PACKAGE_IPTABLES_NFTABLES=y
BR2_PACKAGE_NCURSES_WCHAR=y
BR2_PACKAGE_LIBEDIT=y
BR2_PACKAGE_NGINX=y
BR2_PACKAGE_NGINX_HTTP=y
BR2_PACKAGE_NGINX_HTTP_DAV_MODULE=y
BR2_PACKAGE_NGINX_HTTP_MP4_MODULE=y
BR2_PACKAGE_NGINX_HTTP_FLV_MODULE=y
BR2_PACKAGE_NGINX_HTTP_GUNZIP_MODULE=y
BR2_PACKAGE_NGINX_STREAM=y
BR2_PACKAGE_NGINX_SELECT_MODULE=y
BR2_PACKAGE_NGINX_HTTP_FASTCGI_MODULE=y
BR2_PACKAGE_NGINX_HTTP_UWSGI_MODULE=y
BR2_PACKAGE_NGINX_HTTP_SCGI_MODULE=y
# BR2_PACKAGE_NGINX=y
# BR2_PACKAGE_NGINX_HTTP=y
# BR2_PACKAGE_NGINX_HTTP_DAV_MODULE=y
# BR2_PACKAGE_NGINX_HTTP_MP4_MODULE=y
# BR2_PACKAGE_NGINX_HTTP_FLV_MODULE=y
# BR2_PACKAGE_NGINX_HTTP_GUNZIP_MODULE=y
# BR2_PACKAGE_NGINX_STREAM=y
# BR2_PACKAGE_NGINX_SELECT_MODULE=y
# BR2_PACKAGE_NGINX_HTTP_FASTCGI_MODULE=y
# BR2_PACKAGE_NGINX_HTTP_UWSGI_MODULE=y
# BR2_PACKAGE_NGINX_HTTP_SCGI_MODULE=y
BR2_PACKAGE_RTC_TOOLS=y
BR2_PACKAGE_PICOCOM=y
BR2_PACKAGE_FBGRAB=y
@@ -375,9 +389,15 @@ BR2_PACKAGE_PYTHON_INTELHEX=y
BR2_PACKAGE_VIM=y
BR2_PACKAGE_VIM_RUNTIME=y
BR2_PACKAGE_AXP2101=y
BR2_TARGET_ROOTFS_EXT2=y
BR2_TARGET_ROOTFS_EXT2_4=y
BR2_TARGET_ROOTFS_EXT2_SIZE="900M"
BR2_TARGET_ROOTFS_EXT2_SIZE="1100M"
BR2_ROOTFS_OVERLAY="$(TOPDIR)/board/cvitek/SG200X/overlay"
BR2_PACKAGE_BUSYBOX_CONFIG_FRAGMENT_FILES="$(TOPDIR)/board/cvitek/SG200X/busybox-extra.config"
BR2_TARGET_TZ_INFO=y
BR2_TARGET_TZ_ZONELIST="default"
BR2_TARGET_LOCALTIME="Etc/UTC"

View File

@@ -66,15 +66,14 @@ BR2_PACKAGE_NTP_NTPD=y
BR2_PACKAGE_NTP_NTPDATE=y
BR2_PACKAGE_MACCHANGER=y
BR2_PACKAGE_AVAHI=y
BR2_PACKAGE_AVAHI_AUTOIPD=y
# avahi mdns is buggy
# BR2_PACKAGE_AVAHI_DAEMON is not set
# BR2_PACKAGE_AVAHI_AUTOIPD is not set
BR2_PACKAGE_AVAHI_DAEMON=y
# BR2_PACKAGE_AVAHI_LIBDNSSD_COMPATIBILITY is not set
# BR2_PACKAGE_AVAHI_DEFAULT_SERVICES is not set
BR2_PACKAGE_MDNSD=y
BR2_PACKAGE_MDNSD_MQUERY=y
BR2_PACKAGE_MDNSD_HTTP_SERVICE=y
BR2_PACKAGE_MDNSD_SSH_SERVICE=y
BR2_PACKAGE_AVAHI_DEFAULT_SERVICES=y
# BR2_PACKAGE_MDNSD is not set
# BR2_PACKAGE_MDNSD_MQUERY is not set
# BR2_PACKAGE_MDNSD_HTTP_SERVICE is not set
# BR2_PACKAGE_MDNSD_SSH_SERVICE is not set
BR2_PACKAGE_WIRELESS_TOOLS=y
BR2_PACKAGE_WIRELESS_TOOLS_IFRENAME=y
BR2_PACKAGE_WIRELESS_TOOLS_IWCONFIG=y
@@ -82,6 +81,12 @@ BR2_PACKAGE_WIRELESS_TOOLS_LIB=y
BR2_PACKAGE_AIRCRACK_NG=y
BR2_PACKAGE_UTIL_LINUX_RFKILL=y
BR2_PACKAGE_IPERF3=y
BR2_PACKAGE_IPMITOOL=y
BR2_PACKAGE_IPMITOOL_PEN_REG_URI=y
BR2_PACKAGE_IPMITOOL_LANPLUS=y
BR2_PACKAGE_IPMITOOL_USB=y
BR2_PACKAGE_IPMITOOL_IPMIEVD=y
BR2_PACKAGE_IPMITOOL_IPMISHELL=y
BR2_PACKAGE_ETHTOOL=y
BR2_PACKAGE_DNSMASQ=y
BR2_PACKAGE_DNSMASQ_DHCP=y
@@ -92,7 +97,11 @@ BR2_PACKAGE_WIRELESS_REGDB=y
BR2_PACKAGE_MOSH=y
BR2_PACKAGE_LRZSZ=y
BR2_PACKAGE_IW=y
BR2_PACKAGE_NETCAT=y
BR2_PACKAGE_MTR=y
# BR2_PACKAGE_WIREGUARD=y
BR2_PACKAGE_WIREGUARD_TOOLS=y
# BR2_PACKAGE_WIREGUARD_LINUX_COMPAT=y
BR2_PACKAGE_WPA_SUPPLICANT=y
BR2_PACKAGE_WPA_SUPPLICANT_NL80211=y
BR2_PACKAGE_WPA_SUPPLICANT_WPA3=y
@@ -131,6 +140,7 @@ BR2_PACKAGE_PARTED=y
BR2_PACKAGE_MEMTESTER=y
BR2_PACKAGE_CACHE_CALIBRATOR=y
BR2_PACKAGE_DHRYSTONE=y
BR2_PACKAGE_COREMARK=y
BR2_PACKAGE_RAMSPEED=y
BR2_PACKAGE_SPIDEV_TEST=y
BR2_PACKAGE_STRESS_NG=y
@@ -140,6 +150,7 @@ BR2_PACKAGE_ALSA_UTILS=y
BR2_PACKAGE_ALSA_UTILS_ALSACTL=y
BR2_PACKAGE_ALSA_UTILS_ALSAMIXER=y
BR2_PACKAGE_ALSA_UTILS_APLAY=y
BR2_PACKAGE_ALSA_UTILS_AMIXER=y
BR2_PACKAGE_MPG123=y
BR2_PACKAGE_BZIP2=y
BR2_PACKAGE_LRZIP=y
@@ -158,8 +169,10 @@ BR2_PACKAGE_LZ4_PROGS=y
BR2_PACKAGE_SZIP=y
BR2_PACKAGE_CA_CERTIFICATES=y
BR2_PACKAGE_EVTEST=y
BR2_PACKAGE_BASH=y
BR2_PACKAGE_FILE=y
BR2_PACKAGE_EMPTY=y
BR2_PACKAGE_EXFATPROGS=y
BR2_PACKAGE_E2FSPROGS=y
BR2_PACKAGE_E2FSPROGS_RESIZE2FS=y
BR2_PACKAGE_TMUX=y
@@ -194,6 +207,11 @@ BR2_PACKAGE_TCPDUMP=y
BR2_PACKAGE_SSDP_RESPONDER=y
BR2_PACKAGE_PPPD=y
BR2_PACKAGE_NFTABLES=y
BR2_PACKAGE_BIND=y
BR2_PACKAGE_SYSSTAT=y
BR2_PACKAGE_TRACEROUTE=y
BR2_PACKAGE_IPUTILS=y
BR2_PACKAGE_IPROUTE2=y
BR2_PACKAGE_IPTABLES=y
BR2_PACKAGE_IPTABLES_NFTABLES=y
BR2_PACKAGE_NCURSES_WCHAR=y
@@ -208,29 +226,28 @@ BR2_PACKAGE_UBOOT_TOOLS_MKIMAGE=y
BR2_PACKAGE_UBOOT_TOOLS_DUMPIMAGE=y
# if your sdnand is small, you can delete some package
BR2_PACKAGE_IMAGEMAGICK=y
BR2_PACKAGE_OCRAD=y
BR2_PACKAGE_SDL=y
BR2_PACKAGE_SDL_FBCON=y
BR2_PACKAGE_SDL_GFX=y
BR2_PACKAGE_SDL_IMAGE=y
BR2_PACKAGE_SDL_IMAGE_BMP=y
BR2_PACKAGE_SDL_IMAGE_GIF=y
BR2_PACKAGE_SDL_IMAGE_JPEG=y
BR2_PACKAGE_SDL_IMAGE_PNG=y
BR2_PACKAGE_SDL_IMAGE_WEBP=y
BR2_PACKAGE_SDL_MIXER=y
BR2_PACKAGE_SDL_NET=y
BR2_PACKAGE_SDL_SOUND=y
BR2_PACKAGE_SDL_SOUND_PLAYSOUND=y
BR2_PACKAGE_LBREAKOUT2=y
BR2_PACKAGE_LBREAKOUT2_AUDIO=y
BR2_PACKAGE_LBREAKOUT2_NET=y
BR2_PACKAGE_LTRIS=y
BR2_PACKAGE_LTRIS_AUDIO=y
BR2_PACKAGE_PRBOOM=y
BR2_PACKAGE_DOOM_WAD=y
# BR2_PACKAGE_IMAGEMAGICK is not set
# BR2_PACKAGE_OCRAD is not set
# BR2_PACKAGE_SDL is not set
# BR2_PACKAGE_SDL_FBCON is not set
# BR2_PACKAGE_SDL_GFX is not set
# BR2_PACKAGE_SDL_IMAGE is not set
# BR2_PACKAGE_SDL_IMAGE_BMP is not set
# BR2_PACKAGE_SDL_IMAGE_GIF is not set
# BR2_PACKAGE_SDL_IMAGE_JPEG is not set
# BR2_PACKAGE_SDL_IMAGE_PNG is not set
# BR2_PACKAGE_SDL_IMAGE_WEBP is not set
# BR2_PACKAGE_SDL_MIXER is not set
# BR2_PACKAGE_SDL_NET is not set
# BR2_PACKAGE_SDL_SOUND is not set
# BR2_PACKAGE_SDL_SOUND_PLAYSOUND is not set
# BR2_PACKAGE_LBREAKOUT2 is not set
# BR2_PACKAGE_LBREAKOUT2_AUDIO is not set
# BR2_PACKAGE_LBREAKOUT2_NET is not set
# BR2_PACKAGE_LTRIS is not set
# BR2_PACKAGE_LTRIS_AUDIO is not set
# BR2_PACKAGE_PRBOOM is not set
# BR2_PACKAGE_DOOM_WAD is not set
BR2_PACKAGE_TCL=y
# BR2_PACKAGE_TCL_SHLIB_ONLY is not set
# BR2_PACKAGE_TCL_DEL_ENCODINGS is not set
@@ -265,65 +282,69 @@ BR2_PACKAGE_FFMPEG_FFPROBE=y
BR2_PACKAGE_FFMPEG_GPL=y
BR2_PACKAGE_FFMPEG_NONFREE=y
BR2_PACKAGE_FFMPEG_POSTPROC=y
BR2_PACKAGE_MULTICAT=y
BR2_PACKAGE_WQY_ZENHEI=y
BR2_PACKAGE_DEJAVU=y
BR2_PACKAGE_GNUPLOT=y
BR2_PACKAGE_TESSERACT_OCR=y
BR2_PACKAGE_TESSERACT_OCR_LANG_ENG=y
BR2_PACKAGE_TESSERACT_OCR_LANG_CHI_SIM=y
BR2_PACKAGE_TESSERACT_OCR_LANG_CHI_TRA=y
BR2_PACKAGE_QT5=y
BR2_PACKAGE_QT5BASE_SQLITE_SYSTEM=y
BR2_PACKAGE_QT5BASE_GUI=y
BR2_PACKAGE_QT5BASE_LINUXFB=y
BR2_PACKAGE_QT5BASE_WIDGETS=y
BR2_PACKAGE_QT5BASE_DEFAULT_QPA="linuxfb"
BR2_PACKAGE_QT5BASE_FONTCONFIG=y
BR2_PACKAGE_QT5BASE_GIF=y
BR2_PACKAGE_QT5BASE_PNG=y
BR2_PACKAGE_QT5BASE_JPEG=y
BR2_PACKAGE_QT5BASE_SYSLOG=y
BR2_PACKAGE_QT5BASE_DBUS=y
BR2_PACKAGE_QT5BASE_TSLIB=y
BR2_PACKAGE_QT5BASE_EXAMPLES=y
BR2_PACKAGE_QT5BASE_CONCURRENT=y
BR2_PACKAGE_QT5CONNECTIVITY=y
BR2_PACKAGE_QT5IMAGEFORMATS=y
BR2_PACKAGE_QT5MULTIMEDIA=y
BR2_PACKAGE_QT5SENSORS=y
BR2_PACKAGE_QT5SERIALBUS=y
BR2_PACKAGE_QT5CHARTS=y
BR2_PACKAGE_QT5COAP=y
BR2_PACKAGE_QT5ENGINIO=y
BR2_PACKAGE_QT5KNX=y
BR2_PACKAGE_QT5LOCATION=y
BR2_PACKAGE_QT5MQTT=y
BR2_PACKAGE_QT5OPCUA=y
BR2_PACKAGE_QT5REMOTEOBJECTS=y
BR2_PACKAGE_QT5SPEECH=y
BR2_PACKAGE_QT5SVG=y
BR2_PACKAGE_QT5WEBSOCKETS=y
BR2_PACKAGE_QT5WEBCHANNEL=y
BR2_PACKAGE_QEXTSERIALPORT=y
BR2_PACKAGE_QT5X11EXTRAS=y
BR2_PACKAGE_QT5XMLPATTERNS=y
BR2_PACKAGE_QT5BASE_MYSQL=y
BR2_PACKAGE_QJSON=y
BR2_PACKAGE_QUAZIP=y
# BR2_PACKAGE_MULTICAT is not set
# BR2_PACKAGE_WQY_ZENHEI is not set
# BR2_PACKAGE_DEJAVU is not set
# BR2_PACKAGE_GNUPLOT is not set
# BR2_PACKAGE_TESSERACT_OCR is not set
# BR2_PACKAGE_TESSERACT_OCR_LANG_ENG is not set
# BR2_PACKAGE_TESSERACT_OCR_LANG_CHI_SIM is not set
# BR2_PACKAGE_TESSERACT_OCR_LANG_CHI_TRA is not set
# BR2_PACKAGE_QT5 is not set
# BR2_PACKAGE_QT5BASE_SQLITE_SYSTEM is not set
# BR2_PACKAGE_QT5BASE_GUI is not set
# BR2_PACKAGE_QT5BASE_LINUXFB is not set
# BR2_PACKAGE_QT5BASE_WIDGETS is not set
# BR2_PACKAGE_QT5BASE_DEFAULT_QPA="linuxf is not set
# BR2_PACKAGE_QT5BASE_FONTCONFIG is not set
# BR2_PACKAGE_QT5BASE_GIF is not set
# BR2_PACKAGE_QT5BASE_PNG is not set
# BR2_PACKAGE_QT5BASE_JPEG is not set
# BR2_PACKAGE_QT5BASE_SYSLOG is not set
# BR2_PACKAGE_QT5BASE_DBUS is not set
# BR2_PACKAGE_QT5BASE_TSLIB is not set
# BR2_PACKAGE_QT5BASE_EXAMPLES is not set
# BR2_PACKAGE_QT5BASE_CONCURRENT is not set
# BR2_PACKAGE_QT5CONNECTIVITY is not set
# BR2_PACKAGE_QT5IMAGEFORMATS is not set
# BR2_PACKAGE_QT5MULTIMEDIA is not set
# BR2_PACKAGE_QT5SENSORS is not set
# BR2_PACKAGE_QT5SERIALBUS is not set
# BR2_PACKAGE_QT5CHARTS is not set
# BR2_PACKAGE_QT5COAP is not set
# BR2_PACKAGE_QT5ENGINIO is not set
# BR2_PACKAGE_QT5KNX is not set
# BR2_PACKAGE_QT5LOCATION is not set
# BR2_PACKAGE_QT5MQTT is not set
# BR2_PACKAGE_QT5OPCUA is not set
# BR2_PACKAGE_QT5REMOTEOBJECTS is not set
# BR2_PACKAGE_QT5SPEECH is not set
# BR2_PACKAGE_QT5SVG is not set
# BR2_PACKAGE_QT5WEBSOCKETS is not set
# BR2_PACKAGE_QT5WEBCHANNEL is not set
# BR2_PACKAGE_QEXTSERIALPORT is not set
# BR2_PACKAGE_QT5X11EXTRAS is not set
# BR2_PACKAGE_QT5XMLPATTERNS is not set
# BR2_PACKAGE_QT5BASE_MYSQL is not set
# BR2_PACKAGE_QJSON is not set
# BR2_PACKAGE_QUAZIP is not set
BR2_PACKAGE_OPENCV4_LIB_PYTHON=y
# BR2_PACKAGE_OPENCV4_WITH_QT5 is not set
BR2_PACKAGE_PYTHON3=y
BR2_PACKAGE_PYTHON3_2TO3=y
BR2_PACKAGE_PYTHON3_BZIP2=y
BR2_PACKAGE_PYTHON3_CODECSCJK=y
BR2_PACKAGE_PYTHON3_CURSES=y
BR2_PACKAGE_PYTHON3_READLINE=y
BR2_PACKAGE_PYTHON3_SSL=y
BR2_PACKAGE_PYTHON3_UNICODEDATA=y
BR2_PACKAGE_PYTHON3_SQLITE=y
BR2_PACKAGE_PYTHON3_PYEXPAT=y
BR2_PACKAGE_PYTHON3_XZ=y
BR2_PACKAGE_PYTHON3_ZLIB=y
BR2_PACKAGE_PYTHON3_PY_PYC=y
BR2_PACKAGE_PYTHON_NUMPY=y
BR2_PACKAGE_OPENCV4_LIB_PYTHON=y
BR2_PACKAGE_OPENCV4_WITH_QT5=y
BR2_PACKAGE_PYTHON_BSDIFF4=y
BR2_PACKAGE_PYTHON_BEAUTIFULSOUP4=y
BR2_PACKAGE_PYTHON_CFFI=y
@@ -357,11 +378,9 @@ BR2_PACKAGE_PYTHON_SERIAL_ASYNCIO=y
BR2_PACKAGE_PYTHON_WEBSOCKETS=y
BR2_PACKAGE_PYTHON_WEBSOCKET_CLIENT=y
BR2_PACKAGE_PYTHON_XMODEM=y
BR2_PACKAGE_PYTHON3_PY_PYC=y
BR2_PACKAGE_PYTHON_PYQT5=y
BR2_PACKAGE_PYTHON_PYQRCODE=y
BR2_PACKAGE_PYTHON_PYLIBFDT=y
BR2_PACKAGE_PYTHON3_READLINE=y
BR2_PACKAGE_PYTHON_JEDI=y
BR2_PACKAGE_PYTHON_LIBUSB1=y
BR2_PACKAGE_PYTHON_LXML=y
@@ -371,25 +390,222 @@ BR2_PACKAGE_PYTHON_PERIPHERY=y
BR2_PACKAGE_PYTHON_PILLOW=y
BR2_PACKAGE_PYTHON_POSIX_IPC=y
BR2_PACKAGE_PYTHON_PROTOBUF=y
BR2_PACKAGE_PYTHON_PYGAME=y
BR2_PACKAGE_PYTHON_PYGAME_IMAGE=y
BR2_PACKAGE_PYTHON_PYGAME_EXAMPLES=y
BR2_PACKAGE_PYTHON_PYGAME_FONT=y
BR2_PACKAGE_PYTHON_PYGAME_MIXER=y
BR2_PACKAGE_PYTHON_PYUDEV=y
BR2_PACKAGE_PYTHON_PYYAML=y
BR2_PACKAGE_PYTHON_QRCODE=y
BR2_PACKAGE_PYTHON_QRCODE_PIL=y
BR2_PACKAGE_PYTHON_INTELHEX=y
BR2_PACKAGE_MGBA=y
BR2_PACKAGE_GB_TEST_ROMS=y
#
# External python modules
#
BR2_PACKAGE_PYTHON_AENUM=y
BR2_PACKAGE_PYTHON_ALSAAUDIO=y
BR2_PACKAGE_PYTHON_APISPEC=y
BR2_PACKAGE_PYTHON_ARGH=y
BR2_PACKAGE_PYTHON_ASGIREF=y
BR2_PACKAGE_PYTHON_ASTTOKENS=y
BR2_PACKAGE_PYTHON_ASYNC_GENERATOR=y
BR2_PACKAGE_PYTHON_ASYNC_TIMEOUT=y
BR2_PACKAGE_PYTHON_ATTRS=y
BR2_PACKAGE_PYTHON_BABEL=y
BR2_PACKAGE_PYTHON_BACKCALL=y
BR2_PACKAGE_PYTHON_BEAUTIFULSOUP4=y
BR2_PACKAGE_PYTHON_BIDICT=y
BR2_PACKAGE_PYTHON_BLINKER=y
#
# python-bluezero needs a glibc toolchain, gcc >= 4.9, host gcc >= 8
#
BR2_PACKAGE_PYTHON_BROTLI=y
BR2_PACKAGE_PYTHON_BSDIFF4=y
BR2_PACKAGE_PYTHON_CERTIFI=y
BR2_PACKAGE_PYTHON_CFFI=y
BR2_PACKAGE_PYTHON_CHARSET_NORMALIZER=y
BR2_PACKAGE_PYTHON_CLICK=y
BR2_PACKAGE_PYTHON_CRC16=y
BR2_PACKAGE_PYTHON_CRCMOD=y
BR2_PACKAGE_PYTHON_CRONTAB=y
BR2_PACKAGE_PYTHON_CYCLER=y
BR2_PACKAGE_PYTHON_DATEUTIL=y
BR2_PACKAGE_PYTHON_DBUS_FAST=y
BR2_PACKAGE_PYTHON_DBUS_NEXT=y
BR2_PACKAGE_PYTHON_DECORATOR=y
BR2_PACKAGE_PYTHON_DJANGO=y
BR2_PACKAGE_PYTHON_ENGINEIO=y
BR2_PACKAGE_PYTHON_EVDEV=y
BR2_PACKAGE_PYTHON_EXECUTING=y
BR2_PACKAGE_PYTHON_FLASK=y
BR2_PACKAGE_PYTHON_FLASK_BABEL=y
BR2_PACKAGE_PYTHON_FLASK_CORS=y
BR2_PACKAGE_PYTHON_FLASK_JSONRPC=y
BR2_PACKAGE_PYTHON_FLASK_LOGIN=y
BR2_PACKAGE_PYTHON_FLASK_SMOREST=y
BR2_PACKAGE_PYTHON_FLASK_SQLALCHEMY=y
BR2_PACKAGE_PYTHON_FLASK_WTF=y
BR2_PACKAGE_PYTHON_FLATBUFFERS=y
#
# python-gobject needs a glibc toolchain, gcc >= 4.9, host gcc >= 8
#
BR2_PACKAGE_PYTHON_GREENLET_ARCH_SUPPORTS=y
BR2_PACKAGE_PYTHON_H11=y
BR2_PACKAGE_PYTHON_HTML5LIB=y
BR2_PACKAGE_PYTHON_HUMANIZE=y
BR2_PACKAGE_PYTHON_HWDATA=y
BR2_PACKAGE_PYTHON_IDNA=y
BR2_PACKAGE_PYTHON_IFADDR=y
BR2_PACKAGE_PYTHON_INTELHEX=y
BR2_PACKAGE_PYTHON_IPYTHON=y
BR2_PACKAGE_PYTHON_IPYTHON_GENUTILS=y
BR2_PACKAGE_PYTHON_ITSDANGEROUS=y
BR2_PACKAGE_PYTHON_JEDI=y
BR2_PACKAGE_PYTHON_JINJA2=y
BR2_PACKAGE_PYTHON_KIWISOLVER=y
#
# python-libconfig needs a glibc or uClibc toolchain w/ C++, threads
#
BR2_PACKAGE_PYTHON_LIBEVDEV=y
BR2_PACKAGE_PYTHON_LIBUSB1=y
BR2_PACKAGE_PYTHON_LXML=y
BR2_PACKAGE_PYTHON_MARKUPSAFE=y
BR2_PACKAGE_PYTHON_MARSHMALLOW=y
BR2_PACKAGE_PYTHON_MSGPACK=y
BR2_PACKAGE_PYTHON_MYPY_EXTENSIONS=y
BR2_PACKAGE_PYTHON_NETADDR=y
BR2_PACKAGE_PYTHON_NETIFACES=y
BR2_PACKAGE_PYTHON_NETWORKX=y
BR2_PACKAGE_PYTHON_NUMPY_ARCH_SUPPORTS=y
BR2_PACKAGE_PYTHON_NUMPY=y
BR2_PACKAGE_PYTHON_OAUTHLIB=y
BR2_PACKAGE_PYTHON_OUTCOME=y
BR2_PACKAGE_PYTHON_PACKAGING=y
BR2_PACKAGE_PYTHON_PAHO_MQTT=y
BR2_PACKAGE_PYTHON_PARSO=y
BR2_PACKAGE_PYTHON_PATHTOOLS=y
BR2_PACKAGE_PYTHON_PERIPHERY=y
BR2_PACKAGE_PYTHON_PEXPECT=y
BR2_PACKAGE_PYTHON_PICKLESHARE=y
BR2_PACKAGE_PYTHON_PILLOW=y
BR2_PACKAGE_PYTHON_PIP=y
BR2_PACKAGE_PYTHON_POSIX_IPC=y
BR2_PACKAGE_PYTHON_PROMPT_TOOLKIT=y
BR2_PACKAGE_PYTHON_PROTOBUF=y
BR2_PACKAGE_PYTHON_PSUTIL=y
BR2_PACKAGE_PYTHON_PTYPROCESS=y
BR2_PACKAGE_PYTHON_PURE_EVAL=y
BR2_PACKAGE_PYTHON_PYAES=y
BR2_PACKAGE_PYTHON_PYALSA=y
BR2_PACKAGE_PYTHON_PYASN1=y
BR2_PACKAGE_PYTHON_PYCPARSER=y
BR2_PACKAGE_PYTHON_PYDEVMEM=y
BR2_PACKAGE_PYTHON_PYGMENTS=y
BR2_PACKAGE_PYTHON_PYLIBFDT=y
BR2_PACKAGE_PYTHON_PYMODBUS=y
#
# python-pymupdf needs Xorg
#
BR2_PACKAGE_PYTHON_PYPARSING=y
BR2_PACKAGE_PYTHON_PYQRCODE=y
#
# python-pyqt5 needs Qt5
#
BR2_PACKAGE_PYTHON_PYSMB=y
BR2_PACKAGE_PYTHON_PYSOCKS=y
BR2_PACKAGE_PYTHON_PYTZ=y
BR2_PACKAGE_PYTHON_PYUDEV=y
BR2_PACKAGE_PYTHON_PYUSB=y
BR2_PACKAGE_PYTHON_PYYAML=y
BR2_PACKAGE_PYTHON_PYZMQ=y
BR2_PACKAGE_PYTHON_QRCODE=y
BR2_PACKAGE_PYTHON_QRCODE_PIL=y
BR2_PACKAGE_PYTHON_REQUESTS=y
BR2_PACKAGE_PYTHON_REQUESTS_OAUTHLIB=y
BR2_PACKAGE_PYTHON_REQUESTS_TOOLBELT=y
BR2_PACKAGE_PYTHON_SCAPY=y
#
# python-scipy needs glibc or musl toolchain w/ fortran, c++, gcc >= 9, host gcc >= 9
#
BR2_PACKAGE_PYTHON_SELENIUM=y
BR2_PACKAGE_PYTHON_SERIAL=y
BR2_PACKAGE_PYTHON_SERIAL_ASYNCIO=y
BR2_PACKAGE_PYTHON_SETUPTOOLS=y
BR2_PACKAGE_PYTHON_SIX=y
BR2_PACKAGE_PYTHON_SMBUS_CFFI=y
BR2_PACKAGE_PYTHON_SNAPPY=y
BR2_PACKAGE_PYTHON_SNIFFIO=y
BR2_PACKAGE_PYTHON_SOCKETIO=y
BR2_PACKAGE_PYTHON_SORTEDCONTAINERS=y
BR2_PACKAGE_PYTHON_SOUPSIEVE=y
BR2_PACKAGE_PYTHON_SPIDEV=y
BR2_PACKAGE_PYTHON_SQLALCHEMY=y
BR2_PACKAGE_PYTHON_SQLPARSE=y
BR2_PACKAGE_PYTHON_STACK_DATA=y
#
# python-systemd needs systemd
#
BR2_PACKAGE_PYTHON_TINYRPC=y
BR2_PACKAGE_PYTHON_TOML=y
BR2_PACKAGE_PYTHON_TORNADO=y
BR2_PACKAGE_PYTHON_TQDM=y
BR2_PACKAGE_PYTHON_TRAITLETS=y
BR2_PACKAGE_PYTHON_TRIO=y
BR2_PACKAGE_PYTHON_TRIO_WEBSOCKET=y
BR2_PACKAGE_PYTHON_TYPEGUARD=y
BR2_PACKAGE_PYTHON_TYPING_EXTENSIONS=y
BR2_PACKAGE_PYTHON_TYPING_INSPECT=y
BR2_PACKAGE_PYTHON_UBJSON=y
BR2_PACKAGE_PYTHON_UHID=y
BR2_PACKAGE_PYTHON_UJSON=y
BR2_PACKAGE_PYTHON_URLLIB3=y
BR2_PACKAGE_PYTHON_WATCHDOG=y
BR2_PACKAGE_PYTHON_WCWIDTH=y
BR2_PACKAGE_PYTHON_WEBARGS=y
BR2_PACKAGE_PYTHON_WEBENCODINGS=y
BR2_PACKAGE_PYTHON_WEBSOCKET_CLIENT=y
BR2_PACKAGE_PYTHON_WEBSOCKETS=y
BR2_PACKAGE_PYTHON_WERKZEUG=y
BR2_PACKAGE_PYTHON_WSPROTO=y
BR2_PACKAGE_PYTHON_WTFORMS=y
BR2_PACKAGE_PYTHON_XLRD=y
BR2_PACKAGE_PYTHON_XLSXWRITER=y
BR2_PACKAGE_PYTHON_XLUTILS=y
BR2_PACKAGE_PYTHON_XLWT=y
BR2_PACKAGE_PYTHON_XMODEM=y
BR2_PACKAGE_PYTHON_ZEROCONF=y
# BR2_PACKAGE_MGBA is not set
# BR2_PACKAGE_GB_TEST_ROMS is not set
# BR2_PACKAGE_NGINX=y
# BR2_PACKAGE_NGINX_HTTP=y
# BR2_PACKAGE_NGINX_HTTP_DAV_MODULE=y
# BR2_PACKAGE_NGINX_HTTP_MP4_MODULE=y
# BR2_PACKAGE_NGINX_HTTP_FLV_MODULE=y
# BR2_PACKAGE_NGINX_HTTP_GUNZIP_MODULE=y
# BR2_PACKAGE_NGINX_STREAM=y
# BR2_PACKAGE_NGINX_SELECT_MODULE=y
# BR2_PACKAGE_NGINX_HTTP_FASTCGI_MODULE=y
# BR2_PACKAGE_NGINX_HTTP_UWSGI_MODULE=y
# BR2_PACKAGE_NGINX_HTTP_SCGI_MODULE=y
BR2_PACKAGE_VIM=y
BR2_PACKAGE_VIM_RUNTIME=y
BR2_PACKAGE_AXP2101=y
BR2_TARGET_ROOTFS_EXT2=y
BR2_TARGET_ROOTFS_EXT2_4=y
BR2_TARGET_ROOTFS_EXT2_SIZE="900M"
BR2_TARGET_ROOTFS_EXT2_SIZE="1100M"
BR2_ROOTFS_OVERLAY="$(TOPDIR)/board/cvitek/SG200X/overlay"
BR2_PACKAGE_BUSYBOX_CONFIG_FRAGMENT_FILES="$(TOPDIR)/board/cvitek/SG200X/busybox-extra.config"
BR2_TARGET_TZ_INFO=y
BR2_TARGET_TZ_ZONELIST="default"
BR2_TARGET_LOCALTIME="Etc/UTC"

View File

@@ -2680,6 +2680,7 @@ menu "System tools"
source "package/atop/Config.in"
source "package/attr/Config.in"
source "package/audit/Config.in"
source "package/axp2101/Config.in"
source "package/balena-engine/Config.in"
source "package/bubblewrap/Config.in"
source "package/cgroupfs-mount/Config.in"

View File

@@ -0,0 +1,5 @@
config BR2_PACKAGE_AXP2101
bool "axp2101"
help
If you say Y here you get support for the X-Powers AXP2101 power
management ICs (PMICs) controlled with I2C.

View File

@@ -0,0 +1,20 @@
################################################################################
#
# axp2101
#
################################################################################
AXP2101_VERSION = 1.1.0
AXP2101_SITE = $(TOPDIR)/package/axp2101/src
AXP2101_SITE_METHOD = local
AXP2101_CFLAGS = -Iinclude -IXPowersLib -IXPowersLib/REG -Wall -Wextra
define AXP2101_BUILD_CMDS
$(MAKE) $(TARGET_CONFIGURE_OPTS) CFLAGS="$(AXP2101_CFLAGS)" -C $(@D)
endef
define AXP2101_INSTALL_TARGET_CMDS
$(INSTALL) -D -m 0755 $(@D)/axp2101 $(TARGET_DIR)/usr/bin/axp2101
endef
$(eval $(generic-package))

View File

@@ -0,0 +1,26 @@
APP_DIR = ./src
SRC_DIR = ./XPowersLib
DIR_BIN = ./bin
OBJ_C = $(wildcard ${SRC_DIR}/*.cpp ${APP_DIR}/*.cpp)
OBJ_O = $(patsubst %.cpp,${DIR_BIN}/%.o,$(notdir ${OBJ_C}))
TARGET = axp2101
$(shell mkdir -p $(DIR_BIN))
MSG = -g -O0 -Wall
CFLAGS += $(MSG)
${TARGET}:${OBJ_O}
$(CXX) $(CFLAGS) $(OBJ_O) -o $@ $(LIB)
${DIR_BIN}/%.o:$(APP_DIR)/%.cpp
$(CXX) $(CFLAGS) -c $< -o $@ -I $(SRC_DIR)
${DIR_BIN}/%.o:$(SRC_DIR)/%.cpp
$(CXX) $(CFLAGS) -c $< -o $@ $(LIB)
clean :
rm $(DIR_BIN)/*.*
rm $(TARGET)

View File

@@ -0,0 +1,171 @@
/**
*
* @license MIT License
*
* Copyright (c) 2024 lewis he
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* @file PowerDeliveryHUSB238.tpp
* @author Lewis He (lewishe@outlook.com)
* @date 2024-07-24
*
*/
#if defined(ARDUINO)
#include <Arduino.h>
#else
#include <math.h>
#endif /*ARDUINO*/
#include "XPowersCommon.tpp"
#include "REG/HUSB238Constants.h"
class PowerDeliveryHUSB238 :
public XPowersCommon<PowerDeliveryHUSB238>
{
friend class XPowersCommon<PowerDeliveryHUSB238>;
public:
enum PD_Status {
NO_RESPONSE,
SUCCESS,
INVALID_CMD,
NOT_SUPPORT,
TRANSACTION_FAIL
};
enum PD_Voltage {
PD_5V = 1,
PD_9V,
PD_12V,
PD_15V,
PD_18V,
PD_20V
};
#if defined(ARDUINO)
PowerDeliveryHUSB238(TwoWire &w, int sda = SDA, int scl = SCL, uint8_t addr = HUSB238_SLAVE_ADDRESS)
{
__wire = &w;
__sda = sda;
__scl = scl;
__addr = addr;
}
#endif
PowerDeliveryHUSB238(uint8_t addr, iic_fptr_t readRegCallback, iic_fptr_t writeRegCallback)
{
thisReadRegCallback = readRegCallback;
thisWriteRegCallback = writeRegCallback;
__addr = addr;
}
PowerDeliveryHUSB238()
{
#if defined(ARDUINO)
__wire = &Wire;
__sda = SDA;
__scl = SCL;
#endif
__addr = HUSB238_SLAVE_ADDRESS;
}
~PowerDeliveryHUSB238()
{
log_i("~PowerDeliveryHUSB238");
deinit();
}
#if defined(ARDUINO)
bool init(TwoWire &w, int sda = SDA, int scl = SCL, uint8_t addr = HUSB238_SLAVE_ADDRESS)
{
__wire = &w;
__sda = sda;
__scl = scl;
__addr = addr;
return begin();
}
#endif
void deinit()
{
end();
}
uint8_t getPdVoltage()
{
int val = readRegister(HUSB238_PD_STATUS0);
if (val == -1)return 0;
val &= 0xF0;
val >>= 4;
return pd_voltage_list[val];
}
float getPdCurrent()
{
int val = readRegister(HUSB238_PD_STATUS0);
if (val == -1)return 0;
val &= 0x0F;
return pd_current_list[val];
}
void setPdVoltage(PD_Voltage vol)
{
writeRegister(HUSB238_SRC_PDO, vol);
writeRegister(HUSB238_GO_COMMAND, 0x01);
}
void resetPdVoltage()
{
writeRegister(HUSB238_GO_COMMAND, 0x10);
}
bool attach()
{
return getRegisterBit(HUSB238_PD_STATUS1, 6);
}
PD_Status status()
{
int val = readRegister(HUSB238_PD_STATUS1);
if (val == -1)return NO_RESPONSE;
val >>= 3;
val &= 0x03;
return static_cast<PD_Status>(val);
}
private:
const uint8_t pd_voltage_list[7] = {0, 5, 9, 12, 15, 18, 20};
const float pd_current_list[16] = {
0.5, 0.7, 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5,
2.75, 3, 3.25, 3.5, 4, 4.5, 5
};
bool initImpl()
{
return readRegister(HUSB238_PD_STATUS0) != -1;
}
};

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,182 @@
#pragma once
#define AXP192_SLAVE_ADDRESS (0x34)
#define XPOWERS_AXP192_CHIP_ID (0x03)
#define XPOWERS_AXP192_STATUS (0x00)
#define XPOWERS_AXP192_MODE_CHGSTATUS (0x01)
#define XPOWERS_AXP192_OTG_STATUS (0x02)
#define XPOWERS_AXP192_IC_TYPE (0x03)
#define XPOWERS_AXP192_DATA_BUFFER1 (0x06)
#define XPOWERS_AXP192_DATA_BUFFER2 (0x07)
#define XPOWERS_AXP192_DATA_BUFFER3 (0x08)
#define XPOWERS_AXP192_DATA_BUFFER4 (0x09)
#define XPOWERS_AXP192_DATA_BUFFER5 (0x0A)
#define XPOWERS_AXP192_DATA_BUFFER6 (0x0B)
#define XPOWERS_AXP192_DATA_BUFFER_SIZE (6)
#define XPOWERS_AXP192_LDO23_DC123_EXT_CTL (0x12)
#define XPOWERS_AXP192_DC2OUT_VOL (0x23)
#define XPOWERS_AXP192_DC2_DVM (0x25)
#define XPOWERS_AXP192_DC3OUT_VOL (0x27)
#define XPOWERS_AXP192_LDO24OUT_VOL (0x28)
#define XPOWERS_AXP192_LDO3OUT_VOL (0x29)
#define XPOWERS_AXP192_IPS_SET (0x30)
#define XPOWERS_AXP192_VOFF_SET (0x31)
#define XPOWERS_AXP192_OFF_CTL (0x32)
#define XPOWERS_AXP192_CHARGE1 (0x33)
#define XPOWERS_AXP192_CHARGE2 (0x34)
#define XPOWERS_AXP192_BACKUP_CHG (0x35)
#define XPOWERS_AXP192_POK_SET (0x36)
#define XPOWERS_AXP192_DCDC_FREQSET (0x37)
#define XPOWERS_AXP192_VLTF_CHGSET (0x38)
#define XPOWERS_AXP192_VHTF_CHGSET (0x39)
#define XPOWERS_AXP192_APS_WARNING1 (0x3A)
#define XPOWERS_AXP192_APS_WARNING2 (0x3B)
#define XPOWERS_AXP192_TLTF_DISCHGSET (0x3C)
#define XPOWERS_AXP192_THTF_DISCHGSET (0x3D)
#define XPOWERS_AXP192_DCDC_MODESET (0x80)
#define XPOWERS_AXP192_ADC_EN1 (0x82)
#define XPOWERS_AXP192_ADC_EN2 (0x83)
#define XPOWERS_AXP192_ADC_SPEED (0x84)
#define XPOWERS_AXP192_ADC_INPUTRANGE (0x85)
#define XPOWERS_AXP192_ADC_IRQ_RETFSET (0x86)
#define XPOWERS_AXP192_ADC_IRQ_FETFSET (0x87)
#define XPOWERS_AXP192_TIMER_CTL (0x8A)
#define XPOWERS_AXP192_VBUS_DET_SRP (0x8B)
#define XPOWERS_AXP192_HOTOVER_CTL (0x8F)
#define XPOWERS_AXP192_PWM1_FREQ_SET (0x98)
#define XPOWERS_AXP192_PWM1_DUTY_SET1 (0x99)
#define XPOWERS_AXP192_PWM1_DUTY_SET2 (0x9A)
#define XPOWERS_AXP192_PWM2_FREQ_SET (0x9B)
#define XPOWERS_AXP192_PWM2_DUTY_SET1 (0x9C)
#define XPOWERS_AXP192_PWM2_DUTY_SET2 (0x9D)
// INTERRUPT REGISTER
#define XPOWERS_AXP192_INTEN1 (0x40)
#define XPOWERS_AXP192_INTEN2 (0x41)
#define XPOWERS_AXP192_INTEN3 (0x42)
#define XPOWERS_AXP192_INTEN4 (0x43)
#define XPOWERS_AXP192_INTEN5 (0x4A)
// INTERRUPT STATUS REGISTER
#define XPOWERS_AXP192_INTSTS1 (0x44)
#define XPOWERS_AXP192_INTSTS2 (0x45)
#define XPOWERS_AXP192_INTSTS3 (0x46)
#define XPOWERS_AXP192_INTSTS4 (0x47)
#define XPOWERS_AXP192_INTSTS5 (0x4D)
#define XPOWERS_AXP192_INTSTS_CNT (5)
#define XPOWERS_AXP192_DC1_VLOTAGE (0x26)
#define XPOWERS_AXP192_LDO23OUT_VOL (0x28)
#define XPOWERS_AXP192_GPIO0_CTL (0x90)
#define XPOWERS_AXP192_GPIO0_VOL (0x91)
#define XPOWERS_AXP192_GPIO1_CTL (0X92)
#define XPOWERS_AXP192_GPIO2_CTL (0x93)
#define XPOWERS_AXP192_GPIO012_SIGNAL (0x94)
#define XPOWERS_AXP192_GPIO34_CTL (0x95)
#define XPOWERS_AXP192_GPIO34_SIGNAL (0x96)
#define XPOWERS_AXP192_GPIO012_PULLDOWN (0x97)
#define XPOWERS_AXP192_GPIO5_CTL (0x9E)
#define XPOWERS_AXP192_GPIO0_VOL_ADC_H8 (0x64)
#define XPOWERS_AXP192_GPIO0_VOL_ADC_L4 (0x65)
#define XPOWERS_AXP192_GPIO1_VOL_ADC_H8 (0x66)
#define XPOWERS_AXP192_GPIO1_VOL_ADC_L4 (0x67)
#define XPOWERS_AXP192_GPIO2_VOL_ADC_H8 (0x68)
#define XPOWERS_AXP192_GPIO2_VOL_ADC_L4 (0x69)
#define XPOWERS_AXP192_GPIO3_VOL_ADC_H8 (0x6A)
#define XPOWERS_AXP192_GPIO3_VOL_ADC_L4 (0x6B)
#define XPOWERS_AXP192_GPIO0_STEP (0.5F)
#define XPOWERS_AXP192_GPIO1_STEP (0.5F)
#define XPOWERS_AXP192_TS_IN_H8 (0x62)
#define XPOWERS_AXP192_TS_IN_L4 (0x63)
#define XPOWERS_AXP192_BAT_AVERCHGCUR_H8 (0x7A)
#define XPOWERS_AXP192_BAT_AVERCHGCUR_L5 (0x7B)
#define XPOWERS_AXP192_ACIN_VOL_H8 (0x56)
#define XPOWERS_AXP192_ACIN_VOL_L4 (0x57)
#define XPOWERS_AXP192_ACIN_CUR_H8 (0x58)
#define XPOWERS_AXP192_ACIN_CUR_L4 (0x59)
#define XPOWERS_AXP192_VBUS_VOL_H8 (0x5A)
#define XPOWERS_AXP192_VBUS_VOL_L4 (0x5B)
#define XPOWERS_AXP192_VBUS_CUR_H8 (0x5C)
#define XPOWERS_AXP192_VBUS_CUR_L4 (0x5D)
#define XPOWERS_AXP192_BAT_AVERDISCHGCUR_H8 (0x7C)
#define XPOWERS_AXP192_BAT_AVERDISCHGCUR_L5 (0x7D)
#define XPOWERS_AXP192_APS_AVERVOL_H8 (0x7E)
#define XPOWERS_AXP192_APS_AVERVOL_L4 (0x7F)
#define XPOWERS_AXP192_BAT_AVERVOL_H8 (0x78)
#define XPOWERS_AXP192_BAT_AVERVOL_L4 (0x79)
#define XPOWERS_AXP192_BAT_CHGCOULOMB3 (0xB0)
#define XPOWERS_AXP192_BAT_CHGCOULOMB2 (0xB1)
#define XPOWERS_AXP192_BAT_CHGCOULOMB1 (0xB2)
#define XPOWERS_AXP192_BAT_CHGCOULOMB0 (0xB3)
#define XPOWERS_AXP192_BAT_DISCHGCOULOMB3 (0xB4)
#define XPOWERS_AXP192_BAT_DISCHGCOULOMB2 (0xB5)
#define XPOWERS_AXP192_BAT_DISCHGCOULOMB1 (0xB6)
#define XPOWERS_AXP192_BAT_DISCHGCOULOMB0 (0xB7)
#define XPOWERS_AXP192_COULOMB_CTL (0xB8)
#define XPOWERS_AXP192_BATT_VOLTAGE_STEP (1.1F)
#define XPOWERS_AXP192_BATT_DISCHARGE_CUR_STEP (0.5F)
#define XPOWERS_AXP192_BATT_CHARGE_CUR_STEP (0.5F)
#define XPOWERS_AXP192_ACIN_VOLTAGE_STEP (1.7F)
#define XPOWERS_AXP192_ACIN_CUR_STEP (0.625F)
#define XPOWERS_AXP192_VBUS_VOLTAGE_STEP (1.7F)
#define XPOWERS_AXP192_VBUS_CUR_STEP (0.375F)
#define XPOWERS_AXP192_APS_VOLTAGE_STEP (1.4F)
#define XPOWERS_AXP192_TS_PIN_OUT_STEP (0.8F)
#define XPOWERS_AXP192_LDO2_VOL_MIN (1800u)
#define XPOWERS_AXP192_LDO2_VOL_MAX (3300u)
#define XPOWERS_AXP192_LDO2_VOL_STEPS (100u)
#define XPOWERS_AXP192_LDO2_VOL_BIT_MASK (4u)
#define XPOWERS_AXP192_LDO3_VOL_MIN (1800u)
#define XPOWERS_AXP192_LDO3_VOL_MAX (3300u)
#define XPOWERS_AXP192_LDO3_VOL_STEPS (100u)
#define XPOWERS_AXP192_DC1_VOL_STEPS (25u)
#define XPOWERS_AXP192_DC1_VOL_MIN (700u)
#define XPOWERS_AXP192_DC1_VOL_MAX (3500u)
#define XPOWERS_AXP192_DC2_VOL_STEPS (25u)
#define XPOWERS_AXP192_DC2_VOL_MIN (700u)
#define XPOWERS_AXP192_DC2_VOL_MAX (3500u)
#define XPOWERS_AXP192_DC3_VOL_STEPS (25u)
#define XPOWERS_AXP192_DC3_VOL_MIN (700u)
#define XPOWERS_AXP192_DC3_VOL_MAX (3500u)
#define XPOWERS_AXP192_LDOIO_VOL_STEPS (100)
#define XPOWERS_AXP192_LDOIO_VOL_MIN (1800)
#define XPOWERS_AXP192_LDOIO_VOL_MAX (3300)
#define XPOWERS_AXP192_SYS_VOL_STEPS (100)
#define XPOWERS_AXP192_VOFF_VOL_MIN (2600)
#define XPOWERS_AXP192_VOFF_VOL_MAX (3300)
#define XPOWERS_AXP192_CHG_EXT_CURR_MIN (300)
#define XPOWERS_AXP192_CHG_EXT_CURR_MAX (1000)
#define XPOWERS_AXP192_CHG_EXT_CURR_STEP (100)
#define XPOWERS_AXP192_INTERNAL_TEMP_H8 (0x5E)
#define XPOWERS_AXP192_INTERNAL_TEMP_L4 (0x5F)
#define XPOWERS_AXP192_INTERNAL_TEMP_STEP (0.1F)
#define XPOWERS_AXP192_INERNAL_TEMP_OFFSET (144.7)

View File

@@ -0,0 +1,192 @@
#pragma once
#define AXP202_SLAVE_ADDRESS (0x35)
#define XPOWERS_AXP202_CHIP_ID (0x41)
#define XPOWERS_AXP202_STATUS (0x00)
#define XPOWERS_AXP202_MODE_CHGSTATUS (0x01)
#define XPOWERS_AXP202_OTG_STATUS (0x02)
#define XPOWERS_AXP202_IC_TYPE (0x03)
#define XPOWERS_AXP202_DATA_BUFFER1 (0x04)
#define XPOWERS_AXP202_DATA_BUFFER2 (0x05)
#define XPOWERS_AXP202_DATA_BUFFER3 (0x06)
#define XPOWERS_AXP202_DATA_BUFFER4 (0x07)
#define XPOWERS_AXP202_DATA_BUFFER5 (0x08)
#define XPOWERS_AXP202_DATA_BUFFER6 (0x09)
#define XPOWERS_AXP202_DATA_BUFFER7 (0x0A)
#define XPOWERS_AXP202_DATA_BUFFER8 (0x0B)
#define XPOWERS_AXP202_DATA_BUFFER9 (0x0C)
#define XPOWERS_AXP202_DATA_BUFFERA (0x0D)
#define XPOWERS_AXP202_DATA_BUFFERB (0x0E)
#define XPOWERS_AXP202_DATA_BUFFERC (0x0F)
#define XPOWERS_AXP202_LDO234_DC23_CTL (0x12)
#define XPOWERS_AXP202_DC2OUT_VOL (0x23)
#define XPOWERS_AXP202_LDO3_DC2_DVM (0x25)
#define XPOWERS_AXP202_DC3OUT_VOL (0x27)
#define XPOWERS_AXP202_LDO24OUT_VOL (0x28)
#define XPOWERS_AXP202_LDO3OUT_VOL (0x29)
#define XPOWERS_AXP202_IPS_SET (0x30)
#define XPOWERS_AXP202_VOFF_SET (0x31)
#define XPOWERS_AXP202_OFF_CTL (0x32)
#define XPOWERS_AXP202_CHARGE1 (0x33)
#define XPOWERS_AXP202_CHARGE2 (0x34)
#define XPOWERS_AXP202_BACKUP_CHG (0x35)
#define XPOWERS_AXP202_POK_SET (0x36)
#define XPOWERS_AXP202_DCDC_FREQSET (0x37)
#define XPOWERS_AXP202_VLTF_CHGSET (0x38)
#define XPOWERS_AXP202_VHTF_CHGSET (0x39)
#define XPOWERS_AXP202_APS_WARNING1 (0x3A)
#define XPOWERS_AXP202_APS_WARNING2 (0x3B)
#define XPOWERS_AXP202_TLTF_DISCHGSET (0x3C)
#define XPOWERS_AXP202_THTF_DISCHGSET (0x3D)
#define XPOWERS_AXP202_DCDC_MODESET (0x80)
#define XPOWERS_AXP202_ADC_EN1 (0x82)
#define XPOWERS_AXP202_ADC_EN2 (0x83)
#define XPOWERS_AXP202_ADC_SPEED (0x84)
#define XPOWERS_AXP202_ADC_INPUTRANGE (0x85)
#define XPOWERS_AXP202_ADC_IRQ_RETFSET (0x86)
#define XPOWERS_AXP202_ADC_IRQ_FETFSET (0x87)
#define XPOWERS_AXP202_TIMER_CTL (0x8A)
#define XPOWERS_AXP202_VBUS_DET_SRP (0x8B)
#define XPOWERS_AXP202_HOTOVER_CTL (0x8F)
#define XPOWERS_AXP202_DATA_BUFFER_SIZE (12)
#define XPOWERS_AXP202_GPIO0_CTL (0x90)
#define XPOWERS_AXP202_GPIO0_VOL (0x91)
#define XPOWERS_AXP202_GPIO1_CTL (0x92)
#define XPOWERS_AXP202_GPIO2_CTL (0x93)
#define XPOWERS_AXP202_GPIO012_SIGNAL (0x94)
#define XPOWERS_AXP202_GPIO3_CTL (0x95)
// INTERRUPT REGISTER
#define XPOWERS_AXP202_INTEN1 (0x40)
#define XPOWERS_AXP202_INTEN2 (0x41)
#define XPOWERS_AXP202_INTEN3 (0x42)
#define XPOWERS_AXP202_INTEN4 (0x43)
#define XPOWERS_AXP202_INTEN5 (0x44)
//INTERRUPT STATUS REGISTER
#define XPOWERS_AXP202_INTSTS1 (0x48)
#define XPOWERS_AXP202_INTSTS2 (0x49)
#define XPOWERS_AXP202_INTSTS3 (0x4A)
#define XPOWERS_AXP202_INTSTS4 (0x4B)
#define XPOWERS_AXP202_INTSTS5 (0x4C)
#define XPOWERS_AXP202_INTSTS_CNT (5)
//AXP ADC DATA REGISTER
#define XPOWERS_AXP202_GPIO0_VOL_ADC_H8 (0x64)
#define XPOWERS_AXP202_GPIO0_VOL_ADC_L4 (0x65)
#define XPOWERS_AXP202_GPIO1_VOL_ADC_H8 (0x66)
#define XPOWERS_AXP202_GPIO1_VOL_ADC_L4 (0x67)
#define XPOWERS_AXP202_GPIO0_STEP (0.5F)
#define XPOWERS_AXP202_GPIO1_STEP (0.5F)
#define XPOWERS_AXP202_BAT_AVERVOL_H8 (0x78)
#define XPOWERS_AXP202_BAT_AVERVOL_L4 (0x79)
#define XPOWERS_AXP202_BAT_AVERCHGCUR_H8 (0x7A)
#define XPOWERS_AXP202_BAT_AVERCHGCUR_L4 (0x7B)
#define XPOWERS_AXP202_BAT_AVERCHGCUR_L5 (0x7B)
#define XPOWERS_AXP202_ACIN_VOL_H8 (0x56)
#define XPOWERS_AXP202_ACIN_VOL_L4 (0x57)
#define XPOWERS_AXP202_ACIN_CUR_H8 (0x58)
#define XPOWERS_AXP202_ACIN_CUR_L4 (0x59)
#define XPOWERS_AXP202_VBUS_VOL_H8 (0x5A)
#define XPOWERS_AXP202_VBUS_VOL_L4 (0x5B)
#define XPOWERS_AXP202_VBUS_CUR_H8 (0x5C)
#define XPOWERS_AXP202_VBUS_CUR_L4 (0x5D)
#define XPOWERS_AXP202_INTERNAL_TEMP_H8 (0x5E)
#define XPOWERS_AXP202_INTERNAL_TEMP_L4 (0x5F)
#define XPOWERS_AXP202_TS_IN_H8 (0x62)
#define XPOWERS_AXP202_TS_IN_L4 (0x63)
#define XPOWERS_AXP202_GPIO0_VOL_ADC_H8 (0x64)
#define XPOWERS_AXP202_GPIO0_VOL_ADC_L4 (0x65)
#define XPOWERS_AXP202_GPIO1_VOL_ADC_H8 (0x66)
#define XPOWERS_AXP202_GPIO1_VOL_ADC_L4 (0x67)
#define XPOWERS_AXP202_BAT_AVERDISCHGCUR_H8 (0x7C)
#define XPOWERS_AXP202_BAT_AVERDISCHGCUR_L5 (0x7D)
#define XPOWERS_AXP202_APS_AVERVOL_H8 (0x7E)
#define XPOWERS_AXP202_APS_AVERVOL_L4 (0x7F)
#define XPOWERS_AXP202_INT_BAT_CHGCUR_H8 (0xA0)
#define XPOWERS_AXP202_INT_BAT_CHGCUR_L4 (0xA1)
#define XPOWERS_AXP202_EXT_BAT_CHGCUR_H8 (0xA2)
#define XPOWERS_AXP202_EXT_BAT_CHGCUR_L4 (0xA3)
#define XPOWERS_AXP202_INT_BAT_DISCHGCUR_H8 (0xA4)
#define XPOWERS_AXP202_INT_BAT_DISCHGCUR_L4 (0xA5)
#define XPOWERS_AXP202_EXT_BAT_DISCHGCUR_H8 (0xA6)
#define XPOWERS_AXP202_EXT_BAT_DISCHGCUR_L4 (0xA7)
#define XPOWERS_AXP202_BAT_CHGCOULOMB3 (0xB0)
#define XPOWERS_AXP202_BAT_CHGCOULOMB2 (0xB1)
#define XPOWERS_AXP202_BAT_CHGCOULOMB1 (0xB2)
#define XPOWERS_AXP202_BAT_CHGCOULOMB0 (0xB3)
#define XPOWERS_AXP202_BAT_DISCHGCOULOMB3 (0xB4)
#define XPOWERS_AXP202_BAT_DISCHGCOULOMB2 (0xB5)
#define XPOWERS_AXP202_BAT_DISCHGCOULOMB1 (0xB6)
#define XPOWERS_AXP202_BAT_DISCHGCOULOMB0 (0xB7)
#define XPOWERS_AXP202_COULOMB_CTL (0xB8)
#define XPOWERS_AXP202_BATT_PERCENTAGE (0xB9)
#define XPOWERS_AXP202_BAT_POWERH8 (0x70)
#define XPOWERS_AXP202_BAT_POWERM8 (0x71)
#define XPOWERS_AXP202_BAT_POWERL8 (0x72)
#define XPOWERS_AXP202_BATT_VOLTAGE_STEP (1.1F)
#define XPOWERS_AXP202_BATT_DISCHARGE_CUR_STEP (0.5F)
#define XPOWERS_AXP202_BATT_CHARGE_CUR_STEP (0.5F)
#define XPOWERS_AXP202_ACIN_VOLTAGE_STEP (1.7F)
#define XPOWERS_AXP202_ACIN_CUR_STEP (0.625F)
#define XPOWERS_AXP202_VBUS_VOLTAGE_STEP (1.7F)
#define XPOWERS_AXP202_VBUS_CUR_STEP (0.375F)
#define XPOWERS_AXP202_INTERNAL_TEMP_STEP (0.1F)
#define XPOWERS_AXP202_APS_VOLTAGE_STEP (1.4F)
#define XPOWERS_AXP202_TS_PIN_OUT_STEP (0.8F)
#define XPOWERS_AXP202_LDO2_VOL_MIN (1800u)
#define XPOWERS_AXP202_LDO2_VOL_MAX (3300u)
#define XPOWERS_AXP202_LDO2_VOL_STEPS (100u)
#define XPOWERS_AXP202_LDO2_VOL_BIT_MASK (4u)
#define XPOWERS_AXP202_LDO3_VOL_MIN (1800u)
#define XPOWERS_AXP202_LDO3_VOL_MAX (3300u)
#define XPOWERS_AXP202_LDO3_VOL_STEPS (100u)
#define XPOWERS_AXP202_DC2_VOL_STEPS (25u)
#define XPOWERS_AXP202_DC2_VOL_MIN (700u)
#define XPOWERS_AXP202_DC2_VOL_MAX (3500u)
#define XPOWERS_AXP202_DC3_VOL_STEPS (25u)
#define XPOWERS_AXP202_DC3_VOL_MIN (700u)
#define XPOWERS_AXP202_DC3_VOL_MAX (3500u)
#define XPOWERS_AXP202_LDOIO_VOL_STEPS (100)
#define XPOWERS_AXP202_LDOIO_VOL_MIN (1800)
#define XPOWERS_AXP202_LDOIO_VOL_MAX (3300)
#define XPOWERS_AXP202_SYS_VOL_STEPS (100)
#define XPOWERS_AXP202_VOFF_VOL_MIN (2600)
#define XPOWERS_AXP202_VOFF_VOL_MAX (3300)
#define XPOWERS_AXP202_CHG_EXT_CURR_MIN (300)
#define XPOWERS_AXP202_CHG_EXT_CURR_MAX (1000)
#define XPOWERS_AXP202_CHG_EXT_CURR_STEP (100)
#define XPOWERS_AXP202_INERNAL_TEMP_OFFSET (144.7)

View File

@@ -0,0 +1,243 @@
#pragma once
#define AXP2101_SLAVE_ADDRESS (0x34)
#define XPOWERS_AXP2101_CHIP_ID (0x4A)
#define XPOWERS_AXP2101_CHIP_ID_2 (0x47)
#define XPOWERS_AXP2101_STATUS1 (0x00)
#define XPOWERS_AXP2101_STATUS2 (0x01)
#define XPOWERS_AXP2101_IC_TYPE (0x03)
#define XPOWERS_AXP2101_DATA_BUFFER1 (0x04)
#define XPOWERS_AXP2101_DATA_BUFFER2 (0x05)
#define XPOWERS_AXP2101_DATA_BUFFER3 (0x06)
#define XPOWERS_AXP2101_DATA_BUFFER4 (0x07)
#define XPOWERS_AXP2101_DATA_BUFFER_SIZE (4u)
#define XPOWERS_AXP2101_COMMON_CONFIG (0x10)
#define XPOWERS_AXP2101_BATFET_CTRL (0x12)
#define XPOWERS_AXP2101_DIE_TEMP_CTRL (0x13)
#define XPOWERS_AXP2101_MIN_SYS_VOL_CTRL (0x14)
#define XPOWERS_AXP2101_INPUT_VOL_LIMIT_CTRL (0x15)
#define XPOWERS_AXP2101_INPUT_CUR_LIMIT_CTRL (0x16)
#define XPOWERS_AXP2101_RESET_FUEL_GAUGE (0x17)
#define XPOWERS_AXP2101_CHARGE_GAUGE_WDT_CTRL (0x18)
#define XPOWERS_AXP2101_WDT_CTRL (0x19)
#define XPOWERS_AXP2101_LOW_BAT_WARN_SET (0x1A)
#define XPOWERS_AXP2101_PWRON_STATUS (0x20)
#define XPOWERS_AXP2101_PWROFF_STATUS (0x21)
#define XPOWERS_AXP2101_PWROFF_EN (0x22)
#define XPOWERS_AXP2101_DC_OVP_UVP_CTRL (0x23)
#define XPOWERS_AXP2101_VOFF_SET (0x24)
#define XPOWERS_AXP2101_PWROK_SEQU_CTRL (0x25)
#define XPOWERS_AXP2101_SLEEP_WAKEUP_CTRL (0x26)
#define XPOWERS_AXP2101_IRQ_OFF_ON_LEVEL_CTRL (0x27)
#define XPOWERS_AXP2101_FAST_PWRON_SET0 (0x28)
#define XPOWERS_AXP2101_FAST_PWRON_SET1 (0x29)
#define XPOWERS_AXP2101_FAST_PWRON_SET2 (0x2A)
#define XPOWERS_AXP2101_FAST_PWRON_CTRL (0x2B)
#define XPOWERS_AXP2101_ADC_CHANNEL_CTRL (0x30)
#define XPOWERS_AXP2101_ADC_DATA_RELUST0 (0x34)
#define XPOWERS_AXP2101_ADC_DATA_RELUST1 (0x35)
#define XPOWERS_AXP2101_ADC_DATA_RELUST2 (0x36)
#define XPOWERS_AXP2101_ADC_DATA_RELUST3 (0x37)
#define XPOWERS_AXP2101_ADC_DATA_RELUST4 (0x38)
#define XPOWERS_AXP2101_ADC_DATA_RELUST5 (0x39)
#define XPOWERS_AXP2101_ADC_DATA_RELUST6 (0x3A)
#define XPOWERS_AXP2101_ADC_DATA_RELUST7 (0x3B)
#define XPOWERS_AXP2101_ADC_DATA_RELUST8 (0x3C)
#define XPOWERS_AXP2101_ADC_DATA_RELUST9 (0x3D)
//XPOWERS INTERRUPT REGISTER
#define XPOWERS_AXP2101_INTEN1 (0x40)
#define XPOWERS_AXP2101_INTEN2 (0x41)
#define XPOWERS_AXP2101_INTEN3 (0x42)
//XPOWERS INTERRUPT STATUS REGISTER
#define XPOWERS_AXP2101_INTSTS1 (0x48)
#define XPOWERS_AXP2101_INTSTS2 (0x49)
#define XPOWERS_AXP2101_INTSTS3 (0x4A)
#define XPOWERS_AXP2101_INTSTS_CNT (3)
#define XPOWERS_AXP2101_TS_PIN_CTRL (0x50)
#define XPOWERS_AXP2101_TS_HYSL2H_SET (0x52)
#define XPOWERS_AXP2101_TS_LYSL2H_SET (0x53)
#define XPOWERS_AXP2101_VLTF_CHG_SET (0x54)
#define XPOWERS_AXP2101_VHLTF_CHG_SET (0x55)
#define XPOWERS_AXP2101_VLTF_WORK_SET (0x56)
#define XPOWERS_AXP2101_VHLTF_WORK_SET (0x57)
#define XPOWERS_AXP2101_JIETA_EN_CTRL (0x58)
#define XPOWERS_AXP2101_JIETA_SET0 (0x59)
#define XPOWERS_AXP2101_JIETA_SET1 (0x5A)
#define XPOWERS_AXP2101_JIETA_SET2 (0x5B)
#define XPOWERS_AXP2101_IPRECHG_SET (0x61)
#define XPOWERS_AXP2101_ICC_CHG_SET (0x62)
#define XPOWERS_AXP2101_ITERM_CHG_SET_CTRL (0x63)
#define XPOWERS_AXP2101_CV_CHG_VOL_SET (0x64)
#define XPOWERS_AXP2101_THE_REGU_THRES_SET (0x65)
#define XPOWERS_AXP2101_CHG_TIMEOUT_SET_CTRL (0x67)
#define XPOWERS_AXP2101_BAT_DET_CTRL (0x68)
#define XPOWERS_AXP2101_CHGLED_SET_CTRL (0x69)
#define XPOWERS_AXP2101_BTN_VOL_MIN (2600)
#define XPOWERS_AXP2101_BTN_VOL_MAX (3300)
#define XPOWERS_AXP2101_BTN_VOL_STEPS (100)
#define XPOWERS_AXP2101_BTN_BAT_CHG_VOL_SET (0x6A)
#define XPOWERS_AXP2101_DC_ONOFF_DVM_CTRL (0x80)
#define XPOWERS_AXP2101_DC_FORCE_PWM_CTRL (0x81)
#define XPOWERS_AXP2101_DC_VOL0_CTRL (0x82)
#define XPOWERS_AXP2101_DC_VOL1_CTRL (0x83)
#define XPOWERS_AXP2101_DC_VOL2_CTRL (0x84)
#define XPOWERS_AXP2101_DC_VOL3_CTRL (0x85)
#define XPOWERS_AXP2101_DC_VOL4_CTRL (0x86)
#define XPOWERS_AXP2101_LDO_ONOFF_CTRL0 (0x90)
#define XPOWERS_AXP2101_LDO_ONOFF_CTRL1 (0x91)
#define XPOWERS_AXP2101_LDO_VOL0_CTRL (0x92)
#define XPOWERS_AXP2101_LDO_VOL1_CTRL (0x93)
#define XPOWERS_AXP2101_LDO_VOL2_CTRL (0x94)
#define XPOWERS_AXP2101_LDO_VOL3_CTRL (0x95)
#define XPOWERS_AXP2101_LDO_VOL4_CTRL (0x96)
#define XPOWERS_AXP2101_LDO_VOL5_CTRL (0x97)
#define XPOWERS_AXP2101_LDO_VOL6_CTRL (0x98)
#define XPOWERS_AXP2101_LDO_VOL7_CTRL (0x99)
#define XPOWERS_AXP2101_LDO_VOL8_CTRL (0x9A)
#define XPOWERS_AXP2101_BAT_PARAME (0xA1)
#define XPOWERS_AXP2101_FUEL_GAUGE_CTRL (0xA2)
#define XPOWERS_AXP2101_BAT_PERCENT_DATA (0xA4)
// DCDC 1~5
#define XPOWERS_AXP2101_DCDC1_VOL_MIN (1500)
#define XPOWERS_AXP2101_DCDC1_VOL_MAX (3400)
#define XPOWERS_AXP2101_DCDC1_VOL_STEPS (100u)
#define XPOWERS_AXP2101_DCDC2_VOL1_MIN (500u)
#define XPOWERS_AXP2101_DCDC2_VOL1_MAX (1200u)
#define XPOWERS_AXP2101_DCDC2_VOL2_MIN (1220u)
#define XPOWERS_AXP2101_DCDC2_VOL2_MAX (1540u)
#define XPOWERS_AXP2101_DCDC2_VOL_STEPS1 (10u)
#define XPOWERS_AXP2101_DCDC2_VOL_STEPS2 (20u)
#define XPOWERS_AXP2101_DCDC2_VOL_STEPS1_BASE (0u)
#define XPOWERS_AXP2101_DCDC2_VOL_STEPS2_BASE (71)
#define XPOWERS_AXP2101_DCDC3_VOL1_MIN (500u)
#define XPOWERS_AXP2101_DCDC3_VOL1_MAX (1200u)
#define XPOWERS_AXP2101_DCDC3_VOL2_MIN (1220u)
#define XPOWERS_AXP2101_DCDC3_VOL2_MAX (1540u)
#define XPOWERS_AXP2101_DCDC3_VOL3_MIN (1600u)
#define XPOWERS_AXP2101_DCDC3_VOL3_MAX (3400u)
#define XPOWERS_AXP2101_DCDC3_VOL_MIN (500)
#define XPOWERS_AXP2101_DCDC3_VOL_MAX (3400)
#define XPOWERS_AXP2101_DCDC3_VOL_STEPS1 (10u)
#define XPOWERS_AXP2101_DCDC3_VOL_STEPS2 (20u)
#define XPOWERS_AXP2101_DCDC3_VOL_STEPS3 (100u)
#define XPOWERS_AXP2101_DCDC3_VOL_STEPS1_BASE (0u)
#define XPOWERS_AXP2101_DCDC3_VOL_STEPS2_BASE (71)
#define XPOWERS_AXP2101_DCDC3_VOL_STEPS3_BASE (88)
#define XPOWERS_AXP2101_DCDC4_VOL1_MIN (500u)
#define XPOWERS_AXP2101_DCDC4_VOL1_MAX (1200u)
#define XPOWERS_AXP2101_DCDC4_VOL2_MIN (1220u)
#define XPOWERS_AXP2101_DCDC4_VOL2_MAX (1840u)
#define XPOWERS_AXP2101_DCDC4_VOL_STEPS1 (10u)
#define XPOWERS_AXP2101_DCDC4_VOL_STEPS2 (20u)
#define XPOWERS_AXP2101_DCDC4_VOL_STEPS1_BASE (0u)
#define XPOWERS_AXP2101_DCDC4_VOL_STEPS2_BASE (71)
#define XPOWERS_AXP2101_DCDC5_VOL_1200MV (1200)
#define XPOWERS_AXP2101_DCDC5_VOL_VAL (0x19)
#define XPOWERS_AXP2101_DCDC5_VOL_MIN (1400)
#define XPOWERS_AXP2101_DCDC5_VOL_MAX (3700)
#define XPOWERS_AXP2101_DCDC5_VOL_STEPS (100u)
#define XPOWERS_AXP2101_VSYS_VOL_THRESHOLD_MIN (2600)
#define XPOWERS_AXP2101_VSYS_VOL_THRESHOLD_MAX (3300)
#define XPOWERS_AXP2101_VSYS_VOL_THRESHOLD_STEPS (100)
// ALDO 1~4
#define XPOWERS_AXP2101_ALDO1_VOL_MIN (500)
#define XPOWERS_AXP2101_ALDO1_VOL_MAX (3500)
#define XPOWERS_AXP2101_ALDO1_VOL_STEPS (100u)
#define XPOWERS_AXP2101_ALDO2_VOL_MIN (500)
#define XPOWERS_AXP2101_ALDO2_VOL_MAX (3500)
#define XPOWERS_AXP2101_ALDO2_VOL_STEPS (100u)
#define XPOWERS_AXP2101_ALDO3_VOL_MIN (500)
#define XPOWERS_AXP2101_ALDO3_VOL_MAX (3500)
#define XPOWERS_AXP2101_ALDO3_VOL_STEPS (100u)
#define XPOWERS_AXP2101_ALDO4_VOL_MIN (500)
#define XPOWERS_AXP2101_ALDO4_VOL_MAX (3500)
#define XPOWERS_AXP2101_ALDO4_VOL_STEPS (100u)
// BLDO 1~2
#define XPOWERS_AXP2101_BLDO1_VOL_MIN (500)
#define XPOWERS_AXP2101_BLDO1_VOL_MAX (3500)
#define XPOWERS_AXP2101_BLDO1_VOL_STEPS (100u)
#define XPOWERS_AXP2101_BLDO2_VOL_MIN (500)
#define XPOWERS_AXP2101_BLDO2_VOL_MAX (3500)
#define XPOWERS_AXP2101_BLDO2_VOL_STEPS (100u)
// CPUSLDO
#define XPOWERS_AXP2101_CPUSLDO_VOL_MIN (500)
#define XPOWERS_AXP2101_CPUSLDO_VOL_MAX (1400)
#define XPOWERS_AXP2101_CPUSLDO_VOL_STEPS (50)
// DLDO 1~2
#define XPOWERS_AXP2101_DLDO1_VOL_MIN (500)
#define XPOWERS_AXP2101_DLDO1_VOL_MAX (3400)
#define XPOWERS_AXP2101_DLDO1_VOL_STEPS (100u)
#define XPOWERS_AXP2101_DLDO2_VOL_MIN (500)
#define XPOWERS_AXP2101_DLDO2_VOL_MAX (3400)
#define XPOWERS_AXP2101_DLDO2_VOL_STEPS (100u)
#define XPOWERS_AXP2101_CONVERSION(raw) (22.0 + (7274 - raw) / 20.0)

View File

@@ -0,0 +1,95 @@
#pragma once
#define AXP216_SLAVE_ADDRESS (0x34)
#define XPOWERS_AXP216_CHIP_ID (0x41)
//CONTROL REGISTER
#define XPOWERS_AXP216_STATUS (0x00)
#define XPOWERS_AXP216_MODE_CHGSTATUS (0x01)
#define XPOWERS_AXP216_DATA_BUFFER1 (0x04)
#define XPOWERS_AXP216_DATA_BUFFER2 (0x05)
#define XPOWERS_AXP216_DATA_BUFFER3 (0x06)
#define XPOWERS_AXP216_DATA_BUFFER4 (0x07)
#define XPOWERS_AXP216_DATA_BUFFER5 (0x08)
#define XPOWERS_AXP216_DATA_BUFFER6 (0x09)
#define XPOWERS_AXP216_DATA_BUFFER7 (0x0A)
#define XPOWERS_AXP216_DATA_BUFFER8 (0x0B)
#define XPOWERS_AXP216_DATA_BUFFER9 (0x0C)
#define XPOWERS_AXP216_DATA_BUFFERA (0x0D)
#define XPOWERS_AXP216_DATA_BUFFERB (0x0E)
#define XPOWERS_AXP216_DATA_BUFFERC (0x0F)
#define XPOWERS_AXP216_IC_TYPE (0x03)
#define XPOWERS_AXP216_DC12345_ALDO12_CTL (0x10)
#define XPOWERS_AXP216_LDO123_CTL (0x12)
#define XPOWERS_AXP216_OUTPUT_CTL (0x13)
#define XPOWERS_AXP216_ELDO1_VCTL (0x19)
#define XPOWERS_AXP216_ELDO2_VCTL (0x1A)
#define XPOWERS_AXP216_DCDC1_VCTL (0x21)
#define XPOWERS_AXP216_DCDC2_VCTL (0x22)
#define XPOWERS_AXP216_DCDC3_VCTL (0x23)
#define XPOWERS_AXP216_DCDC4_VCTL (0x24)
#define XPOWERS_AXP216_DCDC5_VCTL (0x25)
#define XPOWERS_AXP216_DCDC23_VOLX (0x27)
#define XPOWERS_AXP216_ALDO1_VCTL (0x28)
#define XPOWERS_AXP216_ALDO2_VCTL (0x29)
#define XPOWERS_AXP216_ALDO3_VCTL (0x2A)
#define XPOWERS_AXP216_VBUS_IPSOUT (0x30)
#define XPOWERS_AXP216_VOFF_SET (0x31)
#define XPOWERS_AXP216_OFF_CTL (0x32)
#define XPOWERS_AXP216_CHARGE1 (0x33)
#define XPOWERS_AXP216_CHARGE2 (0x34)
#define XPOWERS_AXP216_CHARGE3 (0x35)
#define XPOWERS_AXP216_PEK_SET (0x36)
#define XPOWERS_AXP216_OFFLEVEL (0x37)
#define XPOWERS_AXP216_VLTF_CHGSET (0x38)
#define XPOWERS_AXP216_VHTF_CHGSET (0x39)
#define XPOWERS_AXP216_DCDC_FREQ (0x3B)
#define XPOWERS_AXP216_TLTF_DISCHGSET (0x3C)
#define XPOWERS_AXP216_THTF_DISCHGSET (0x3D)
#define XPOWERS_AXP216_DCDC_MODESET (0x80)
#define XPOWERS_AXP216_ADC_CTL (0x82)
#define XPOWERS_AXP216_ADC_SPEED (0x84)
#define XPOWERS_AXP216_TS_ADC (0x85)
#define XPOWERS_AXP216_TIMER_CTL (0x8A)
#define XPOWERS_AXP216_HOTOVER_CTL (0x8F)
//GPIO REGISTER
#define XPOWERS_AXP216_GPIO1_CTL (0x92)
#define XPOWERS_AXP216_GPIO1_LDO_CTL (0x93)
#define XPOWERS_AXP216_GPIO01_STATUS (0x94)
#define XPOWERS_AXP216_GPIO1_PULLDOWN_CTL (0x97)
//XPOWERS INTERRUPT REGISTER
#define XPOWERS_AXP216_INTEN1 (0x40)
#define XPOWERS_AXP216_INTEN2 (0x41)
#define XPOWERS_AXP216_INTEN3 (0x42)
#define XPOWERS_AXP216_INTEN4 (0x43)
#define XPOWERS_AXP216_INTEN5 (0x44)
//XPOWERS INTERRUPT STATUS REGISTER
#define XPOWERS_AXP216_INTSTS1 (0x48)
#define XPOWERS_AXP216_INTSTS2 (0x49)
#define XPOWERS_AXP216_INTSTS3 (0x4A)
#define XPOWERS_AXP216_INTSTS4 (0x4B)
#define XPOWERS_AXP216_INTSTS5 (0x4C)
//XPOWERS ADC DATA REGISTER
#define XPOWERS_AXP216_INTERNAL_TEMP_H8 (0x56)
#define XPOWERS_AXP216_INTERNAL_TEMP_L4 (0x57)
#define XPOWERS_AXP216_TS_IN_H8 (0x58)
#define XPOWERS_AXP216_TS_IN_L4 (0x59)
#define XPOWERS_AXP216_BAT_VOLTAGE_H8 (0x78)
#define XPOWERS_AXP216_BAT_VOLTAGE_L4 (0x79)
#define XPOWERS_AXP216_BAT_CHGCURCUR_H8 (0x7A)
#define XPOWERS_AXP216_BAT_CHGCURCUR_L4 (0x7B)
#define XPOWERS_AXP216_BAT_DISCHGCUR_H8 (0x7C)
#define XPOWERS_AXP216_BAT_DISCHGCUR_L4 (0x7D)
#define XPOWERS_AXP216_FUEL_GAUGE_CTRL (0xB8)
#define XPOWERS_AXP216_FUEL_GAUGE_REULST (0xB9)
#define XPOWERS_AXP216_BAT_CAPACITY_0 (0xE0)
#define XPOWERS_AXP216_BAT_CAPACITY_1 (0xE1)
#define XPOWERS_AXP216_BAT_LOW_WARNING_CTRL (0xE6)

View File

@@ -0,0 +1,45 @@
/**
*
* @license MIT License
*
* Copyright (c) 2022 lewis he
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* @file HUSB238Constants.h
* @author Lewis He (lewishe@outlook.com)
* @date 2024-07-24
*
*/
#pragma once
#define HUSB238_SLAVE_ADDRESS (0x8)
#define HUSB238_PD_STATUS0 (0x0)
#define HUSB238_PD_STATUS1 (0x1)
#define HUSB238_SRC_PDO_5V (0x2)
#define HUSB238_SRC_PDO_9V (0x3)
#define HUSB238_SRC_PDO_12V (0x4)
#define HUSB238_SRC_PDO_15V (0x5)
#define HUSB238_SRC_PDO_18V (0x6)
#define HUSB238_SRC_PDO_20V (0x7)
#define HUSB238_SRC_PDO (0x8)
#define HUSB238_GO_COMMAND (0x9)

View File

@@ -0,0 +1,126 @@
/**
*
* @license MIT License
*
* Copyright (c) 2022 lewis he
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* @file SY6970Constants.h
* @author Lewis He (lewishe@outlook.com)
* @date 2023-07-20
*
*/
#pragma once
#define SY6970_SLAVE_ADDRESS (0x6A)
// https://www.ti.com/product/BQ25896
#define BQ25896_SLAVE_ADDRESS (0x6B)
// https://www.sg-micro.com/cnproduct/SGM41511
#define SGM41511_SLAVE_ADDRESS (0x6B)
#define SY6970_DEV_REV (0x00)
#define BQ25896_DEV_REV (0x02)
#define POWERS_SY6970_REG_00H (0x00)
#define POWERS_SY6970_REG_01H (0x01)
#define POWERS_SY6970_REG_02H (0x02)
#define POWERS_SY6970_REG_03H (0x03)
#define POWERS_SY6970_REG_04H (0x04)
#define POWERS_SY6970_REG_05H (0x05)
#define POWERS_SY6970_REG_06H (0x06)
#define POWERS_SY6970_REG_07H (0x07)
#define POWERS_SY6970_REG_08H (0x08)
#define POWERS_SY6970_REG_09H (0x09)
#define POWERS_SY6970_REG_0AH (0x0A)
// Read only STATUS REG
#define POWERS_SY6970_REG_0BH (0x0B)
// Read only CHARGE IRQ REG
#define POWERS_SY6970_REG_0CH (0x0C)
// Absolute VINDPM Threshold
#define POWERS_SY6970_REG_0DH (0x0D)
// Read only BATTERY VOLTAGE
#define POWERS_SY6970_REG_0EH (0x0E)
// Read only SYSTEM VOLTAGE
#define POWERS_SY6970_REG_0FH (0x0F)
// Read only NTC PERCENTAGE
#define POWERS_SY6970_REG_10H (0x10)
// Read only VBUS VOLTAGE
#define POWERS_SY6970_REG_11H (0x11)
// Read only CHARGE CURRENT
#define POWERS_SY6970_REG_12H (0x12)
// Read only VINDPM/IINDPM STATUS/CURR LIMIT SETTING
#define POWERS_SY6970_REG_13H (0x13)
// RESET REG
#define POWERS_SY6970_REG_14H (0x14)
#define POWERS_SY6970_VBUS_MASK_VAL(val) (val & 0x7F)
#define POWERS_SY6970_VBAT_MASK_VAL(val) (val & 0x7F)
#define POWERS_SY6970_VSYS_MASK_VAL(val) (val & 0x7F)
#define POWERS_SY6970_NTC_MASK_VAL(val) (val & 0x7F)
#define POWERS_SY6970_VBUS_BASE_VAL (2600)
#define POWERS_SY6970_VBAT_BASE_VAL (2304)
#define POWERS_SY6970_VSYS_BASE_VAL (2304)
#define POWERS_SY6970_NTC_BASE_VAL (21)
#define POWERS_SY6970_VBUS_VOL_STEP (100)
#define POWERS_SY6970_VBAT_VOL_STEP (20)
#define POWERS_SY6970_VSYS_VOL_STEP (20)
#define POWERS_SY6970_NTC_VOL_STEP (0.465)
#define POWERS_SY6970_CHG_STEP_VAL (50)
#define POWERS_SY6970_PRE_CHG_CUR_BASE (64)
#define POWERS_SY6970_FAST_CHG_CUR_STEP (64)
#define POWERS_SY6970_PRE_CHG_CUR_STEP (64)
#define POWERS_FAST_CHG_CURRENT_MIN (0)
#define POWERS_FAST_CHG_CURRENT_MAX (5056)
#define POWERS_PRE_CHG_CURRENT_MIN (64)
#define POWERS_PRE_CHG_CURRENT_MAX (1024)
#define POWERS_SY6970_CHG_VOL_BASE (3840)
#define POWERS_SY6970_CHG_VOL_STEP (16)
#define POWERS_FAST_CHG_VOL_MIN (3840)
#define POWERS_FAST_CHG_VOL_MAX (4608)
#define POWERS_SY6970_SYS_VOL_STEPS (100)
#define POWERS_SY6970_SYS_VOFF_VOL_MIN (3000)
#define POWERS_SY6970_SYS_VOFF_VOL_MAX (3700)
#define POWERS_SY6970_IN_CURRENT_STEP (50)
#define POWERS_SY6970_IN_CURRENT_MIN (100)
#define POWERS_SY6970_IN_CURRENT_MAX (3250)
#define POWERS_SY6970_BOOTS_VOL_BASE (4550)
#define POWERS_SY6970_BOOTS_VOL_STEP (64)
#define POWERS_SY6970_BOOST_VOL_MIN (4550)
#define POWERS_SY6970_BOOST_VOL_MAX (5510)
#define POWERS_SY6970_IRQ_WTD_FAULT(x) (bool)(( x & 0xFF ) >> 7)
#define POWERS_SY6970_IRQ_BOOST_FAULT(x) (bool)(( x & 0xFF ) >> 6)
#define POWERS_SY6970_IRQ_CHG_FAULT(x) (bool)(( x & 0xFF ) >> 5)
#define POWERS_SY6970_IRQ_BAT_FAULT(x) (bool)(( x & 0xFF ) >> 4)
#define POWERS_SY6970_IRQ_NTC_FAULT(x) (bool)(( x & 0xFF ) & 0x03)
#define POWERS_SY6970_VINDPM_VOL_BASE (4550)
#define POWERS_SY6970_VINDPM_VOL_STEPS (100)
#define POWERS_SY6970_VINDPM_VOL_MIN (3900)
#define POWERS_SY6970_VINDPM_VOL_MAX (15300)

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,512 @@
/**
*
* @license MIT License
*
* Copyright (c) 2022 lewis he
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* @file XPowersCommon.h
* @author Lewis He (lewishe@outlook.com)
* @date 2022-05-07
*
*/
#pragma once
#include <stdint.h>
#if defined(ARDUINO)
#include <Wire.h>
#elif defined(ESP_PLATFORM)
#include "esp_log.h"
#include "esp_err.h"
#include <cstring>
#include "esp_idf_version.h"
#if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5,0,0)) && defined(CONFIG_XPOWERS_ESP_IDF_NEW_API)
#include "driver/i2c_master.h"
#else
#include "driver/i2c.h"
#define XPOWERSLIB_I2C_MASTER_TX_BUF_DISABLE 0 /*!< I2C master doesn't need buffer */
#define XPOWERSLIB_I2C_MASTER_RX_BUF_DISABLE 0 /*!< I2C master doesn't need buffer */
#define XPOWERSLIB_I2C_MASTER_TIMEOUT_MS 1000
#endif //ESP_IDF_VERSION
#endif //ESP_PLATFORM
#define XPOWERSLIB_I2C_MASTER_SPEED 400000
#ifdef _BV
#undef _BV
#endif
#define _BV(b) (1ULL << (uint64_t)(b))
#ifndef constrain
#define constrain(amt,low,high) ((amt)<(low)?(low):((amt)>(high)?(high):(amt)))
#endif
#define XPOWERS_ATTR_NOT_IMPLEMENTED __attribute__((error("Not implemented")))
#define IS_BIT_SET(val,mask) (((val)&(mask)) == (mask))
#if !defined(ARDUINO)
#ifdef linux
#include <stdio.h>
#include <string.h>
#include <errno.h>
#define log_e(__info,...) printf("error :" __info,##__VA_ARGS__)
#define log_i(__info,...) printf("info :" __info,##__VA_ARGS__)
#define log_d(__info,...) printf("debug :" __info,##__VA_ARGS__)
#else
#define log_e(...)
#define log_i(...)
#define log_d(...)
#endif
#define LOW 0x0
#define HIGH 0x1
//GPIO FUNCTIONS
#define INPUT 0x01
#define OUTPUT 0x03
#define PULLUP 0x04
#define INPUT_PULLUP 0x05
#define PULLDOWN 0x08
#define INPUT_PULLDOWN 0x09
#define RISING 0x01
#define FALLING 0x02
#endif
#ifndef ESP32
#ifdef LOG_FILE_LINE_INFO
#undef LOG_FILE_LINE_INFO
#endif
#define LOG_FILE_LINE_INFO __FILE__, __LINE__
#ifndef log_e
#define log_e(fmt, ...) Serial.printf("[E][%s:%d] " fmt "\n", LOG_FILE_LINE_INFO, ##__VA_ARGS__)
#endif
#ifndef log_i
#define log_i(fmt, ...) Serial.printf("[I][%s:%d] " fmt "\n", LOG_FILE_LINE_INFO, ##__VA_ARGS__)
#endif
#ifndef log_d
#define log_d(fmt, ...) Serial.printf("[D][%s:%d] " fmt "\n", LOG_FILE_LINE_INFO, ##__VA_ARGS__)
#endif
#endif
#if defined(NRF52840_XXAA) || defined(NRF52832_XXAA)
#ifndef SDA
#define SDA (0xFF)
#endif
#ifndef SCL
#define SCL (0xFF)
#endif
#endif
typedef int (*iic_fptr_t)(uint8_t devAddr, uint8_t regAddr, uint8_t *data, uint8_t len);
template <class chipType>
class XPowersCommon
{
public:
#if defined(ARDUINO)
bool begin(TwoWire &w, uint8_t addr, int sda, int scl)
{
if (__has_init)return thisChip().initImpl();
__has_init = true;
__sda = sda;
__scl = scl;
__wire = &w;
#if defined(NRF52840_XXAA) || defined(NRF52832_XXAA)
if (__sda != 0xFF && __scl != 0xFF) {
__wire->setPins(__sda, __scl);
}
__wire->begin();
#elif defined(ARDUINO_ARCH_RP2040) || defined(ARDUINO_ARCH_STM32)
if (__sda != 0xFF && __scl != 0xFF) {
__wire->end();
__wire->setSDA(__sda);
__wire->setSCL(__scl);
}
__wire->begin();
#elif defined(ARDUINO_ARCH_ESP32)
__wire->begin(__sda, __scl);
#else
__wire->begin();
#endif
__addr = addr;
return thisChip().initImpl();
}
#elif defined(ESP_PLATFORM)
#if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5,0,0)) && defined(CONFIG_XPOWERS_ESP_IDF_NEW_API)
// * Using the new API of esp-idf 5.x, you need to pass the I2C BUS handle,
// * which is useful when the bus shares multiple devices.
bool begin(i2c_master_bus_handle_t i2c_dev_bus_handle, uint8_t addr)
{
log_i("Using ESP-IDF Driver interface.");
if (i2c_dev_bus_handle == NULL) return false;
if (__has_init)return thisChip().initImpl();
thisReadRegCallback = NULL;
thisWriteRegCallback = NULL;
/*
i2c_master_bus_config_t i2c_bus_config;
memset(&i2c_bus_config, 0, sizeof(i2c_bus_config));
i2c_bus_config.clk_source = I2C_CLK_SRC_DEFAULT;
i2c_bus_config.i2c_port = port_num;
i2c_bus_config.scl_io_num = (gpio_num_t)__scl;
i2c_bus_config.sda_io_num = (gpio_num_t)__sda;
i2c_bus_config.glitch_ignore_cnt = 7;
i2c_new_master_bus(&i2c_bus_config, &bus_handle);
*/
bus_handle = i2c_dev_bus_handle;
i2c_device_config_t i2c_dev_conf = {
.dev_addr_length = I2C_ADDR_BIT_LEN_7,
.device_address = addr,
.scl_speed_hz = XPOWERSLIB_I2C_MASTER_SPEED,
#if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5,3,0))
#if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5,4,0))
// New fields since esp-idf-v5.3-beta1
.scl_wait_us = 0,
#endif
.flags = {
. disable_ack_check = 0
}
#endif
};
if (ESP_OK != i2c_master_bus_add_device(bus_handle,
&i2c_dev_conf,
&__i2c_device)) {
return false;
}
__has_init = thisChip().initImpl();
if (!__has_init) {
// Initialization failed, delete device
i2c_master_bus_rm_device(__i2c_device);
}
return __has_init;
}
#else //ESP 4.X
bool begin(i2c_port_t port_num, uint8_t addr, int sda, int scl)
{
__i2c_num = port_num;
log_i("Using ESP-IDF Driver interface.");
if (__has_init)return thisChip().initImpl();
__sda = sda;
__scl = scl;
__addr = addr;
thisReadRegCallback = NULL;
thisWriteRegCallback = NULL;
i2c_config_t i2c_conf;
memset(&i2c_conf, 0, sizeof(i2c_conf));
i2c_conf.mode = I2C_MODE_MASTER;
i2c_conf.sda_io_num = sda;
i2c_conf.scl_io_num = scl;
i2c_conf.sda_pullup_en = GPIO_PULLUP_ENABLE;
i2c_conf.scl_pullup_en = GPIO_PULLUP_ENABLE;
i2c_conf.master.clk_speed = XPOWERSLIB_I2C_MASTER_SPEED;
/**
* @brief Without checking whether the initialization is successful,
* I2C may be initialized externally,
* so just make sure there is an initialization here.
*/
i2c_param_config(__i2c_num, &i2c_conf);
i2c_driver_install(__i2c_num,
i2c_conf.mode,
XPOWERSLIB_I2C_MASTER_RX_BUF_DISABLE,
XPOWERSLIB_I2C_MASTER_TX_BUF_DISABLE, 0);
__has_init = thisChip().initImpl();
return __has_init;
}
#endif //ESP 5.X
#endif //ESP_PLATFORM
bool begin(uint8_t addr, iic_fptr_t readRegCallback, iic_fptr_t writeRegCallback)
{
if (__has_init)return thisChip().initImpl();
__has_init = true;
thisReadRegCallback = readRegCallback;
thisWriteRegCallback = writeRegCallback;
__addr = addr;
return thisChip().initImpl();
}
int readRegister(uint8_t reg)
{
uint8_t val = 0;
return readRegister(reg, &val, 1) == -1 ? -1 : val;
}
int writeRegister(uint8_t reg, uint8_t val)
{
return writeRegister(reg, &val, 1);
}
int readRegister(uint8_t reg, uint8_t *buf, uint8_t length)
{
if (thisReadRegCallback) {
return thisReadRegCallback(__addr, reg, buf, length);
}
#if defined(ARDUINO)
if (__wire) {
__wire->beginTransmission(__addr);
__wire->write(reg);
if (__wire->endTransmission() != 0) {
return -1;
}
__wire->requestFrom(__addr, length);
return __wire->readBytes(buf, length) == length ? 0 : -1;
}
#elif defined(ESP_PLATFORM)
#if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5,0,0)) && defined(CONFIG_XPOWERS_ESP_IDF_NEW_API)
if (ESP_OK == i2c_master_transmit_receive(
__i2c_device,
(const uint8_t *)&reg,
1,
buf,
length,
-1)) {
return 0;
}
#else //ESP_IDF_VERSION
if (ESP_OK == i2c_master_write_read_device(__i2c_num,
__addr,
(uint8_t *)&reg,
1,
buf,
length,
XPOWERSLIB_I2C_MASTER_TIMEOUT_MS / portTICK_PERIOD_MS)) {
return 0;
}
#endif //ESP_IDF_VERSION
#endif //ESP_PLATFORM
return -1;
}
int writeRegister(uint8_t reg, uint8_t *buf, uint8_t length)
{
if (thisWriteRegCallback) {
return thisWriteRegCallback(__addr, reg, buf, length);
}
#if defined(ARDUINO)
if (__wire) {
__wire->beginTransmission(__addr);
__wire->write(reg);
__wire->write(buf, length);
return (__wire->endTransmission() == 0) ? 0 : -1;
}
return -1;
#elif defined(ESP_PLATFORM)
uint8_t *write_buffer = (uint8_t *)malloc(sizeof(uint8_t) * (length + 1));
if (!write_buffer) {
return -1;
}
write_buffer[0] = reg;
memcpy(write_buffer + 1, buf, length);
#if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5,0,0)) && defined(CONFIG_XPOWERS_ESP_IDF_NEW_API)
if (ESP_OK != i2c_master_transmit(
__i2c_device,
write_buffer,
length + 1,
-1)) {
free(write_buffer);
return -1;
}
#else //ESP_IDF_VERSION
if (ESP_OK != i2c_master_write_to_device(__i2c_num,
__addr,
write_buffer,
length + 1,
XPOWERSLIB_I2C_MASTER_TIMEOUT_MS / portTICK_PERIOD_MS)) {
free(write_buffer);
return -1;
}
#endif //ESP_IDF_VERSION
free(write_buffer);
return 0;
#endif //ESP_PLATFORM
return 0;
}
bool inline clrRegisterBit(uint8_t registers, uint8_t bit)
{
int val = readRegister(registers);
if (val == -1) {
return false;
}
return writeRegister(registers, (val & (~_BV(bit)))) == 0;
}
bool inline setRegisterBit(uint8_t registers, uint8_t bit)
{
int val = readRegister(registers);
if (val == -1) {
return false;
}
return writeRegister(registers, (val | (_BV(bit)))) == 0;
}
bool inline getRegisterBit(uint8_t registers, uint8_t bit)
{
int val = readRegister(registers);
if (val == -1) {
return false;
}
return val & _BV(bit);
}
uint16_t inline readRegisterH8L4(uint8_t highReg, uint8_t lowReg)
{
int h8 = readRegister(highReg);
int l4 = readRegister(lowReg);
if (h8 == -1 || l4 == -1)return 0;
return (h8 << 4) | (l4 & 0x0F);
}
uint16_t inline readRegisterH8L5(uint8_t highReg, uint8_t lowReg)
{
int h8 = readRegister(highReg);
int l5 = readRegister(lowReg);
if (h8 == -1 || l5 == -1)return 0;
return (h8 << 5) | (l5 & 0x1F);
}
uint16_t inline readRegisterH6L8(uint8_t highReg, uint8_t lowReg)
{
int h6 = readRegister(highReg);
int l8 = readRegister(lowReg);
if (h6 == -1 || l8 == -1)return 0;
return ((h6 & 0x3F) << 8) | l8;
}
uint16_t inline readRegisterH5L8(uint8_t highReg, uint8_t lowReg)
{
int h5 = readRegister(highReg);
int l8 = readRegister(lowReg);
if (h5 == -1 || l8 == -1)return 0;
return ((h5 & 0x1F) << 8) | l8;
}
/*
* CRTP Helper
*/
protected:
bool begin()
{
#if defined(ARDUINO)
if (__has_init) return thisChip().initImpl();
__has_init = true;
if (__wire) {
log_i("SDA:%d SCL:%d", __sda, __scl);
#if defined(NRF52840_XXAA) || defined(NRF52832_XXAA)
if (__sda != 0xFF && __scl != 0xFF) {
__wire->setPins(__sda, __scl);
}
__wire->begin();
#elif defined(ARDUINO_ARCH_RP2040) || defined(ARDUINO_ARCH_STM32)
if (__sda != 0xFF && __scl != 0xFF) {
__wire->end();
__wire->setSDA(__sda);
__wire->setSCL(__scl);
}
__wire->begin();
#elif defined(ARDUINO_ARCH_ESP32)
__wire->begin(__sda, __scl);
#else
__wire->begin();
#endif
}
#endif /*ARDUINO*/
return thisChip().initImpl();
}
void end()
{
#if defined(ARDUINO)
if (__wire) {
#if defined(ESP_IDF_VERSION)
#if ESP_IDF_VERSION > ESP_IDF_VERSION_VAL(4,4,0)
__wire->end();
#endif /*ESP_IDF_VERSION*/
#endif /*ESP_IDF_VERSION*/
}
#endif /*ARDUINO*/
}
inline const chipType &thisChip() const
{
return static_cast<const chipType &>(*this);
}
inline chipType &thisChip()
{
return static_cast<chipType &>(*this);
}
protected:
bool __has_init = false;
#if defined(ARDUINO)
TwoWire *__wire = NULL;
#elif defined(ESP_PLATFORM)
i2c_port_t __i2c_num;
#if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5,0,0)) && defined(CONFIG_XPOWERS_ESP_IDF_NEW_API)
i2c_master_bus_handle_t bus_handle;
i2c_master_dev_handle_t __i2c_device;
#endif //ESP_IDF_VERSION
#endif //ESP_PLATFORM
int __sda = -1;
int __scl = -1;
uint8_t __addr = 0xFF;
iic_fptr_t thisReadRegCallback = NULL;
iic_fptr_t thisWriteRegCallback = NULL;
};

View File

@@ -0,0 +1,37 @@
/**
* @file XPowersLib.h
* @author Lewis He (lewishe@outlook.com)
* @license MIT
* @copyright Copyright (c) 2022
* @date 2022-05-07
*
*/
#ifndef __XPOWERSLIB_H__
#define __XPOWERSLIB_H__
#if defined(XPOWERS_CHIP_AXP192)
#include "XPowersAXP192.tpp"
typedef XPowersAXP192 XPowersPMU;
#elif defined(XPOWERS_CHIP_AXP202)
#include "XPowersAXP202.tpp"
typedef XPowersAXP202 XPowersPMU;
#elif defined(XPOWERS_CHIP_AXP2101)
#include "XPowersAXP2101.tpp"
typedef XPowersAXP2101 XPowersPMU;
#else
#include "XPowersAXP192.tpp"
#include "XPowersAXP202.tpp"
#include "XPowersAXP2101.tpp"
#include "PowersSY6970.tpp"
#include "PowerDeliveryHUSB238.hpp"
#endif
#endif /*__XPOWERSLIB_H__*/

View File

@@ -0,0 +1,173 @@
/**
*
* @license MIT License
*
* Copyright (c) 2022 lewis he
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* @file XPowersLibInterface.cpp
* @author Lewis He (lewishe@outlook.com)
* @date 2022-08-28
*
*/
#if defined(ARDUINO)
#include <Arduino.h>
#endif
#include "XPowersLibInterface.hpp"
bool XPowersLibInterface::isChannelAvailable(uint8_t channel)
{
if (__chipModel == XPOWERS_AXP192) {
switch (channel) {
case XPOWERS_DCDC1:
case XPOWERS_DCDC2:
case XPOWERS_DCDC3:
case XPOWERS_LDO2:
case XPOWERS_LDO3:
case XPOWERS_LDOIO:
return true;
default:
return false;
}
} else if (__chipModel == XPOWERS_AXP202) {
switch (channel) {
case XPOWERS_DCDC2:
case XPOWERS_DCDC3:
case XPOWERS_LDO2:
case XPOWERS_LDO3:
case XPOWERS_LDO4:
case XPOWERS_LDO5:
return true;
default:
return false;
}
} else if (__chipModel == XPOWERS_AXP2101) {
switch (channel) {
case XPOWERS_DCDC1:
case XPOWERS_DCDC2:
case XPOWERS_DCDC3:
case XPOWERS_DCDC4:
case XPOWERS_DCDC5:
case XPOWERS_ALDO1:
case XPOWERS_ALDO2:
case XPOWERS_ALDO3:
case XPOWERS_ALDO4:
case XPOWERS_BLDO1:
case XPOWERS_BLDO2:
case XPOWERS_VBACKUP:
case XPOWERS_CPULDO:
return true;
default:
// DLDO is not available, will also return false
return false;
}
}
return false;
}
void XPowersLibInterface::setProtectedChannel(uint8_t channel)
{
__protectedMask |= _BV(channel);
}
void XPowersLibInterface::setUnprotectChannel(uint8_t channel)
{
__protectedMask &= (~_BV(channel));
}
bool XPowersLibInterface::getProtectedChannel(uint8_t channel)
{
return __protectedMask & _BV(channel);
}
uint16_t XPowersLibInterface::getVbusVoltage()
{
return 0;
}
static uint64_t inline check_params(uint32_t opt, uint32_t params, uint64_t mask)
{
return ((opt & params) == params) ? mask : 0;
}
bool XPowersLibInterface::enableInterrupt(uint32_t option)
{
return setInterruptMask(option, true);
}
bool XPowersLibInterface::disableInterrupt(uint32_t option)
{
return setInterruptMask(option, false);
}
bool XPowersLibInterface::setInterruptMask(uint32_t option, bool enable)
{
uint64_t params = 0;
switch (__chipModel) {
case XPOWERS_AXP173:
break;
case XPOWERS_AXP192:
params |= check_params(option, XPOWERS_USB_INSERT_INT, XPOWERS_AXP192_VBUS_INSERT_IRQ);
params |= check_params(option, XPOWERS_USB_REMOVE_INT, XPOWERS_AXP192_VBUS_REMOVE_IRQ);
params |= check_params(option, XPOWERS_BATTERY_INSERT_INT, XPOWERS_AXP192_BAT_INSERT_IRQ);
params |= check_params(option, XPOWERS_BATTERY_REMOVE_INT, XPOWERS_AXP192_BAT_REMOVE_IRQ);
params |= check_params(option, XPOWERS_CHARGE_START_INT, XPOWERS_AXP192_BAT_CHG_START_IRQ);
params |= check_params(option, XPOWERS_CHARGE_DONE_INT, XPOWERS_AXP192_BAT_CHG_DONE_IRQ);
params |= check_params(option, XPOWERS_PWR_BTN_CLICK_INT, XPOWERS_AXP192_PKEY_SHORT_IRQ);
params |= check_params(option, XPOWERS_PWR_BTN_LONGPRESSED_INT, XPOWERS_AXP192_PKEY_LONG_IRQ);
params |= check_params(option, XPOWERS_ALL_INT, XPOWERS_AXP192_ALL_IRQ);
return enable ? enableIRQ(params) : disableIRQ(params);
break;
case XPOWERS_AXP202:
params |= check_params(option, XPOWERS_USB_INSERT_INT, XPOWERS_AXP202_VBUS_INSERT_IRQ);
params |= check_params(option, XPOWERS_USB_REMOVE_INT, XPOWERS_AXP202_VBUS_REMOVE_IRQ);
params |= check_params(option, XPOWERS_BATTERY_INSERT_INT, XPOWERS_AXP202_BAT_INSERT_IRQ);
params |= check_params(option, XPOWERS_BATTERY_REMOVE_INT, XPOWERS_AXP202_BAT_REMOVE_IRQ);
params |= check_params(option, XPOWERS_CHARGE_START_INT, XPOWERS_AXP202_BAT_CHG_START_IRQ);
params |= check_params(option, XPOWERS_CHARGE_DONE_INT, XPOWERS_AXP202_BAT_CHG_DONE_IRQ);
params |= check_params(option, XPOWERS_PWR_BTN_CLICK_INT, XPOWERS_AXP202_PKEY_SHORT_IRQ);
params |= check_params(option, XPOWERS_PWR_BTN_LONGPRESSED_INT, XPOWERS_AXP202_PKEY_LONG_IRQ);
params |= check_params(option, XPOWERS_ALL_INT, XPOWERS_AXP202_ALL_IRQ);
return enable ? enableIRQ(params) : disableIRQ(params);
break;
case XPOWERS_AXP216:
break;
case XPOWERS_AXP2101:
params |= check_params(option, XPOWERS_USB_INSERT_INT, XPOWERS_AXP2101_VBUS_INSERT_IRQ);
params |= check_params(option, XPOWERS_USB_REMOVE_INT, XPOWERS_AXP2101_VBUS_REMOVE_IRQ);
params |= check_params(option, XPOWERS_BATTERY_INSERT_INT, XPOWERS_AXP2101_BAT_INSERT_IRQ);
params |= check_params(option, XPOWERS_BATTERY_REMOVE_INT, XPOWERS_AXP2101_BAT_REMOVE_IRQ);
params |= check_params(option, XPOWERS_CHARGE_START_INT, XPOWERS_AXP2101_BAT_CHG_START_IRQ);
params |= check_params(option, XPOWERS_CHARGE_DONE_INT, XPOWERS_AXP2101_BAT_CHG_DONE_IRQ);
params |= check_params(option, XPOWERS_PWR_BTN_CLICK_INT, XPOWERS_AXP2101_PKEY_SHORT_IRQ);
params |= check_params(option, XPOWERS_PWR_BTN_LONGPRESSED_INT, XPOWERS_AXP2101_PKEY_LONG_IRQ);
params |= check_params(option, XPOWERS_ALL_INT, XPOWERS_AXP2101_ALL_IRQ);
return enable ? enableIRQ(params) : disableIRQ(params);
break;
default:
break;
}
return false;
}

View File

@@ -0,0 +1,672 @@
/**
*
* @license MIT License
*
* Copyright (c) 2022 lewis he
*
* Permission is hereby granted,free of charge,to any person obtaining a copy
* of this software and associated documentation files (the "Software"),to deal
* in the Software without restriction,including without limitation the rights
* to use,copy,modify,merge,publish,distribute,sublicense,and/or sell
* copies of the Software,and to permit persons to whom the Software is
* furnished to do so,subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS",WITHOUT WARRANTY OF ANY KIND,EXPRESS OR
* IMPLIED,INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,DAMAGES OR OTHER
* LIABILITY,WHETHER IN AN ACTION OF CONTRACT,TORT OR OTHERWISE,ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* @file XPowersLibInterface.hpp
* @author Lewis He (lewishe@outlook.com)
* @date 2022-08-28
*
*/
#pragma once
#include <stdint.h>
#include "XPowersParams.hpp"
/*
| CHIP | AXP173 | AXP192 | AXP202 | AXP2101 |
| ---------- | ----------------- | ----------------- | ----------------- | -------------------------------------- |
| DC1 | 0.7V-3.5V /1.2A | 0.7V-3.5V /1.2A | X | 1.5-3.4V /2A |
| DC2 | 0.7-2.275V/0.6A | 0.7-2.275V /1.6A | 0.7-2.275V /1.6A | 0.5-1.2V,1.22-1.54V /2A |
| DC3 | X | 0.7-3.5V /0.7A | 0.7-3.5V /1.2A | 0.5-1.2V,1.22-1.54V,1.6-3.4V /2A |
| DC4 | X | x | x | 0.5-1.2V,1.22-1.84V /1.5A |
| DC5 | X | x | x | 1.2V,1.4-3.7V /1A |
| LDO1(VRTC) | 3.3V /30mA | 3.3V /30mA | 3.3V /30mA | 1.8V /30mA |
| LDO2 | 1.8V-3.3V /200mA | 1.8V-3.3V /200mA | 1.8V-3.3V /200mA | x |
| LDO3 | 1.8V-3.3V /200mA | 1.8-3.3V /200mA | 0.7-3.5V /200mA | x |
| LDO4 | 0.7-3.5V /500mA | X | 1.8V-3.3V /200mA | x |
| LDO5/IO0 | X | 1.8-3.3V /50mA | 1.8-3.3V /50mA | x |
| ALDO1 | x | x | x | 0.5-3.5V /300mA |
| ALDO2 | x | x | x | 0.5-3.5V /300mA |
| ALDO3 | x | x | x | 0.5-3.5V /300mA |
| ALDO4 | x | x | x | 0.5-3.5V /300mA |
| BLDO1 | x | x | x | 0.5-3.5V /300mA |
| BLDO2 | x | x | x | 0.5-3.5V /300mA |
| DLDO1 | x | x | x | 0.5-3.3V/ 0.5-1.4V /300mA |
| DLDO1 | x | x | x | 0.5-3.3V/ 0.5-1.4V /300mA |
| CPUSLDO | x | x | x | 0.5-1.4V /30mA |
| | | | | |
*/
// @brief Each chip resource is different,please refer to the table above
typedef enum __XPowersPowerChannel {
XPOWERS_DCDC1,
XPOWERS_DCDC2,
XPOWERS_DCDC3,
XPOWERS_DCDC4,
XPOWERS_DCDC5,
XPOWERS_LDO1,
XPOWERS_LDO2,
XPOWERS_LDO3,
XPOWERS_LDO4,
XPOWERS_LDO5,
XPOWERS_LDOIO,
XPOWERS_ALDO1,
XPOWERS_ALDO2,
XPOWERS_ALDO3,
XPOWERS_ALDO4,
XPOWERS_BLDO1,
XPOWERS_BLDO2,
XPOWERS_DLDO1,
XPOWERS_DLDO2,
XPOWERS_VBACKUP,
XPOWERS_CPULDO,
} XPowersPowerChannel_t;
// @brief Chip type
typedef enum __XPowersChipModel {
XPOWERS_AXP173,
XPOWERS_AXP192,
XPOWERS_AXP202,
XPOWERS_AXP216,
XPOWERS_AXP2101,
XPOWERS_UNDEFINED,
} XPowersChipModel_t;
/**
* @brief Compatible with subclasses of the Meshtastic-devic project
*/
class HasBatteryLevel
{
public:
/**
* @brief Get battery percentage
* @retval 0~100% , -1 no battery is connected
*/
virtual int getBatteryPercent()
{
return -1;
}
/**
* @brief Get battery Voltage
* @retval Voltage unit: millivolt , 0 is no battery is connected
*/
virtual uint16_t getBattVoltage()
{
return 0;
}
/**
* @brief Query whether the current battery is connected
* @retval true to access,false to not access
*/
virtual bool isBatteryConnect()
{
return false;
}
/**
* @brief Query whether the current USB is connected
* @retval true to access,false to not access
*/
virtual bool isVbusIn()
{
return false;
}
/**
* @brief Query whether it is currently in charging state
* @retval true to charge,false to not charge
*/
virtual bool isCharging()
{
return false;
}
};
// @brief Power resource interface class
class XPowersLibInterface : public HasBatteryLevel
{
public:
XPowersLibInterface() : __chipModel(XPOWERS_UNDEFINED), __protectedMask(0) {};
virtual ~XPowersLibInterface() {}
/**
* @brief Calling the XPowersLibInterface interface class
* requires calling init for initialization
* @retval
*/
virtual bool init() = 0;
/**
* @brief When calling the XPowersLibInterface interface class,
* calling deinit releases the Wire handle
* @retval None
*/
virtual void deinit() = 0;
/**
* @brief Set the PMU sleep flag,
* need to manually close the power channel after setting
* @retval true success false failed
*/
virtual bool enableSleep() = 0;
/**
* @brief Set shutdown, calling shutdown will turn off all power channels,
* only VRTC belongs to normal power supply
* @retval None
*/
virtual void shutdown() = 0;
/**
* @brief Get PMU satatus register
* @note
* @retval register value
*/
virtual uint16_t status() = 0;
/**
* @brief Query chip ID
* @retval Chip ID
*/
virtual uint8_t getChipID() = 0;
//Status function
/**
* @brief Query whether it is currently in charging state
* @retval true to charge,false to not charge
*/
// virtual bool isCharging() = 0;
/**
* @brief Query whether the current USB is connected
* @retval true to access,false to not access
*/
// virtual bool isVbusIn() = 0;
/**
* @brief Query whether the current battery is connected
* @retval true to access,false to not access
*/
// virtual bool isBatteryConnect() = 0;
/**
* @brief Query whether the current is in the discharge state
* @retval true the battery is discharged,false is not discharged
*/
virtual bool isDischarge() = 0;
//Power Channel Control
/**
* @brief Turn on the power channel
* @param channel: Parameters See XPowersPowerChannel_t enumeration
* @retval true success false failed
*/
virtual bool enablePowerOutput(uint8_t channel) = 0;
/**
* @brief Turn off the power channel
* @param channel: Parameters See XPowersPowerChannel_t enumeration
* @retval true success false failed
*/
virtual bool disablePowerOutput(uint8_t channel) = 0;
/**
* @brief Get whether the power channel is enabled
* @param channel: Parameters See XPowersPowerChannel_t enumeration
* @retval true success false failed
*/
virtual bool isPowerChannelEnable(uint8_t channel) = 0;
/**
* @brief Get the set voltage of the power channel
* @param channel: Parameters See XPowersPowerChannel_t enumeration
* @retval true success false failed
*/
virtual uint16_t getPowerChannelVoltage(uint8_t channel) = 0;
/**
* @brief Set the output voltage of a channel power supply
* @param channel: Parameters See XPowersPowerChannel_t enumeration
* @retval true success false failed
*/
virtual bool setPowerChannelVoltage(uint8_t channel, uint16_t millivolt) = 0;
/**
* @brief Set a channel power protection,after setting this channel
* will not be able to be set and closed
* @param channel: Parameters See XPowersPowerChannel_t enumeration
*/
virtual void setProtectedChannel(uint8_t channel);
/**
* @brief Unprotect the channel, call this to unprotect the channel lock
* @param channel: Parameters See XPowersPowerChannel_t enumeration
*/
virtual void setUnprotectChannel(uint8_t channel);
/**
* * @brief Get whether a channel power supply has been protected
* @param channel: Parameters See XPowersPowerChannel_t enumeration
* @retval true is set,false is not set
*/
virtual bool getProtectedChannel(uint8_t channel);
/**
* @brief Query whether the PMU input parameter channel is valid
* @param channel: Parameters See XPowersPowerChannel_t enumeration
* @retval true valid false invalid
*/
virtual bool isChannelAvailable(uint8_t channel);
virtual void setPrechargeCurr(uint8_t opt) = 0;
virtual void disableChargerTerminationLimit(void) = 0;
virtual bool setVbusVoltageLimit(uint8_t opt) = 0;
virtual uint8_t getVbusVoltageLimit(void) = 0;
virtual bool isStandby(void) = 0;
virtual bool isVbusGood(void) = 0;
virtual uint8_t getChargerStatus(void) = 0;
virtual void enableCellbatteryCharge(void) = 0;
virtual void enableGauge(void) = 0;
virtual void disableGauge(void) = 0;
virtual void setLinearChargerVsysDpm(uint8_t opt) = 0;
virtual void disablePwronShutPMIC(void) = 0;
virtual void fuelGaugeControl(bool writeROM, bool enable) = 0;
virtual void printIntRegister() = 0;
//battery
/**
* @brief Get battery Voltage
* @retval Voltage unit: millivolt , 0 is no battery is connected
*/
// virtual uint16_t getBattVoltage() = 0;
/**
* @brief Get battery percentage
* @retval 0~100% , -1 no battery is connected
*/
// virtual int getBatteryPercent(void);
// Vbus
/**
* @brief Get PMU VBUS/USB Voltage
* @retval Voltage unit: millivolt , 0 is no vbus is connected
*/
virtual uint16_t getVbusVoltage();
/**
* @brief Set VBUS Current Input Limit.
* @param opt: View the related chip type xpowers_axpxxx_vbus_cur_limit_t enumeration
* parameters in "XPowersParams.hpp"
* @retval true valid false invalid
*/
virtual bool setVbusCurrentLimit(uint8_t opt) = 0;
/**
* @brief Get VBUS Current Input Limit.
* @retval View the related chip type xpowers_axpxxx_vbus_cur_limit_t enumeration
* parameters in "XPowersParams.hpp"
*/
virtual uint8_t getVbusCurrentLimit(void) = 0;
// SYS
/**
* @brief Get PMU SYS main Voltage
* @retval Voltage unit: millivolt
*/
virtual uint16_t getSystemVoltage() = 0;
/**
* @brief Set PMU Low Voltage Shutdown Threshold
* @param millivolt: 2600mV ~ 3300mV
* @retval true valid false invalid
*/
virtual bool setSysPowerDownVoltage(uint16_t millivolt) = 0;
/**
* @brief Get PMU Low Voltage Shutdown Threshold
* @retval Voltage unit: millivolt
*/
virtual uint16_t getSysPowerDownVoltage() = 0;
/**
* @brief Set charge target voltage.
* @param opt: View the related chip type xpowers_axpxxx_chg_vol_t enumeration
* parameters in "XPowersParams.hpp"
* @retval true valid false invalid
*/
virtual bool setChargeTargetVoltage(uint8_t opt) = 0;
/**
* @brief Get charge target voltage.
* @retval View the related chip type xpowers_axpxxx_chg_vol_t enumeration
* parameters in "XPowersParams.hpp"
* parameters in "XPowersParams.hpp"
*/
virtual uint8_t getChargeTargetVoltage() = 0;
/**
* @brief Set charge current.
* @param opt: View the related chip type xpowers_axpxxx_chg_curr_t enumeration
* parameters in "XPowersParams.hpp"
* @retval true valid false invalid
*/
virtual bool setChargerConstantCurr(uint8_t opt) = 0;
/**
* @brief Get charge current.
* @retval View the related chip type xpowers_axpxxx_chg_curr_t enumeration
* parameters in "XPowersParams.hpp"
*/
virtual uint8_t getChargerConstantCurr() = 0;
//!PMU Interrupt control
/*
* Example of interrupt usage
* if (pmuInterrupt) {
* pmuInterrupt = false;
*
* Read interrupt status
* uint64_t mask = PMU->getIrqStatus();
* Serial.print("IRQ Mask:0b");
* Serial.println(mask,BIN);
*
* if (PMU->isPekeyShortPressIrq()) {
* Serial.println("isPekeyShortPressIrq");
* }
* if (PMU->isBatChagerStartIrq()) {
* Serial.println("isBatChagerStart");
* }
* ......
*
* After reading the interrupt status,you need to manually clear the status register
* PMU->clearIrqStatus();
* }
* * * */
/**
* @brief Get the interrupt controller mask value.
* @retval Mask value corresponds to xpowers_axpxxx_irq_t ,
*/
virtual uint64_t getIrqStatus() = 0;
/**
* @brief Clear interrupt controller state.
*/
virtual void clearIrqStatus() = 0;
/**
* @brief Eanble PMU interrupt control mask .
* @param opt: View the related chip type xpowers_axpxxx_irq_t enumeration
* parameters in "XPowersParams.hpp"
* @retval true valid false invalid
*/
virtual bool enableIRQ(uint64_t opt) = 0;
/**
* @brief Disable PMU interrupt control mask .
* @param opt: View the related chip type xpowers_axpxxx_irq_t enumeration
* parameters in "XPowersParams.hpp"
* @retval true valid false invalid
*/
virtual bool disableIRQ(uint64_t opt) = 0;
/**
* @brief .
* @param opt: View the related chip type xpowers_interrupt_enum_t enumeration
* parameters in "XPowersParams.hpp"
* @retval true valid false invalid
*/
bool enableInterrupt(uint32_t opt);
/**
* @brief .
* @param opt: View the related chip type xpowers_interrupt_enum_t enumeration
* parameters in "XPowersParams.hpp"
* @retval true valid false invalid
*/
bool disableInterrupt(uint32_t opt);
/**
* @brief .
* @param opt: View the related chip type xpowers_interrupt_enum_t enumeration
* parameters in "XPowersParams.hpp"
* @retval true valid false invalid
*/
bool setInterruptMask(uint32_t option, bool enable);
/**
* @brief Interrupt response when PMU PEKEY is short pressed
* @retval true valid false invalid
*/
virtual bool isPekeyShortPressIrq() = 0;
/**
* @brief Interrupt response when PMU PEKEY is long pressed
* @retval true valid false invalid
*/
virtual bool isPekeyLongPressIrq() = 0;
/**
* @brief Interrupt response when PMU battery is connected
* @retval true valid false invalid
*/
virtual bool isBatInsertIrq() = 0;
/**
* @brief Interrupt response when PMU battery is removed
* @retval true valid false invalid
*/
virtual bool isBatRemoveIrq() = 0;
/**
* @brief Interrupt response when PMU USB is plugged in
* @retval true valid false invalid
*/
virtual bool isVbusInsertIrq() = 0;
/**
* @brief Interrupt response when PMU USB is removed
* @retval true valid false invalid
*/
virtual bool isVbusRemoveIrq() = 0;
/**
* @brief Interrupt response when PMU charging is complete
* @retval true valid false invalid
*/
virtual bool isBatChagerDoneIrq() = 0;
/**
* @brief Interrupt response when PMU charging starts
* @retval true valid false invalid
*/
virtual bool isBatChagerStartIrq() = 0;
//Data collection function
/**
* @brief Enable battery detection function,the default is on
* @retval true success false failed
*/
virtual bool enableBattDetection() = 0;
/**
* @brief Disable battery detection
* @retval true success false failed
*/
virtual bool disableBattDetection() = 0;
/**
* @brief Enable USB input voltage detection
* @retval true success false failed
*/
virtual bool enableVbusVoltageMeasure(void) = 0;
/**
* @brief Disable USB input voltage detection
* @retval true success false failed
*/
virtual bool disableVbusVoltageMeasure(void) = 0;
/**
* @brief Enable system voltage detection
* @retval true success false failed
*/
virtual bool enableSystemVoltageMeasure(void) = 0;
/**
* @brief Disable system voltage detection
* @retval true success false failed
*/
virtual bool disableSystemVoltageMeasure(void) = 0;
/**
* @brief Enable PMU internal temperature sensor detection
* @retval true success false failed
*/
virtual bool enableTemperatureMeasure(void) = 0;
/**
* @brief Disable PMU internal temperature sensor detection
* @retval true success false failed
*/
virtual bool disableTemperatureMeasure(void) = 0;
/**
* @brief Enable battery input voltage detection
* @retval true success false failed
*/
virtual bool enableBattVoltageMeasure(void) = 0;
/**
* @brief Disable battery input voltage detection
* @retval true success false failed
*/
virtual bool disableBattVoltageMeasure(void) = 0;
/**
* @brief Enable NTC thermistor detection (requires hardware support)
* @retval true success false failed
*/
virtual bool enableTSPinMeasure(void) = 0;
/**
* @brief Disable NTC thermistor detection (requires hardware support)
* @retval true success false failed
*/
virtual bool disableTSPinMeasure(void) = 0;
// Charge indicator function
/**
* @brief Set charging led mode
* @param opt: View the related chip type xpowers_chg_led_mode_t enumeration
* parameters in "XPowersParams.hpp"
*/
virtual void setChargingLedMode(uint8_t mode) = 0;
virtual void setChargerTerminationCurr(uint8_t opt) = 0;
virtual void disableDieOverTempDetect(void) = 0;
virtual void resetGauge(void) = 0;
virtual void enableLongPressShutdown(void) = 0;
// PMU PEKEY settings
/**
* @brief Set PEKEY press power on time
* @param opt: View the related chip type xpowers_press_on_time_t enumeration
* parameters in "XPowersParams.hpp"
* @retval true success false failed
*/
virtual bool setPowerKeyPressOnTime(uint8_t opt) = 0;
/**
* @brief Get PEKEY press power on time
* @retval View the related chip type xpowers_press_on_time_t enumeration
* parameters in "XPowersParams.hpp"
*/
virtual uint8_t getPowerKeyPressOnTime() = 0;
/**
* @brief Set PEKEY press power off time
* @param opt: View the related chip type xpowers_press_off_time_t enumeration
* parameters in "XPowersParams.hpp"
* @retval true success false failed
*/
virtual bool setPowerKeyPressOffTime(uint8_t opt) = 0;
/**
* @brief Get PEKEY press power off time
* @retval View the related chip type xpowers_press_off_time_t enumeration
* parameters in "XPowersParams.hpp"
*/
virtual uint8_t getPowerKeyPressOffTime() = 0;
/**
* @brief Get the chip model
* @retval See XPowersChipModel_t enumeration
*/
uint8_t getChipModel()
{
return __chipModel;
}
protected:
void setChipModel(uint8_t m)
{
__chipModel = m;
}
uint8_t __chipModel;
uint32_t __protectedMask;
};

View File

@@ -0,0 +1,399 @@
/**
*
* @license MIT License
*
* Copyright (c) 2022 lewis he
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* @file XPowersParams.hpp
* @author Lewis He (lewishe@outlook.com)
* @date 2022-08-28
*
*/
#pragma once
#ifdef _BV
#undef _BV
#endif
#define _BV(b) (1ULL << (uint64_t)(b))
//TODO:Unified interface functions and parameters
/**
* @brief PMU PEKEY Press off time parameters.
*/
typedef enum __xpowers_press_off_time {
XPOWERS_POWEROFF_4S,
XPOWERS_POWEROFF_6S,
XPOWERS_POWEROFF_8S,
XPOWERS_POWEROFF_10S,
} xpowers_press_off_time_t;
/**
* @brief PMU PEKEY Press on time parameters.
*/
typedef enum __xpowers_press_on_time {
XPOWERS_POWERON_128MS,
XPOWERS_POWERON_512MS,
XPOWERS_POWERON_1S,
XPOWERS_POWERON_2S,
} xpowers_press_on_time_t;
/**
* @brief Charging led mode parameters.
*/
typedef enum __xpowers_chg_led_mode {
XPOWERS_CHG_LED_OFF,
XPOWERS_CHG_LED_BLINK_1HZ,
XPOWERS_CHG_LED_BLINK_4HZ,
XPOWERS_CHG_LED_ON,
XPOWERS_CHG_LED_CTRL_CHG, // The charging indicator is controlled by the charger
} xpowers_chg_led_mode_t;
/**
* @brief axp2101 charge target voltage parameters.
*/
typedef enum __xpowers_axp2101_chg_vol {
XPOWERS_AXP2101_CHG_VOL_4V = 1,
XPOWERS_AXP2101_CHG_VOL_4V1,
XPOWERS_AXP2101_CHG_VOL_4V2,
XPOWERS_AXP2101_CHG_VOL_4V35,
XPOWERS_AXP2101_CHG_VOL_4V4,
XPOWERS_AXP2101_CHG_VOL_MAX
} xpowers_axp2101_chg_vol_t;
/**
* @brief axp2101 charge currnet voltage parameters.
*/
typedef enum __xpowers_axp2101_chg_curr {
XPOWERS_AXP2101_CHG_CUR_0MA,
XPOWERS_AXP2101_CHG_CUR_100MA = 4,
XPOWERS_AXP2101_CHG_CUR_125MA,
XPOWERS_AXP2101_CHG_CUR_150MA,
XPOWERS_AXP2101_CHG_CUR_175MA,
XPOWERS_AXP2101_CHG_CUR_200MA,
XPOWERS_AXP2101_CHG_CUR_300MA,
XPOWERS_AXP2101_CHG_CUR_400MA,
XPOWERS_AXP2101_CHG_CUR_500MA,
XPOWERS_AXP2101_CHG_CUR_600MA,
XPOWERS_AXP2101_CHG_CUR_700MA,
XPOWERS_AXP2101_CHG_CUR_800MA,
XPOWERS_AXP2101_CHG_CUR_900MA,
XPOWERS_AXP2101_CHG_CUR_1000MA,
} xpowers_axp2101_chg_curr_t;
/**
* @brief axp192 charge target voltage parameters.
*/
typedef enum __xpowers_axp192_chg_vol {
XPOWERS_AXP192_CHG_VOL_4V1,
XPOWERS_AXP192_CHG_VOL_4V15,
XPOWERS_AXP192_CHG_VOL_4V2,
XPOWERS_AXP192_CHG_VOL_4V36,
XPOWERS_AXP192_CHG_VOL_MAX,
} xpowers_axp192_chg_vol_t;
/**
* @brief axp202 charge target voltage parameters.
*/
typedef enum __xpowers_axp202_chg_vol {
XPOWERS_AXP202_CHG_VOL_4V1,
XPOWERS_AXP202_CHG_VOL_4V15,
XPOWERS_AXP202_CHG_VOL_4V2,
XPOWERS_AXP202_CHG_VOL_4V36,
XPOWERS_AXP202_CHG_VOL_MAX,
} xpowers_axp202_chg_vol_t;
/**
* @brief axp192 charge currnet voltage parameters.
*/
typedef enum __xpowers_axp192_chg_curr {
XPOWERS_AXP192_CHG_CUR_100MA,
XPOWERS_AXP192_CHG_CUR_190MA,
XPOWERS_AXP192_CHG_CUR_280MA,
XPOWERS_AXP192_CHG_CUR_360MA,
XPOWERS_AXP192_CHG_CUR_450MA,
XPOWERS_AXP192_CHG_CUR_550MA,
XPOWERS_AXP192_CHG_CUR_630MA,
XPOWERS_AXP192_CHG_CUR_700MA,
XPOWERS_AXP192_CHG_CUR_780MA,
XPOWERS_AXP192_CHG_CUR_880MA,
XPOWERS_AXP192_CHG_CUR_960MA,
XPOWERS_AXP192_CHG_CUR_1000MA,
XPOWERS_AXP192_CHG_CUR_1080MA,
XPOWERS_AXP192_CHG_CUR_1160MA,
XPOWERS_AXP192_CHG_CUR_1240MA,
XPOWERS_AXP192_CHG_CUR_1320MA,
} xpowers_axp192_chg_curr_t;
/**
* @brief axp202 charge currnet voltage parameters.
*/
typedef enum __xpowers_axp202_chg_curr {
XPOWERS_AXP202_CHG_CUR_100MA,
XPOWERS_AXP202_CHG_CUR_190MA,
XPOWERS_AXP202_CHG_CUR_280MA,
XPOWERS_AXP202_CHG_CUR_360MA,
XPOWERS_AXP202_CHG_CUR_450MA,
XPOWERS_AXP202_CHG_CUR_550MA,
XPOWERS_AXP202_CHG_CUR_630MA,
XPOWERS_AXP202_CHG_CUR_700MA,
XPOWERS_AXP202_CHG_CUR_780MA,
XPOWERS_AXP202_CHG_CUR_880MA,
XPOWERS_AXP202_CHG_CUR_960MA,
XPOWERS_AXP202_CHG_CUR_1000MA,
XPOWERS_AXP202_CHG_CUR_1080MA,
XPOWERS_AXP202_CHG_CUR_1160MA,
XPOWERS_AXP202_CHG_CUR_1240MA,
XPOWERS_AXP202_CHG_CUR_1320MA,
} xpowers_axp202_chg_curr_t;
/**
* @brief axp2101 vbus currnet limit parameters.
*/
typedef enum {
XPOWERS_AXP2101_VBUS_CUR_LIM_100MA,
XPOWERS_AXP2101_VBUS_CUR_LIM_500MA,
XPOWERS_AXP2101_VBUS_CUR_LIM_900MA,
XPOWERS_AXP2101_VBUS_CUR_LIM_1000MA,
XPOWERS_AXP2101_VBUS_CUR_LIM_1500MA,
XPOWERS_AXP2101_VBUS_CUR_LIM_2000MA,
} xpowers_axp2101_vbus_cur_limit_t;
/**
* @brief axp192 vbus currnet limit parameters.
*/
typedef enum {
XPOWERS_AXP192_VBUS_CUR_LIM_500MA,
XPOWERS_AXP192_VBUS_CUR_LIM_100MA,
XPOWERS_AXP192_VBUS_CUR_LIM_OFF,
} xpowers_axp192_vbus_cur_limit_t;
/**
* @brief axp202 vbus currnet limit parameters.
*/
typedef enum {
XPOWERS_AXP202_VBUS_CUR_LIM_900MA,
XPOWERS_AXP202_VBUS_CUR_LIM_500MA,
XPOWERS_AXP202_VBUS_CUR_LIM_100MA,
XPOWERS_AXP202_VBUS_CUR_LIM_OFF,
} xpowers_axp202_vbus_cur_limit_t;
/**
* @brief XPowersLibInterface interrupt control mask parameters.
* Common interrupt interfaces
* @Example: enableInterrupt(XPOWERS_USB_INSERT_INT|XPOWERS_USB_REMOVE_INT);
* disableInterrupt(XPOWERS_CHARGE_START_INT|XPOWERS_PWR_BTN_CLICK_INT);
*/
typedef enum __xpowers_interrupt_enum {
XPOWERS_USB_INSERT_INT = _BV(0),
XPOWERS_USB_REMOVE_INT = _BV(1),
XPOWERS_BATTERY_INSERT_INT = _BV(2),
XPOWERS_BATTERY_REMOVE_INT = _BV(3),
XPOWERS_CHARGE_START_INT = _BV(4),
XPOWERS_CHARGE_DONE_INT = _BV(5),
XPOWERS_PWR_BTN_CLICK_INT = _BV(6),
XPOWERS_PWR_BTN_LONGPRESSED_INT = _BV(7),
XPOWERS_ALL_INT = _BV(8),
} xpowers_interrupt_enum_t;
/**
* @brief axp192 interrupt control mask parameters.
*/
typedef enum __xpowers_axp192_irq {
//! IRQ1 REG 40H
XPOWERS_AXP192_VBUS_VHOLD_LOW_IRQ = _BV(1), //VBUS is available, but lower than V HOLD, IRQ enable
XPOWERS_AXP192_VBUS_REMOVE_IRQ = _BV(2), //VBUS removed, IRQ enable
XPOWERS_AXP192_VBUS_INSERT_IRQ = _BV(3), //VBUS connected, IRQ enable
XPOWERS_AXP192_VBUS_OVER_VOL_IRQ = _BV(4), //VBUS over-voltage, IRQ enable
XPOWERS_AXP192_ACIN_REMOVED_IRQ = _BV(5), //ACIN removed, IRQ enable
XPOWERS_AXP192_ACIN_CONNECT_IRQ = _BV(6), //ACIN connected, IRQ enable
XPOWERS_AXP192_ACIN_OVER_VOL_IRQ = _BV(7), //ACIN over-voltage, IRQ enable
//! IRQ2 REG 41H
XPOWERS_AXP192_BATT_LOW_TEMP_IRQ = _BV(8), //Battery low-temperature, IRQ enable
XPOWERS_AXP192_BATT_OVER_TEMP_IRQ = _BV(9), //Battery over-temperature, IRQ enable
XPOWERS_AXP192_BAT_CHG_DONE_IRQ = _BV(10), //Charge finished, IRQ enable
XPOWERS_AXP192_BAT_CHG_START_IRQ = _BV(11), //Be charging, IRQ enable
XPOWERS_AXP192_BATT_EXIT_ACTIVATE_IRQ = _BV(12), //Exit battery activate mode, IRQ enable
XPOWERS_AXP192_BATT_ACTIVATE_IRQ = _BV(13), //Battery activate mode, IRQ enable
XPOWERS_AXP192_BAT_REMOVE_IRQ = _BV(14), //Battery removed, IRQ enable
XPOWERS_AXP192_BAT_INSERT_IRQ = _BV(15), //Battery connected, IRQ enable
//! IRQ3 REG 42H
XPOWERS_AXP192_PKEY_LONG_IRQ = _BV(16), //PEK long press, IRQ enable
XPOWERS_AXP192_PKEY_SHORT_IRQ = _BV(17), //PEK short press, IRQ enable
//**Reserved and unchangeable BIT 2
XPOWERS_AXP192_DC3_LOW_VOL_IRQ = _BV(19), //DC-DC3output voltage is lower than the set value, IRQ enable
XPOWERS_AXP192_DC2_LOW_VOL_IRQ = _BV(20), //DC-DC2 output voltage is lower than the set value, IRQ enable
XPOWERS_AXP192_DC1_LOW_VOL_IRQ = _BV(21), //DC-DC1 output voltage is lower than the set value, IRQ enable
XPOWERS_AXP192_CHARGE_LOW_CUR_IRQ = _BV(22), //Charge current is lower than the set current, IRQ enable
XPOWERS_AXP192_CHIP_TEMP_HIGH_IRQ = _BV(23), //XPOWERS internal over-temperature, IRQ enable
//! IRQ4 REG 43H
XPOWERS_AXP192_APS_LOW_VOL_LEVEL_IRQ = _BV(24), //APS low-voltage, IRQ enable
//**Reserved and unchangeable BIT 1
XPOWERS_AXP192_VBUS_SESSION_END_IRQ = _BV(26), //VBUS Session End IRQ enable
XPOWERS_AXP192_VBUS_SESSION_AB_IRQ = _BV(27), //VBUS Session A/B IRQ enable
XPOWERS_AXP192_VBUS_INVALID_IRQ = _BV(28), //VBUS invalid, IRQ enable
XPOWERS_AXP192_VBUS_VAILD_IRQ = _BV(29), //VBUS valid, IRQ enable
XPOWERS_AXP192_NOE_OFF_IRQ = _BV(30), //N_OE shutdown, IRQ enable
XPOWERS_AXP192_NOE_ON_IRQ = _BV(31), //N_OE startup, IRQ enable
//! IRQ5 REG 4AH
XPOWERS_AXP192_GPIO0_EDGE_TRIGGER_IRQ = _BV(32), //GPIO0 input edge trigger, IRQ enable
XPOWERS_AXP192_GPIO1_EDGE_TRIGGER_IRQ = _BV(33), //GPIO1input edge trigger or ADC input, IRQ enable
XPOWERS_AXP192_GPIO2_EDGE_TRIGGER_IRQ = _BV(34), //GPIO2input edge trigger, IRQ enable
//**Reserved and unchangeable BIT 3
//**Reserved and unchangeable BIT 4
//**Reserved and unchangeable BIT 5
//**Reserved and unchangeable BIT 6
XPOWERS_AXP192_TIMER_TIMEOUT_IRQ = _BV(39), //Timer timeout, IRQ enable
XPOWERS_AXP192_ALL_IRQ = (0xFFFFFFFFFFULL)
} xpowers_axp192_irq_t;
/**
* @brief axp2101 interrupt control mask parameters.
*/
typedef enum __xpowers_axp2101_irq {
//! IRQ1 REG 40H
XPOWERS_AXP2101_BAT_NOR_UNDER_TEMP_IRQ = _BV(0), // Battery Under Temperature in Work
XPOWERS_AXP2101_BAT_NOR_OVER_TEMP_IRQ = _BV(1), // Battery Over Temperature in Work mode
XPOWERS_AXP2101_BAT_CHG_UNDER_TEMP_IRQ = _BV(2), // Battery Under Temperature in Charge mode IRQ(bcut_irq)
XPOWERS_AXP2101_BAT_CHG_OVER_TEMP_IRQ = _BV(3), // Battery Over Temperature in Charge mode IRQ(bcot_irq) enable
XPOWERS_AXP2101_GAUGE_NEW_SOC_IRQ = _BV(4), // Gauge New SOC IRQ(lowsoc_irq) enable ???
XPOWERS_AXP2101_WDT_TIMEOUT_IRQ = _BV(5), // Gauge Watchdog Timeout IRQ(gwdt_irq) enable
XPOWERS_AXP2101_WARNING_LEVEL1_IRQ = _BV(6), // SOC drop to Warning Level1 IRQ(socwl1_irq) enable
XPOWERS_AXP2101_WARNING_LEVEL2_IRQ = _BV(7), // SOC drop to Warning Level2 IRQ(socwl2_irq) enable
//! IRQ2 REG 41H
XPOWERS_AXP2101_PKEY_POSITIVE_IRQ = _BV(8), // POWERON Positive Edge IRQ(ponpe_irq_en) enable
XPOWERS_AXP2101_PKEY_NEGATIVE_IRQ = _BV(9), // POWERON Negative Edge IRQ(ponne_irq_en) enable
XPOWERS_AXP2101_PKEY_LONG_IRQ = _BV(10), // POWERON Long PRESS IRQ(ponlp_irq) enable
XPOWERS_AXP2101_PKEY_SHORT_IRQ = _BV(11), // POWERON Short PRESS IRQ(ponsp_irq_en) enable
XPOWERS_AXP2101_BAT_REMOVE_IRQ = _BV(12), // Battery Remove IRQ(bremove_irq) enable
XPOWERS_AXP2101_BAT_INSERT_IRQ = _BV(13), // Battery Insert IRQ(binsert_irq) enabl
XPOWERS_AXP2101_VBUS_REMOVE_IRQ = _BV(14), // VBUS Remove IRQ(vremove_irq) enabl
XPOWERS_AXP2101_VBUS_INSERT_IRQ = _BV(15), // VBUS Insert IRQ(vinsert_irq) enable
//! IRQ3 REG 42H
XPOWERS_AXP2101_BAT_OVER_VOL_IRQ = _BV(16), // Battery Over Voltage Protection IRQ(bovp_irq) enable
XPOWERS_AXP2101_CHAGER_TIMER_IRQ = _BV(17), // Charger Safety Timer1/2 expire IRQ(chgte_irq) enable
XPOWERS_AXP2101_DIE_OVER_TEMP_IRQ = _BV(18), // DIE Over Temperature level1 IRQ(dotl1_irq) enable
XPOWERS_AXP2101_BAT_CHG_START_IRQ = _BV(19), // Charger start IRQ(chgst_irq) enable
XPOWERS_AXP2101_BAT_CHG_DONE_IRQ = _BV(20), // Battery charge done IRQ(chgdn_irq) enable
XPOWERS_AXP2101_BATFET_OVER_CURR_IRQ = _BV(21), // BATFET Over Current Protection IRQ(bocp_irq) enable
XPOWERS_AXP2101_LDO_OVER_CURR_IRQ = _BV(22), // LDO Over Current IRQ(ldooc_irq) enable
XPOWERS_AXP2101_WDT_EXPIRE_IRQ = _BV(23), // Watchdog Expire IRQ(wdexp_irq) enable
XPOWERS_AXP2101_ALL_IRQ = (0xFFFFFFFFUL)
} xpowers_axp2101_irq_t;
/**
* @brief axp202 interrupt control mask parameters.
*/
typedef enum __xpowers_axp202_irq {
//! IRQ1 REG 40H
XPOWERS_AXP202_VBUS_VHOLD_LOW_IRQ = _BV(1), //VBUS is available, but lower than V HOLD, IRQ enable
XPOWERS_AXP202_VBUS_REMOVE_IRQ = _BV(2), //VBUS removed, IRQ enable
XPOWERS_AXP202_VBUS_INSERT_IRQ = _BV(3), //VBUS connected, IRQ enable
XPOWERS_AXP202_VBUS_OVER_VOL_IRQ = _BV(4), //VBUS over-voltage, IRQ enable
XPOWERS_AXP202_ACIN_REMOVED_IRQ = _BV(5), //ACIN removed, IRQ enable
XPOWERS_AXP202_ACIN_CONNECT_IRQ = _BV(6), //ACIN connected, IRQ enable
XPOWERS_AXP202_ACIN_OVER_VOL_IRQ = _BV(7), //ACIN over-voltage, IRQ enable
//! IRQ2 REG 41H
XPOWERS_AXP202_BATT_LOW_TEMP_IRQ = _BV(8), //Battery low-temperature, IRQ enable
XPOWERS_AXP202_BATT_OVER_TEMP_IRQ = _BV(9), //Battery over-temperature, IRQ enable
XPOWERS_AXP202_BAT_CHG_DONE_IRQ = _BV(10), //Charge finished, IRQ enable
XPOWERS_AXP202_BAT_CHG_START_IRQ = _BV(11), //Be charging, IRQ enable
XPOWERS_AXP202_BATT_EXIT_ACTIVATE_IRQ = _BV(12), //Exit battery activate mode, IRQ enable
XPOWERS_AXP202_BATT_ACTIVATE_IRQ = _BV(13), //Battery activate mode, IRQ enable
XPOWERS_AXP202_BAT_REMOVE_IRQ = _BV(14), //Battery removed, IRQ enable
XPOWERS_AXP202_BAT_INSERT_IRQ = _BV(15), //Battery connected, IRQ enable
//! IRQ3 REG 42H
XPOWERS_AXP202_PKEY_LONG_IRQ = _BV(16), //PEK long press, IRQ enable
XPOWERS_AXP202_PKEY_SHORT_IRQ = _BV(17), //PEK short press, IRQ enable
XPOWERS_AXP202_LDO3_LOW_VOL_IRQ = _BV(18), //LDO3output voltage is lower than the set value, IRQ enable
XPOWERS_AXP202_DC3_LOW_VOL_IRQ = _BV(19), //DC-DC3output voltage is lower than the set value, IRQ enable
XPOWERS_AXP202_DC2_LOW_VOL_IRQ = _BV(20), //DC-DC2 output voltage is lower than the set value, IRQ enable
//**Reserved and unchangeable BIT 5
XPOWERS_AXP202_CHARGE_LOW_CUR_IRQ = _BV(22), //Charge current is lower than the set current, IRQ enable
XPOWERS_AXP202_CHIP_TEMP_HIGH_IRQ = _BV(23), //AXP202 internal over-temperature, IRQ enable
//! IRQ4 REG 43H
XPOWERS_AXP202_APS_LOW_VOL_LEVEL2_IRQ = _BV(24), //APS low-voltage, IRQ enableLEVEL2
XPOWERS_APX202_APS_LOW_VOL_LEVEL1_IRQ = _BV(25), //APS low-voltage, IRQ enableLEVEL1
XPOWERS_AXP202_VBUS_SESSION_END_IRQ = _BV(26), //VBUS Session End IRQ enable
XPOWERS_AXP202_VBUS_SESSION_AB_IRQ = _BV(27), //VBUS Session A/B IRQ enable
XPOWERS_AXP202_VBUS_INVALID_IRQ = _BV(28), //VBUS invalid, IRQ enable
XPOWERS_AXP202_VBUS_VAILD_IRQ = _BV(29), //VBUS valid, IRQ enable
XPOWERS_AXP202_NOE_OFF_IRQ = _BV(30), //N_OE shutdown, IRQ enable
XPOWERS_AXP202_NOE_ON_IRQ = _BV(31), //N_OE startup, IRQ enable
//! IRQ5 REG 44H
XPOWERS_AXP202_GPIO0_EDGE_TRIGGER_IRQ = _BV(32), //GPIO0 input edge trigger, IRQ enable
XPOWERS_AXP202_GPIO1_EDGE_TRIGGER_IRQ = _BV(33), //GPIO1input edge trigger or ADC input, IRQ enable
XPOWERS_AXP202_GPIO2_EDGE_TRIGGER_IRQ = _BV(34), //GPIO2input edge trigger, IRQ enable
XPOWERS_AXP202_GPIO3_EDGE_TRIGGER_IRQ = _BV(35), //GPIO3 input edge trigger, IRQ enable
//**Reserved and unchangeable BIT 4
XPOWERS_AXP202_PKEY_NEGATIVE_IRQ = _BV(37), //PEK press falling edge, IRQ enable
XPOWERS_AXP202_PKEY_POSITIVE_IRQ = _BV(38), //PEK press rising edge, IRQ enable
XPOWERS_AXP202_TIMER_TIMEOUT_IRQ = _BV(39), //Timer timeout, IRQ enable
XPOWERS_AXP202_ALL_IRQ = (0xFFFFFFFFFFULL)
} xpowers_axp202_irq_t;

View File

@@ -0,0 +1,3 @@
#pragma once

View File

@@ -0,0 +1,326 @@
#include "main.h"
#include <stdlib.h>
#include <errno.h>
#include <stdint.h>
#include <fcntl.h>
#include <linux/i2c-dev.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <poll.h>
#include <iostream>
#include <string>
#include "XPowersLib.h"
#define I2C_BUS (4)
#define AXP2101_SLAVE_ADDRESS (0x34)
#define APP_VERSION "1.1.0"
int i2c_dev = -1;
XPowersLibInterface *PMU = NULL;
static int linux_i2c_read_callback(uint8_t devAddr, uint8_t regAddr, uint8_t *data, uint8_t len);
static int linux_i2c_write_callback(uint8_t devAddr, uint8_t regAddr, uint8_t *data, uint8_t len);
static void printPMU();
static int open_i2c_bus(int bus)
{
char filename[20];
snprintf(filename, 19, "/dev/i2c-%d", bus);
int file = open(filename, O_RDWR);
if (file < 0) {
perror("PMU: Failed to open the i2c bus");
}
return file;
}
static int set_i2c_slave(int file, int addr)
{
if (ioctl(file, I2C_SLAVE, addr) < 0) {
perror("PMU: Failed to acquire bus access and/or talk to slave");
return -1;
}
return 0;
}
int main(int argc, char* argv[])
{
bool log_enabled = false;
bool version_enabled = false;
printf("PMU: Init axp2101 pmu\n");
i2c_dev = open_i2c_bus(I2C_BUS);
if (i2c_dev < 0) {
printf("PMU: Open i2c bus error\n");
return -1;
} else {
printf("PMU: Open i2c bus success\n");
}
if (set_i2c_slave(i2c_dev, AXP2101_SLAVE_ADDRESS) < 0) {
close(i2c_dev);
printf("PMU: Set i2c slave error\n");
return 1;
} else {
printf("PMU: Set i2c slave success\n");
}
if (!PMU) {
if (ioctl(i2c_dev, I2C_SLAVE, AXP2101_SLAVE_ADDRESS) < 0) {
printf("PMU: Failed to access bus.\n");
exit(1);
}
PMU = new XPowersAXP2101(AXP2101_SLAVE_ADDRESS, linux_i2c_read_callback, linux_i2c_write_callback);
if (!PMU->init()) {
printf("PMU: Failed to find AXP2101 power management\n");
delete PMU;
PMU = NULL;
} else {
printf("PMU: AXP2101 PMU init succeeded, using AXP2101 PMU\n");
}
}
for (int i = 1; i < argc; ++i) {
std::string arg = argv[i];
if (arg == "--log" || arg == "-l") {
log_enabled = true;
} else if (arg == "--version" || arg == "-v") {
version_enabled = true;
}
break;
}
if (version_enabled) {
std::cout << "version: " << APP_VERSION << std::endl;
if (PMU != nullptr) {
delete PMU;
PMU = NULL;
}
return 0;
}
if (log_enabled) {
std::cout << "=======================================================================\n";
if (PMU->isChannelAvailable(XPOWERS_DCDC1)) {
std::cout << "DC1 : " << (PMU->isPowerChannelEnable(XPOWERS_DCDC1) ? "+" : "-")
<< " Voltage:" << PMU->getPowerChannelVoltage(XPOWERS_DCDC1) << " mV \n";
}
if (PMU->isChannelAvailable(XPOWERS_DCDC2)) {
std::cout << "DC2 : " << (PMU->isPowerChannelEnable(XPOWERS_DCDC2) ? "+" : "-")
<< " Voltage:" << PMU->getPowerChannelVoltage(XPOWERS_DCDC2) << " mV \n";
}
if (PMU->isChannelAvailable(XPOWERS_DCDC3)) {
std::cout << "DC3 : " << (PMU->isPowerChannelEnable(XPOWERS_DCDC3) ? "+" : "-")
<< " Voltage:" << PMU->getPowerChannelVoltage(XPOWERS_DCDC3) << " mV \n";
}
if (PMU->isChannelAvailable(XPOWERS_DCDC4)) {
std::cout << "DC4 : " << (PMU->isPowerChannelEnable(XPOWERS_DCDC4) ? "+" : "-")
<< " Voltage:" << PMU->getPowerChannelVoltage(XPOWERS_DCDC4) << " mV \n";
}
if (PMU->isChannelAvailable(XPOWERS_DCDC5)) {
std::cout << "DC5 : " << (PMU->isPowerChannelEnable(XPOWERS_DCDC5) ? "+" : "-")
<< " Voltage:" << PMU->getPowerChannelVoltage(XPOWERS_DCDC5) << " mV \n";
}
if (PMU->isChannelAvailable(XPOWERS_ALDO1)) {
std::cout << "ALDO1: " << (PMU->isPowerChannelEnable(XPOWERS_ALDO1) ? "+" : "-")
<< " Voltage:" << PMU->getPowerChannelVoltage(XPOWERS_ALDO1) << " mV \n";
}
if (PMU->isChannelAvailable(XPOWERS_ALDO2)) {
std::cout << "ALDO2: " << (PMU->isPowerChannelEnable(XPOWERS_ALDO2) ? "+" : "-")
<< " Voltage:" << PMU->getPowerChannelVoltage(XPOWERS_ALDO2) << " mV \n";
}
if (PMU->isChannelAvailable(XPOWERS_ALDO3)) {
std::cout << "ALDO3: " << (PMU->isPowerChannelEnable(XPOWERS_ALDO3) ? "+" : "-")
<< " Voltage:" << PMU->getPowerChannelVoltage(XPOWERS_ALDO3) << " mV \n";
}
if (PMU->isChannelAvailable(XPOWERS_ALDO4)) {
std::cout << "ALDO4: " << (PMU->isPowerChannelEnable(XPOWERS_ALDO4) ? "+" : "-")
<< " Voltage:" << PMU->getPowerChannelVoltage(XPOWERS_ALDO4) << " mV \n";
}
if (PMU->isChannelAvailable(XPOWERS_BLDO1)) {
std::cout << "BLDO1: " << (PMU->isPowerChannelEnable(XPOWERS_BLDO1) ? "+" : "-")
<< " Voltage:" << PMU->getPowerChannelVoltage(XPOWERS_BLDO1) << " mV \n";
}
if (PMU->isChannelAvailable(XPOWERS_BLDO2)) {
std::cout << "BLDO2: " << (PMU->isPowerChannelEnable(XPOWERS_BLDO2) ? "+" : "-")
<< " Voltage:" << PMU->getPowerChannelVoltage(XPOWERS_BLDO2) << " mV \n";
}
if (PMU->isChannelAvailable(XPOWERS_DLDO1)) {
std::cout << "DLDO1: " << (PMU->isPowerChannelEnable(XPOWERS_DLDO1) ? "+" : "-")
<< " Voltage:" << PMU->getPowerChannelVoltage(XPOWERS_DLDO1) << " mV \n";
}
if (PMU->isChannelAvailable(XPOWERS_DLDO2)) {
std::cout << "DLDO2: " << (PMU->isPowerChannelEnable(XPOWERS_DLDO2) ? "+" : "-")
<< " Voltage:" << PMU->getPowerChannelVoltage(XPOWERS_DLDO2) << " mV \n";
}
if (PMU->isChannelAvailable(XPOWERS_CPULDO)) {
std::cout << "CPUSLDO: " << (PMU->isPowerChannelEnable(XPOWERS_CPULDO) ? "+" : "-")
<< " Voltage:" << PMU->getPowerChannelVoltage(XPOWERS_CPULDO) << " mV \n";
}
if (PMU->isChannelAvailable(XPOWERS_VBACKUP)) {
std::cout << "VBACKUP: " << (PMU->isPowerChannelEnable(XPOWERS_VBACKUP) ? "+" : "-")
<< " Voltage:" << PMU->getPowerChannelVoltage(XPOWERS_VBACKUP) << " mV \n";
}
std::cout << "=======================================================================\n";
printPMU();
if (PMU != nullptr) {
delete PMU;
PMU = NULL;
}
return 0;
}
PMU->setVbusVoltageLimit(XPOWERS_AXP2101_VBUS_VOL_LIM_3V88);
PMU->setVbusCurrentLimit(XPOWERS_AXP2101_VBUS_CUR_LIM_2000MA);
PMU->setSysPowerDownVoltage(2600);
// DCDC1 --> VDD3V3_SYS
PMU->setPowerChannelVoltage(XPOWERS_DCDC1, 3300);
PMU->enablePowerOutput(XPOWERS_DCDC1);
// DCDC2 --> Disable
PMU->disablePowerOutput(XPOWERS_DCDC2);
// DCDC3 --> VDD0V9_CPU
PMU->setPowerChannelVoltage(XPOWERS_DCDC3, 1000);
PMU->enablePowerOutput(XPOWERS_DCDC3);
// DCDC4 --> VDD1V35_DRAM
PMU->setPowerChannelVoltage(XPOWERS_DCDC4, 1400);
PMU->enablePowerOutput(XPOWERS_DCDC4);
// DCDC5 --> Disable
PMU->disablePowerOutput(XPOWERS_DCDC5);
// ALDO1 --> VDD1V8_SYS
PMU->setPowerChannelVoltage(XPOWERS_ALDO1, 1800);
PMU->enablePowerOutput(XPOWERS_ALDO1);
// ALDO2 ~ ALDO4 --> Disable
PMU->disablePowerOutput(XPOWERS_ALDO2);
PMU->disablePowerOutput(XPOWERS_ALDO3);
PMU->disablePowerOutput(XPOWERS_ALDO4);
// BLDO1 ~ BLDO2 --> Disable
PMU->disablePowerOutput(XPOWERS_BLDO1);
PMU->disablePowerOutput(XPOWERS_BLDO2);
// DLDO1 ~ DLDO2 --> Disable
PMU->disablePowerOutput(XPOWERS_DLDO1);
PMU->disablePowerOutput(XPOWERS_DLDO2);
// CPUSLDO --> Disable
PMU->disablePowerOutput(XPOWERS_CPULDO);
// VBACKUP
PMU->setPowerChannelVoltage(XPOWERS_VBACKUP, 3100);
PMU->enablePowerOutput(XPOWERS_VBACKUP);
PMU->disableIRQ(XPOWERS_AXP2101_ALL_IRQ);
PMU->clearIrqStatus();
PMU->setLinearChargerVsysDpm(XPOWERS_AXP2101_VSYS_VOL_4V8);
PMU->setPrechargeCurr(XPOWERS_AXP2101_PRECHARGE_200MA);
PMU->setChargerConstantCurr(XPOWERS_AXP2101_CHG_CUR_1000MA);
PMU->setChargeTargetVoltage(XPOWERS_AXP2101_CHG_VOL_4V2);
PMU->disableChargerTerminationLimit();
PMU->setChargingLedMode(XPOWERS_CHG_LED_OFF);
PMU->enableCellbatteryCharge();
// Set the time of pressing the button to turn off
PMU->setPowerKeyPressOffTime(XPOWERS_POWEROFF_4S);
// Set the button power-on press time
PMU->setPowerKeyPressOnTime(XPOWERS_POWERON_128MS);
PMU->enableLongPressShutdown();
PMU->enableIRQ(XPOWERS_AXP2101_PKEY_POSITIVE_IRQ);
PMU->enableIRQ(XPOWERS_AXP2101_PKEY_NEGATIVE_IRQ);
PMU->disableTSPinMeasure();
PMU->enableVbusVoltageMeasure();
PMU->enableBattVoltageMeasure();
PMU->enableSystemVoltageMeasure();
PMU->enableBattDetection();
PMU -> fuelGaugeControl(true, true);
if (PMU != nullptr) {
delete PMU;
PMU = NULL;
}
return 0;
}
static int linux_i2c_read_callback(uint8_t devAddr, uint8_t regAddr, uint8_t *data, uint8_t len)
{
if (write(i2c_dev, &regAddr, 1) != 1) {
perror("Failed to write to the i2c device");
close(i2c_dev);
return -1;
}
if (read(i2c_dev, data, len) != len) {
perror("Failed to read from the i2c device");
close(i2c_dev);
return -1;
}
return 0;
}
static int linux_i2c_write_callback(uint8_t devAddr, uint8_t regAddr, uint8_t *data, uint8_t len)
{
uint8_t buffer[len + 1];
buffer[0] = regAddr;
for (int i = 0; i < len; i++) {
buffer[i + 1] = data[i];
}
if (write(i2c_dev, buffer, len + 1) != len + 1) {
perror("Failed to write to the i2c device");
close(i2c_dev);
return -1;
}
return 0;
}
void printPMU() {
std::cout << "---------------------------------------------------------------------------------------------------------\n";
std::cout << "CHARG DISC STBY VBUSIN VGOOD VBAT VBUS VSYS Percentage CHG_STATUS\n";
std::cout << "(bool) (bool) (bool) (bool) (bool) (mV) (mV) (mV) (%%) (str) \n";
std::cout << "---------------------------------------------------------------------------------------------------------\n";
std::cout << (PMU->isCharging() ? "YES" : "NO ") << "\t";
std::cout << (PMU->isDischarge() ? "YES" : "NO ") << "\t";
std::cout << (PMU->isStandby() ? "YES" : "NO ") << "\t";
std::cout << (PMU->isVbusIn() ? "YES" : "NO ") << "\t";
std::cout << (PMU->isVbusGood() ? "YES" : "NO ") << "\t";
std::cout << PMU->getBattVoltage() << "\t";
std::cout << PMU->getVbusVoltage() << "\t";
std::cout << PMU->getSystemVoltage() << "\t";
std::cout << PMU->getBatteryPercent() << "%\t";
uint8_t charge_status = PMU->getChargerStatus();
if (charge_status == XPOWERS_AXP2101_CHG_TRI_STATE) {
std::cout << "tri_charge";
} else if (charge_status == XPOWERS_AXP2101_CHG_PRE_STATE) {
std::cout << "pre_charge";
} else if (charge_status == XPOWERS_AXP2101_CHG_CC_STATE) {
std::cout << "constant charge(CC)";
} else if (charge_status == XPOWERS_AXP2101_CHG_CV_STATE) {
std::cout << "constant voltage(CV)";
} else if (charge_status == XPOWERS_AXP2101_CHG_DONE_STATE) {
std::cout << "charge done";
} else if (charge_status == XPOWERS_AXP2101_CHG_STOP_STATE) {
std::cout << "not charging";
}
std::cout << "\n";
}

View File

@@ -719,7 +719,7 @@ CONFIG_VOLUMEID=y
# CONFIG_FEATURE_VOLUMEID_BTRFS is not set
# CONFIG_FEATURE_VOLUMEID_CRAMFS is not set
CONFIG_FEATURE_VOLUMEID_EROFS=y
# CONFIG_FEATURE_VOLUMEID_EXFAT is not set
CONFIG_FEATURE_VOLUMEID_EXFAT
# CONFIG_FEATURE_VOLUMEID_EXT is not set
# CONFIG_FEATURE_VOLUMEID_F2FS is not set
# CONFIG_FEATURE_VOLUMEID_FAT is not set

View File

@@ -4,7 +4,7 @@
#
################################################################################
LCDTEST_VERSION = 9dc8793ff0a6cdc973cf823af6447a79a4da6cac
LCDTEST_VERSION = d6defe34015d64b70963e16ee0e1d274387ec060
LCDTEST_SITE = $(call github,0x754C,lcdtest,$(LCDTEST_VERSION))
define LCDTEST_BUILD_CMDS

View File

@@ -1,3 +1,3 @@
# Locally calculated
sha256 62f650467a60a38794d681ae7e66e3e8cfba38f445e0bf87867e2f2cdc8be9d5 opencv4-4.8.1.tar.gz
sha256 ddf76f9dffd322c7c3cb1f721d0887f62d747b82059342213138dc190f28bc6c opencv4-4.9.0.tar.gz
sha256 cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30 LICENSE

View File

@@ -4,7 +4,7 @@
#
################################################################################
OPENCV4_VERSION = 4.8.1
OPENCV4_VERSION = 4.9.0
OPENCV4_SITE = $(call github,opencv,opencv,$(OPENCV4_VERSION))
OPENCV4_INSTALL_STAGING = YES
OPENCV4_LICENSE = Apache-2.0
@@ -44,6 +44,12 @@ ifeq ($(BR2_PACKAGE_OPENCV4_BUILD_TESTS)$(BR2_PACKAGE_OPENCV4_BUILD_PERF_TESTS),
OPENCV4_CONF_OPTS += -DINSTALL_TEST=OFF
else
OPENCV4_CONF_OPTS += -DINSTALL_TEST=ON
define OPENCV4_INSTALL_TESTBIN
ls $(@D)/buildroot-build/bin
mkdir -pv $(TARGET_DIR)/usr/bin/
cp -vf $(@D)/buildroot-build/bin/* $(TARGET_DIR)/usr/bin/
endef
OPENCV4_POST_INSTALL_TARGET_HOOKS += OPENCV4_INSTALL_TESTBIN
endif
# OpenCV build options

View File

@@ -4,7 +4,7 @@
#
################################################################################
TPUDEMO_SG200X_VERSION = 345541b2f2a30e4efaa7505aa3b911826ec78505
TPUDEMO_SG200X_VERSION = e50c97cbfc3f6018d674883a6a60bccd63bbf01d
TPUDEMO_SG200X_SITE = $(call github,0x754C,tpudemo-sg200x,$(TPUDEMO_SG200X_VERSION))
define TPUDEMO_SG200X_INSTALL_TARGET_CMDS

View File

@@ -25,6 +25,7 @@ class TestBmapTools(BRTest):
BR2_PACKAGE_UTIL_LINUX=y
BR2_PACKAGE_UTIL_LINUX_FALLOCATE=y
BR2_PACKAGE_E2FSPROGS=y
BR2_PACKAGE_EXFATPROGS=y
BR2_PACKAGE_UTIL_LINUX_LIBUUID=y
""".format(infra.filepath(copy_script),
infra.filepath(sample_script))

21
demo/tioccons.c Normal file
View File

@@ -0,0 +1,21 @@
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <fcntl.h>
int main(int argc, char *argv[]) {
int fd;
if (argc < 2) {
fprintf(stderr, "usage: %s /dev/ttyX\n", argv[0]);
exit(EXIT_FAILURE);
}
fd = open(argv[1], O_RDWR);
if (fd < 0) {
perror("open");
exit(EXIT_FAILURE);
}
ioctl(fd, TIOCCONS);
close(fd);
exit(EXIT_SUCCESS);
}

View File

@@ -1,5 +1,3 @@
# SPDX-License-Identifier: BSD-3-Clause
.PHONY: FORCE
# Default goal is build all images
.DEFAULT_GOAL := all

View File

@@ -1,5 +1,3 @@
/* SPDX-License-Identifier: BSD-3-Clause */
#ifndef __BL2_HELPER_H__
#define __BL2_HELPER_H__

View File

@@ -1,5 +1,3 @@
/* SPDX-License-Identifier: BSD-3-Clause */
#ifndef __CPU_HELP_H__
#define __CPU_HELP_H__

View File

@@ -1,5 +1,3 @@
/* SPDX-License-Identifier: BSD-3-Clause */
#ifndef __CPU_H__
#define __CPU_H__

View File

@@ -1,8 +1,6 @@
/* SPDX-License-Identifier: BSD-3-Clause */
#ifndef __ARCH_HELPERS_H__
#define __ARCH_HELPERS_H__
//#include <cpu.h> /* for additional register definitions */
#include <cdefs.h> /* For __dead2 */
#include <stdint.h>
#include <sys/types.h>

View File

@@ -1,5 +1,3 @@
/* SPDX-License-Identifier: BSD-3-Clause */
#ifndef __CPU_HELP_H__
#define __CPU_HELP_H__

View File

@@ -1,110 +1,110 @@
# CHANGE LOG FOR BIGDIGITS
## Changes in Version 2.6
_Version 2.6.1 (Released 31 March 2016)_
* Added new functions to perform modular arithmetic operations, particularly useful for doing computations in a prime field for elliptic curves:
* `mpModSquare`, `bdModSquare` to compute `a = x^2 (mod m)`
* `mpModSqrt`, `bdModSqrt` to compute a square root modulo a prime p
* `mpModHalve`, `bdModHalve` to compute `a = x / 2 (mod p)`
* `mpModAdd`, `bdModAdd` and `mpModSub`, `bdModSub` to compute `w = u <20> v (mod m)` quickly for u and v in the range `[0, m-1]`.
* The function `mpModSpecial` to compute `u = v (mod m)` in the special case where v is known to be in the range `[0, km]` for k a small integer. This is faster than `mpModulo`.
* Added functions `mpToShort`, `bdToShort` to convert a multiprecision integer to a single digit.
* Added functions `mpShortIsEqual`, `bdmpShortIsEqual` to check if a multiprecision integer is equal to a single digit.
* Added the explicit constant-time comparison functions.
* `mpEqual_ct()`, `bdIsEqual_ct()`
* `mpIsZero_ct()`, `bdIsZero_ct()`
* `mpCompare_ct()`, `bdCompare_ct()`
* Reversed the change in v2.5 to make the comparison functions constant-time by default. The original comparison functions are now _not_ constant-time, as they were before v2.5\. The user must explicitly select the constant-time variant (ending **_ct**). To summarize: the functions `mpEqual`, `bdIsEqual`, `mpIsZero`, `bdIsZero`, `mpCompare` and `bdCompare` are _not_ constant-time in v2.6.
> _Comment:_ We realised after we made the change in v2.5 that the majority of comparison operations in our own code were simple checks for special cases and were not comparing secret values, so they did not need the more expensive constant-time operations. There were only a few occasions where we did comparisons on secret values and these were easily found and explicitly changed to do a constant-time comparison. So, sorry, we shouldn't have changed the default behaviour in v2.5\. It's back now to how it was before.
* Added the functions `mpCompileTime`, `bdCompileTime` to show the time and date of compilation.
* Added the function `mpPrintBits` to print the value in 0/1 bit format.
* Added the option to specify the global preprocessor definition, say, `MAX_FIXED_BIT_LENGTH=640` when using the `NO_ALLOCS` option for the "mp" functions. This allows you to change the maximum fixed length of arrays without editing the core source code.
* Increased the size of the fixed-length buffers in the `mpPrint*()` functions to avoid buffer overflows
* Fixed an issue with the `mpPrint*()` functions when displaying zero values.
* Added the `bdNewVars` and `bdFreeVars` functions to allow "bulk" creation and destruction of "bd" variables in a single line of code.
## Changes in Version 2.5
_Version 2.5 (Released 22 October 2015)_
* Changed license conditions to Mozilla Public License, v. 2.0.
* Fixed `bdShortMult` to catch empty `u` parameter.
* Fixed `bdPrintBits` to print "0" if bit length is zero.
* Changed comparison functions to be constant-time by default. Retained the old, quicker functions as `_q` variants.
* `mpEqual` `bdIsEqual` `mpEqual_q` `bdIsEqual_q`
* `mpIsZero` `bdIsZero` `mpIsZero_q` `bdIsZero_q`
* `mpCompare` `bdCompare` `mpCompare_q` `bdCompare_q`
* Added constant-time modular exponentiation functions `bdModExp_ct` and `mpModExp_ct`.
* Added `mpPrintDecimalSigned` function to display negative numbers ("**mp**" only).
## Changes in Version 2.4
_Version 2.4 (Released 27 April 2013)_
* Added markup for Doxygen documentation to produce a manual in CHM and HTML formats.
* Updated the "pretty-good" internal RNG functions in `bigdRand` and `bigdigitsRand` to improve the seeding of the ANSI X9.31 PRNG algorithm.
* Fixed the `NO_ALLOCS` option so it does not use malloc with the `mpConv` functions (thanks to Kevin Kramb for pointing this out).
* Added the new functions `bdRandomOctets`, `bdRandomNumber` and `bdQuickRandBits`, which do various contortions you might want to do with random numbers.
* Updated the test source code modules.
## Changes in Version 2.3
_Version 2.3 (Released 11 November 2011)_
* Added new functions to compute the integer cube root: `bdCubeRoot` and `mpCubeRoot`.
* Updated and improved the integer square root functions: `bdSqrt` and `mpSqrt`.
* Added the more useful print functions with an optional prefix and suffix:
* `bdPrintHex` prints a bigdigit number in hex format.
* `bdPrintDecimal` prints a bigdigit number in decimal format.and the equivalent mp functions `mpPrintHex` and `mpPrintDecimal`.
* Added the new function `bdPower` to compute the n-th power of a number `y = g^n`. Use this with caution as you can quickly run out of memory. It's meant for small exponents like n=3.
* Improved the efficiency of the greatest common divisor functions, `bdGcd` and `mpGcd`.
* Fixed the bug in `mpChs` (thanks to Valery Blazhnov).
* Fixed the bug in `mpAlloc` which would fail if you called `bdSetDigit(b, 0)` (thanks to "Radistao").
## Changes in Version 2.2
_Version 2.2 (Released 31 July 2008)_
* Added sliding-window exponentiation to speed up the ModExp functions.
* Added new bd functions:
* `bdJacobi` computes the Jacobi (Legendre) symbol.
* `bdGetBit` returns the value of a bit at a given position in a number.
* `bdSetBit` sets the bit at a given position in a number.
* `bdNotBits` computes bitwise a = NOT a.
* Added the new functions `mpIsNegative`, `mpChs` and `mpAbs` in anticipation of adding full signed integer functionality in a later version.
* Added the `NO_ALLOCS` option to compile the "mp" library without using any memory allocation.
* Added the `USE_64WITH32` option to use the 64-bit integer types (`long long`) if available on a 32-bit machine.
* Improved the zeroisation and destroy macros.
* Moved the type declarations for the exact-width types to a separate include file.
* Re-organised and re-named the ancillary source and include files (yet again!).
* Deprecated the `bd*Ex` functions in favour of re-named "safe" `bd*_s` functions.
## Changes in Version 2.1
_Version 2.1 (Released 23 August 2006)_
* Added support for 64-bit compilers.
* Added fudge so opaque pointers will work with C++ compilers.
* Added new functions:
* `bdSqrt` computes the `integer' square root, s = floor(sqrt(x)).
* `bdModPowerOf2` computes a = a (mod 2^L).
* `bdXorBits` computes bitwise a = b XOR c.
* `bdOrBits` computes bitwise a = b OR c.
* `bdAndBits` computes bitwise a = b AND c.
* `bdVersion` returns version number as an integer = major*1000+minor*100+release*10+uses_asm(0|1).
* `bdRandomBits` generates a random BIGD number up to n bits long (i.e. r = [0, 2^n]) using the internal RNG.
* Removed the shift limit on `bdShiftLeft` and `bdShiftRight`. This was previously limited to a maximum of 32 bits. It will now shift by any value - well, any value up to `SIZE_MAX`.
* Re-organised the source and include files for the internal random number generator functions to avoid having to include the `spRandom` modules when they are not needed.
* Fixed up inconsistencies in the documentation for the `bdConv*` functions.
* Made minor change to `mpIsPrime` to comply with ANSI X.42-2003 Annex F.1.1 "Range of bases in Miller-Rabin test".
* Made minor improvements to the `spBetterRand` function.
* Fixed bugs in `bdConvertHex`, `bdGetBit` and `bdSetBit`.
* Made various minor changes in the code to avoid warning messages when compiling with the `-Wall -pedantic` options.
# CHANGE LOG FOR BIGDIGITS
## Changes in Version 2.6
_Version 2.6.1 (Released 31 March 2016)_
* Added new functions to perform modular arithmetic operations, particularly useful for doing computations in a prime field for elliptic curves:
* `mpModSquare`, `bdModSquare` to compute `a = x^2 (mod m)`
* `mpModSqrt`, `bdModSqrt` to compute a square root modulo a prime p
* `mpModHalve`, `bdModHalve` to compute `a = x / 2 (mod p)`
* `mpModAdd`, `bdModAdd` and `mpModSub`, `bdModSub` to compute `w = u <20> v (mod m)` quickly for u and v in the range `[0, m-1]`.
* The function `mpModSpecial` to compute `u = v (mod m)` in the special case where v is known to be in the range `[0, km]` for k a small integer. This is faster than `mpModulo`.
* Added functions `mpToShort`, `bdToShort` to convert a multiprecision integer to a single digit.
* Added functions `mpShortIsEqual`, `bdmpShortIsEqual` to check if a multiprecision integer is equal to a single digit.
* Added the explicit constant-time comparison functions.
* `mpEqual_ct()`, `bdIsEqual_ct()`
* `mpIsZero_ct()`, `bdIsZero_ct()`
* `mpCompare_ct()`, `bdCompare_ct()`
* Reversed the change in v2.5 to make the comparison functions constant-time by default. The original comparison functions are now _not_ constant-time, as they were before v2.5\. The user must explicitly select the constant-time variant (ending **_ct**). To summarize: the functions `mpEqual`, `bdIsEqual`, `mpIsZero`, `bdIsZero`, `mpCompare` and `bdCompare` are _not_ constant-time in v2.6.
> _Comment:_ We realised after we made the change in v2.5 that the majority of comparison operations in our own code were simple checks for special cases and were not comparing secret values, so they did not need the more expensive constant-time operations. There were only a few occasions where we did comparisons on secret values and these were easily found and explicitly changed to do a constant-time comparison. So, sorry, we shouldn't have changed the default behaviour in v2.5\. It's back now to how it was before.
* Added the functions `mpCompileTime`, `bdCompileTime` to show the time and date of compilation.
* Added the function `mpPrintBits` to print the value in 0/1 bit format.
* Added the option to specify the global preprocessor definition, say, `MAX_FIXED_BIT_LENGTH=640` when using the `NO_ALLOCS` option for the "mp" functions. This allows you to change the maximum fixed length of arrays without editing the core source code.
* Increased the size of the fixed-length buffers in the `mpPrint*()` functions to avoid buffer overflows
* Fixed an issue with the `mpPrint*()` functions when displaying zero values.
* Added the `bdNewVars` and `bdFreeVars` functions to allow "bulk" creation and destruction of "bd" variables in a single line of code.
## Changes in Version 2.5
_Version 2.5 (Released 22 October 2015)_
* Changed license conditions to Mozilla Public License, v. 2.0.
* Fixed `bdShortMult` to catch empty `u` parameter.
* Fixed `bdPrintBits` to print "0" if bit length is zero.
* Changed comparison functions to be constant-time by default. Retained the old, quicker functions as `_q` variants.
* `mpEqual` `bdIsEqual` `mpEqual_q` `bdIsEqual_q`
* `mpIsZero` `bdIsZero` `mpIsZero_q` `bdIsZero_q`
* `mpCompare` `bdCompare` `mpCompare_q` `bdCompare_q`
* Added constant-time modular exponentiation functions `bdModExp_ct` and `mpModExp_ct`.
* Added `mpPrintDecimalSigned` function to display negative numbers ("**mp**" only).
## Changes in Version 2.4
_Version 2.4 (Released 27 April 2013)_
* Added markup for Doxygen documentation to produce a manual in CHM and HTML formats.
* Updated the "pretty-good" internal RNG functions in `bigdRand` and `bigdigitsRand` to improve the seeding of the ANSI X9.31 PRNG algorithm.
* Fixed the `NO_ALLOCS` option so it does not use malloc with the `mpConv` functions (thanks to Kevin Kramb for pointing this out).
* Added the new functions `bdRandomOctets`, `bdRandomNumber` and `bdQuickRandBits`, which do various contortions you might want to do with random numbers.
* Updated the test source code modules.
## Changes in Version 2.3
_Version 2.3 (Released 11 November 2011)_
* Added new functions to compute the integer cube root: `bdCubeRoot` and `mpCubeRoot`.
* Updated and improved the integer square root functions: `bdSqrt` and `mpSqrt`.
* Added the more useful print functions with an optional prefix and suffix:
* `bdPrintHex` prints a bigdigit number in hex format.
* `bdPrintDecimal` prints a bigdigit number in decimal format.and the equivalent mp functions `mpPrintHex` and `mpPrintDecimal`.
* Added the new function `bdPower` to compute the n-th power of a number `y = g^n`. Use this with caution as you can quickly run out of memory. It's meant for small exponents like n=3.
* Improved the efficiency of the greatest common divisor functions, `bdGcd` and `mpGcd`.
* Fixed the bug in `mpChs` (thanks to Valery Blazhnov).
* Fixed the bug in `mpAlloc` which would fail if you called `bdSetDigit(b, 0)` (thanks to "Radistao").
## Changes in Version 2.2
_Version 2.2 (Released 31 July 2008)_
* Added sliding-window exponentiation to speed up the ModExp functions.
* Added new bd functions:
* `bdJacobi` computes the Jacobi (Legendre) symbol.
* `bdGetBit` returns the value of a bit at a given position in a number.
* `bdSetBit` sets the bit at a given position in a number.
* `bdNotBits` computes bitwise a = NOT a.
* Added the new functions `mpIsNegative`, `mpChs` and `mpAbs` in anticipation of adding full signed integer functionality in a later version.
* Added the `NO_ALLOCS` option to compile the "mp" library without using any memory allocation.
* Added the `USE_64WITH32` option to use the 64-bit integer types (`long long`) if available on a 32-bit machine.
* Improved the zeroisation and destroy macros.
* Moved the type declarations for the exact-width types to a separate include file.
* Re-organised and re-named the ancillary source and include files (yet again!).
* Deprecated the `bd*Ex` functions in favour of re-named "safe" `bd*_s` functions.
## Changes in Version 2.1
_Version 2.1 (Released 23 August 2006)_
* Added support for 64-bit compilers.
* Added fudge so opaque pointers will work with C++ compilers.
* Added new functions:
* `bdSqrt` computes the `integer' square root, s = floor(sqrt(x)).
* `bdModPowerOf2` computes a = a (mod 2^L).
* `bdXorBits` computes bitwise a = b XOR c.
* `bdOrBits` computes bitwise a = b OR c.
* `bdAndBits` computes bitwise a = b AND c.
* `bdVersion` returns version number as an integer = major*1000+minor*100+release*10+uses_asm(0|1).
* `bdRandomBits` generates a random BIGD number up to n bits long (i.e. r = [0, 2^n]) using the internal RNG.
* Removed the shift limit on `bdShiftLeft` and `bdShiftRight`. This was previously limited to a maximum of 32 bits. It will now shift by any value - well, any value up to `SIZE_MAX`.
* Re-organised the source and include files for the internal random number generator functions to avoid having to include the `spRandom` modules when they are not needed.
* Fixed up inconsistencies in the documentation for the `bdConv*` functions.
* Made minor change to `mpIsPrime` to comply with ANSI X.42-2003 Annex F.1.1 "Range of bases in Miller-Rabin test".
* Made minor improvements to the `spBetterRand` function.
* Fixed bugs in `bdConvertHex`, `bdGetBit` and `bdSetBit`.
* Made various minor changes in the code to avoid warning messages when compiling with the `-Wall -pedantic` options.

View File

@@ -1,373 +1,373 @@
Mozilla Public License Version 2.0
==================================
1. Definitions
--------------
1.1. "Contributor"
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
1.3. "Contribution"
means Covered Software of a particular Contributor.
1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
1.5. "Incompatible With Secondary Licenses"
means
(a) that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
(b) that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.7. "Larger Work"
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
1.8. "License"
means this document.
1.9. "Licensable"
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
1.10. "Modifications"
means any of the following:
(a) any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
(b) any new file in Source Code Form that contains any Covered
Software.
1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
1.13. "Source Code Form"
means the form of the work preferred for making modifications.
1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, "control" means (a) the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or (b) ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
2. License Grants and Conditions
--------------------------------
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
(a) under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
(b) under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
(a) for any code that a Contributor has removed from Covered Software;
or
(b) for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
(c) under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.
3. Responsibilities
-------------------
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
(a) such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and
(b) You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
---------------------------------------------------
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.
5. Termination
--------------
5.1. The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated (a) provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and (b) on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
************************************************************************
* *
* 6. Disclaimer of Warranty *
* ------------------------- *
* *
* Covered Software is provided under this License on an "as is" *
* basis, without warranty of any kind, either expressed, implied, or *
* statutory, including, without limitation, warranties that the *
* Covered Software is free of defects, merchantable, fit for a *
* particular purpose or non-infringing. The entire risk as to the *
* quality and performance of the Covered Software is with You. *
* Should any Covered Software prove defective in any respect, You *
* (not any Contributor) assume the cost of any necessary servicing, *
* repair, or correction. This disclaimer of warranty constitutes an *
* essential part of this License. No use of any Covered Software is *
* authorized under this License except under this disclaimer. *
* *
************************************************************************
************************************************************************
* *
* 7. Limitation of Liability *
* -------------------------- *
* *
* Under no circumstances and under no legal theory, whether tort *
* (including negligence), contract, or otherwise, shall any *
* Contributor, or anyone who distributes Covered Software as *
* permitted above, be liable to You for any direct, indirect, *
* special, incidental, or consequential damages of any character *
* including, without limitation, damages for lost profits, loss of *
* goodwill, work stoppage, computer failure or malfunction, or any *
* and all other commercial damages or losses, even if such party *
* shall have been informed of the possibility of such damages. This *
* limitation of liability shall not apply to liability for death or *
* personal injury resulting from such party's negligence to the *
* extent applicable law prohibits such limitation. Some *
* jurisdictions do not allow the exclusion or limitation of *
* incidental or consequential damages, so this exclusion and *
* limitation may not apply to You. *
* *
************************************************************************
8. Litigation
-------------
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
9. Miscellaneous
----------------
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
10. Versions of the License
---------------------------
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice
-------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
---------------------------------------------------------
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.
Mozilla Public License Version 2.0
==================================
1. Definitions
--------------
1.1. "Contributor"
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
1.3. "Contribution"
means Covered Software of a particular Contributor.
1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
1.5. "Incompatible With Secondary Licenses"
means
(a) that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
(b) that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.7. "Larger Work"
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
1.8. "License"
means this document.
1.9. "Licensable"
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
1.10. "Modifications"
means any of the following:
(a) any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
(b) any new file in Source Code Form that contains any Covered
Software.
1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
1.13. "Source Code Form"
means the form of the work preferred for making modifications.
1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, "control" means (a) the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or (b) ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
2. License Grants and Conditions
--------------------------------
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
(a) under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
(b) under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
(a) for any code that a Contributor has removed from Covered Software;
or
(b) for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
(c) under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.
3. Responsibilities
-------------------
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
(a) such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and
(b) You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
---------------------------------------------------
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.
5. Termination
--------------
5.1. The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated (a) provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and (b) on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
************************************************************************
* *
* 6. Disclaimer of Warranty *
* ------------------------- *
* *
* Covered Software is provided under this License on an "as is" *
* basis, without warranty of any kind, either expressed, implied, or *
* statutory, including, without limitation, warranties that the *
* Covered Software is free of defects, merchantable, fit for a *
* particular purpose or non-infringing. The entire risk as to the *
* quality and performance of the Covered Software is with You. *
* Should any Covered Software prove defective in any respect, You *
* (not any Contributor) assume the cost of any necessary servicing, *
* repair, or correction. This disclaimer of warranty constitutes an *
* essential part of this License. No use of any Covered Software is *
* authorized under this License except under this disclaimer. *
* *
************************************************************************
************************************************************************
* *
* 7. Limitation of Liability *
* -------------------------- *
* *
* Under no circumstances and under no legal theory, whether tort *
* (including negligence), contract, or otherwise, shall any *
* Contributor, or anyone who distributes Covered Software as *
* permitted above, be liable to You for any direct, indirect, *
* special, incidental, or consequential damages of any character *
* including, without limitation, damages for lost profits, loss of *
* goodwill, work stoppage, computer failure or malfunction, or any *
* and all other commercial damages or losses, even if such party *
* shall have been informed of the possibility of such damages. This *
* limitation of liability shall not apply to liability for death or *
* personal injury resulting from such party's negligence to the *
* extent applicable law prohibits such limitation. Some *
* jurisdictions do not allow the exclusion or limitation of *
* incidental or consequential damages, so this exclusion and *
* limitation may not apply to You. *
* *
************************************************************************
8. Litigation
-------------
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
9. Miscellaneous
----------------
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
10. Versions of the License
---------------------------
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice
-------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
---------------------------------------------------------
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.

View File

@@ -1,74 +1,74 @@
# Linux/Cygwin gcc Makefile for bigdigits tests
# $Date: 2015-10-21 20:07:00 $
# $Revision: 2.5.0 $
# $Author: dai $
#
OBJECTS= bigd.o bigdigits.o bigdigitsRand.o bigdRand.o
INCLUDES= bigd.h bigdigits.h bigdtypes.h bigdRand.h bigdigitsRand.h
CFLAGS= -std=c99 -pedantic -Wall -Wpointer-arith -Wstrict-prototypes -Wno-format -O2
CC= gcc
%.o: %.c $(INCLUDES)
$(CC) $(CFLAGS) -c $<
# bigd "bd" tests
t_bdTest: t_bdTest.o $(INCLUDES) $(OBJECTS)
$(CC) $(CFLAGS) -o $@ $@.o $(OBJECTS) $(LDFLAGS)
t_bdSimple: t_bdSimple.o $(INCLUDES) $(OBJECTS)
$(CC) $(CFLAGS) -o $@ $@.o $(OBJECTS) $(LDFLAGS)
t_bdRSA: t_bdRSA.o $(INCLUDES) $(OBJECTS)
$(CC) $(CFLAGS) -o $@ $@.o $(OBJECTS) $(LDFLAGS)
t_bdRSA1: t_bdRSA1.o $(INCLUDES) $(OBJECTS)
$(CC) $(CFLAGS) -o $@ $@.o $(OBJECTS) $(LDFLAGS)
t_bdDSA: t_bdDSA.o $(INCLUDES) $(OBJECTS)
$(CC) $(CFLAGS) -o $@ $@.o $(OBJECTS) $(LDFLAGS)
t_bdRDSA: t_bdRDSA.o $(INCLUDES) $(OBJECTS)
$(CC) $(CFLAGS) -o $@ $@.o $(OBJECTS) $(LDFLAGS)
t_bdRsaCrack: t_bdRsaCrack.o $(INCLUDES) $(OBJECTS)
$(CC) $(CFLAGS) -o $@ $@.o $(OBJECTS) $(LDFLAGS)
t_bdRsaFactorN: t_bdRsaFactorN.o $(INCLUDES) $(OBJECTS)
$(CC) $(CFLAGS) -o $@ $@.o $(OBJECTS) $(LDFLAGS)
t_bdRandomOctets: t_bdRandomOctets.o $(INCLUDES) $(OBJECTS)
$(CC) $(CFLAGS) -o $@ $@.o $(OBJECTS) $(LDFLAGS) -lm
t_bdQuickRandBits: t_bdQuickRandBits.o $(INCLUDES) $(OBJECTS)
$(CC) $(CFLAGS) -o $@ $@.o $(OBJECTS) $(LDFLAGS)
t_bdRSA_blinded: t_bdRSA_blinded.o $(INCLUDES) $(OBJECTS)
$(CC) $(CFLAGS) -o $@ $@.o $(OBJECTS) $(LDFLAGS)
# bigdigits "mp" tests
t_mpTest: t_mpTest.o $(INCLUDES) $(OBJECTS)
$(CC) $(CFLAGS) -o $@ $@.o $(OBJECTS) $(LDFLAGS)
t_mpRSA508: t_mpRSA508.o $(INCLUDES) $(OBJECTS)
$(CC) $(CFLAGS) -o $@ $@.o $(OBJECTS) $(LDFLAGS)
t_mpJacobi: t_mpJacobi.o $(INCLUDES) $(OBJECTS)
$(CC) $(CFLAGS) -o $@ $@.o $(OBJECTS) $(LDFLAGS)
# extra "sp" function tests
t_spExtras: t_spExtras.o spExtras.o
$(CC) $(CFLAGS) -o $@ $@.o spExtras.o $(OBJECTS) $(LDFLAGS)
spExtras.o: spExtras.c spExtras.h $(INCLUDES)
# Call functions from a C++ program
t_bdCPP: t_bdCPP.o $(INCLUDES) $(OBJECTS)
g++ $(CFLAGS) -o $@ $@.o $(OBJECTS) $(LDFLAGS)
clean:
-rm -f *.o
# Linux/Cygwin gcc Makefile for bigdigits tests
# $Date: 2015-10-21 20:07:00 $
# $Revision: 2.5.0 $
# $Author: dai $
#
OBJECTS= bigd.o bigdigits.o bigdigitsRand.o bigdRand.o
INCLUDES= bigd.h bigdigits.h bigdtypes.h bigdRand.h bigdigitsRand.h
CFLAGS= -std=c99 -pedantic -Wall -Wpointer-arith -Wstrict-prototypes -Wno-format -O2
CC= gcc
%.o: %.c $(INCLUDES)
$(CC) $(CFLAGS) -c $<
# bigd "bd" tests
t_bdTest: t_bdTest.o $(INCLUDES) $(OBJECTS)
$(CC) $(CFLAGS) -o $@ $@.o $(OBJECTS) $(LDFLAGS)
t_bdSimple: t_bdSimple.o $(INCLUDES) $(OBJECTS)
$(CC) $(CFLAGS) -o $@ $@.o $(OBJECTS) $(LDFLAGS)
t_bdRSA: t_bdRSA.o $(INCLUDES) $(OBJECTS)
$(CC) $(CFLAGS) -o $@ $@.o $(OBJECTS) $(LDFLAGS)
t_bdRSA1: t_bdRSA1.o $(INCLUDES) $(OBJECTS)
$(CC) $(CFLAGS) -o $@ $@.o $(OBJECTS) $(LDFLAGS)
t_bdDSA: t_bdDSA.o $(INCLUDES) $(OBJECTS)
$(CC) $(CFLAGS) -o $@ $@.o $(OBJECTS) $(LDFLAGS)
t_bdRDSA: t_bdRDSA.o $(INCLUDES) $(OBJECTS)
$(CC) $(CFLAGS) -o $@ $@.o $(OBJECTS) $(LDFLAGS)
t_bdRsaCrack: t_bdRsaCrack.o $(INCLUDES) $(OBJECTS)
$(CC) $(CFLAGS) -o $@ $@.o $(OBJECTS) $(LDFLAGS)
t_bdRsaFactorN: t_bdRsaFactorN.o $(INCLUDES) $(OBJECTS)
$(CC) $(CFLAGS) -o $@ $@.o $(OBJECTS) $(LDFLAGS)
t_bdRandomOctets: t_bdRandomOctets.o $(INCLUDES) $(OBJECTS)
$(CC) $(CFLAGS) -o $@ $@.o $(OBJECTS) $(LDFLAGS) -lm
t_bdQuickRandBits: t_bdQuickRandBits.o $(INCLUDES) $(OBJECTS)
$(CC) $(CFLAGS) -o $@ $@.o $(OBJECTS) $(LDFLAGS)
t_bdRSA_blinded: t_bdRSA_blinded.o $(INCLUDES) $(OBJECTS)
$(CC) $(CFLAGS) -o $@ $@.o $(OBJECTS) $(LDFLAGS)
# bigdigits "mp" tests
t_mpTest: t_mpTest.o $(INCLUDES) $(OBJECTS)
$(CC) $(CFLAGS) -o $@ $@.o $(OBJECTS) $(LDFLAGS)
t_mpRSA508: t_mpRSA508.o $(INCLUDES) $(OBJECTS)
$(CC) $(CFLAGS) -o $@ $@.o $(OBJECTS) $(LDFLAGS)
t_mpJacobi: t_mpJacobi.o $(INCLUDES) $(OBJECTS)
$(CC) $(CFLAGS) -o $@ $@.o $(OBJECTS) $(LDFLAGS)
# extra "sp" function tests
t_spExtras: t_spExtras.o spExtras.o
$(CC) $(CFLAGS) -o $@ $@.o spExtras.o $(OBJECTS) $(LDFLAGS)
spExtras.o: spExtras.c spExtras.h $(INCLUDES)
# Call functions from a C++ program
t_bdCPP: t_bdCPP.o $(INCLUDES) $(OBJECTS)
g++ $(CFLAGS) -o $@ $@.o $(OBJECTS) $(LDFLAGS)
clean:
-rm -f *.o

View File

@@ -1,57 +1,57 @@
BIGDIGITS LIBRARY
Version 2.6.1 Released 2016-03-31.
Core Source Code Files
----------------------
bigd.c
bigd.h
bigdigits.c
bigdigits.h
bigdtypes.h
Use these for "pretty-good" random number routines
--------------------------------------------------
bigdRand.c
bigdRand.h
bigdigitsRand.c
bigdigitsRand.h
Additional Source Code Files
----------------------------
spExtras.c
spExtras.h
Test Source Code Files
----------------------
t_bdDSA.c
t_bdQuickRandBits.c
t_bdRandomOctets.c
t_bdRDSA.c
t_bdRSA.c
t_bdRSA1.c
t_bdRsaCrack.c
t_bdRsaFactorN.c
t_bdSimple.c
t_bdTest.c
t_mpJacobi.c
t_mpRSA508.c
t_mpTest.c
t_spExtras.c
t_bdCPP.cpp
t_bdRSA_blinded.c
t_mpModArith.c
Manual
------
BigDigits.chm
For more details on how to compile and so forth, see
<http://www.di-mgt.com.au/bigdigits.html>
For the online manual, see
<http://www.di-mgt.com.au/bigdigitsmanual/>
Please read the copyright notice and licence conditions in
LICENCE.txt.
BIGDIGITS LIBRARY
Version 2.6.1 Released 2016-03-31.
Core Source Code Files
----------------------
bigd.c
bigd.h
bigdigits.c
bigdigits.h
bigdtypes.h
Use these for "pretty-good" random number routines
--------------------------------------------------
bigdRand.c
bigdRand.h
bigdigitsRand.c
bigdigitsRand.h
Additional Source Code Files
----------------------------
spExtras.c
spExtras.h
Test Source Code Files
----------------------
t_bdDSA.c
t_bdQuickRandBits.c
t_bdRandomOctets.c
t_bdRDSA.c
t_bdRSA.c
t_bdRSA1.c
t_bdRsaCrack.c
t_bdRsaFactorN.c
t_bdSimple.c
t_bdTest.c
t_mpJacobi.c
t_mpRSA508.c
t_mpTest.c
t_spExtras.c
t_bdCPP.cpp
t_bdRSA_blinded.c
t_mpModArith.c
Manual
------
BigDigits.chm
For more details on how to compile and so forth, see
<http://www.di-mgt.com.au/bigdigits.html>
For the online manual, see
<http://www.di-mgt.com.au/bigdigitsmanual/>
Please read the copyright notice and licence conditions in
LICENCE.txt.

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,78 +1,78 @@
/* $Id: bigdRand.c $ */
/***** BEGIN LICENSE BLOCK *****
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Copyright (c) 2001-16 David Ireland, D.I. Management Services Pty Limited
* <http://www.di-mgt.com.au/bigdigits.html>. All rights reserved.
*
***** END LICENSE BLOCK *****/
/*
* Last updated:
* $Date: 2016-03-31 09:51:00 $
* $Revision: 2.6.1 $
* $Author: dai $
*/
/* Random number BIGD functions that rely on spBetterRand */
#include "bigdRand.h"
#include "bigdigitsRand.h"
#include <stdio.h>
bdigit_t bdRandDigit(void)
/* Return a random digit. */
{
return spBetterRand();
}
size_t bdRandomBits(BIGD a, size_t nbits)
/* Generate a random BIGD number <= 2^{nbits}-1 using internal RNG */
{
const int bits_per_digit = sizeof(bdigit_t) * 8;
size_t i;
int j;
bdigit_t r;
bdSetZero(a);
bdSetBit(a, nbits-1, 0);
r = bdRandDigit();
j = bits_per_digit;
for (i = 0; i < nbits; i++)
{
if (j <= 0)
{
r = bdRandDigit();
j = bits_per_digit;
}
bdSetBit(a, i, r & 0x1);
r >>= 1;
j--;
}
return i;
}
/** Generate array of random octets (bytes) using internal RNG.
This function is in the correct form for BD_RANDFUNC.
Seed is ignored here.
*/
int bdRandomOctets(unsigned char *bytes, size_t nbytes, const unsigned char *seed, size_t seedlen)
{
return mpRandomOctets(bytes, nbytes, seed, seedlen);
}
size_t bdRandomNumber(BIGD a, BIGD n)
{ /* Generate a number in the range [0, n-1] */
size_t nbits = bdBitLength(n);
bdSetZero(a);
do {
bdRandomBits(a, nbits);
} while (bdCompare(a, n) >= 0);
return bdSizeof(a);
}
/* $Id: bigdRand.c $ */
/***** BEGIN LICENSE BLOCK *****
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Copyright (c) 2001-16 David Ireland, D.I. Management Services Pty Limited
* <http://www.di-mgt.com.au/bigdigits.html>. All rights reserved.
*
***** END LICENSE BLOCK *****/
/*
* Last updated:
* $Date: 2016-03-31 09:51:00 $
* $Revision: 2.6.1 $
* $Author: dai $
*/
/* Random number BIGD functions that rely on spBetterRand */
#include "bigdRand.h"
#include "bigdigitsRand.h"
#include <stdio.h>
bdigit_t bdRandDigit(void)
/* Return a random digit. */
{
return spBetterRand();
}
size_t bdRandomBits(BIGD a, size_t nbits)
/* Generate a random BIGD number <= 2^{nbits}-1 using internal RNG */
{
const int bits_per_digit = sizeof(bdigit_t) * 8;
size_t i;
int j;
bdigit_t r;
bdSetZero(a);
bdSetBit(a, nbits-1, 0);
r = bdRandDigit();
j = bits_per_digit;
for (i = 0; i < nbits; i++)
{
if (j <= 0)
{
r = bdRandDigit();
j = bits_per_digit;
}
bdSetBit(a, i, r & 0x1);
r >>= 1;
j--;
}
return i;
}
/** Generate array of random octets (bytes) using internal RNG.
This function is in the correct form for BD_RANDFUNC.
Seed is ignored here.
*/
int bdRandomOctets(unsigned char *bytes, size_t nbytes, const unsigned char *seed, size_t seedlen)
{
return mpRandomOctets(bytes, nbytes, seed, seedlen);
}
size_t bdRandomNumber(BIGD a, BIGD n)
{ /* Generate a number in the range [0, n-1] */
size_t nbits = bdBitLength(n);
bdSetZero(a);
do {
bdRandomBits(a, nbits);
} while (bdCompare(a, n) >= 0);
return bdSizeof(a);
}

View File

@@ -1,69 +1,69 @@
/* $Id: bigdRand.h $ */
/** @file
Interface for BigDigits "bd" random number functions using a "pretty-good" internal RNG
@par The internal random number generator (RNG)
The internal RNG uses a variant of the random number generation algorithm
in Appendix A of ANSI X9.31-1998, but using the Tiny Encryption Algorithm (TEAX)
instead of the Data Encryption Algorithm (DEA).
It uses the current time and process ID as a seed.
Although not strictly crypto secure, it is "pretty good", and certainly much better than
anything using the built-in rand() function in C. Look at the source code and make your own call.
@par
If you want proper cryptographic security, use the bdRandomSeeded() function with a call to a
secure RNG function that you trust.
*/
/***** BEGIN LICENSE BLOCK *****
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Copyright (c) 2001-16 David Ireland, D.I. Management Services Pty Limited
* <http://www.di-mgt.com.au/bigdigits.html>. All rights reserved.
*
***** END LICENSE BLOCK *****/
/*
* Last updated:
* $Date: 2016-03-31 09:51:00 $
* $Revision: 2.6.1 $
* $Author: dai $
*/
#ifndef BIGDRAND_H_
#define BIGDRAND_H_ 1
#include "bigd.h"
#include "bigdRand.h"
#ifdef __cplusplus
extern "C" {
#endif
/** Generate a single random digit using internal RNG. */
bdigit_t bdRandDigit(void);
/** Generate a random BIGD number of bit length at most \c nbits using internal RNG
@param[out] a to receive generated random number
@param[in] nbits maximum number of bits
@returns Number of digits actually set
*/
size_t bdRandomBits(BIGD a, size_t nbits);
/* Added in [v2.4] */
/** Generate array of random octets (bytes) using internal RNG
* @remarks This function is in the correct form for BD_RANDFUNC.
*/
int bdRandomOctets(unsigned char *bytes, size_t nbytes, const unsigned char *seed, size_t seedlen);
/** Generate a number at random from a uniform distribution in [0, n-1] */
size_t bdRandomNumber(BIGD a, BIGD n);
#ifdef __cplusplus
}
#endif
#endif /* BIGDRAND_H_ */
/* $Id: bigdRand.h $ */
/** @file
Interface for BigDigits "bd" random number functions using a "pretty-good" internal RNG
@par The internal random number generator (RNG)
The internal RNG uses a variant of the random number generation algorithm
in Appendix A of ANSI X9.31-1998, but using the Tiny Encryption Algorithm (TEAX)
instead of the Data Encryption Algorithm (DEA).
It uses the current time and process ID as a seed.
Although not strictly crypto secure, it is "pretty good", and certainly much better than
anything using the built-in rand() function in C. Look at the source code and make your own call.
@par
If you want proper cryptographic security, use the bdRandomSeeded() function with a call to a
secure RNG function that you trust.
*/
/***** BEGIN LICENSE BLOCK *****
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Copyright (c) 2001-16 David Ireland, D.I. Management Services Pty Limited
* <http://www.di-mgt.com.au/bigdigits.html>. All rights reserved.
*
***** END LICENSE BLOCK *****/
/*
* Last updated:
* $Date: 2016-03-31 09:51:00 $
* $Revision: 2.6.1 $
* $Author: dai $
*/
#ifndef BIGDRAND_H_
#define BIGDRAND_H_ 1
#include "bigd.h"
#include "bigdRand.h"
#ifdef __cplusplus
extern "C" {
#endif
/** Generate a single random digit using internal RNG. */
bdigit_t bdRandDigit(void);
/** Generate a random BIGD number of bit length at most \c nbits using internal RNG
@param[out] a to receive generated random number
@param[in] nbits maximum number of bits
@returns Number of digits actually set
*/
size_t bdRandomBits(BIGD a, size_t nbits);
/* Added in [v2.4] */
/** Generate array of random octets (bytes) using internal RNG
* @remarks This function is in the correct form for BD_RANDFUNC.
*/
int bdRandomOctets(unsigned char *bytes, size_t nbytes, const unsigned char *seed, size_t seedlen);
/** Generate a number at random from a uniform distribution in [0, n-1] */
size_t bdRandomNumber(BIGD a, BIGD n);
#ifdef __cplusplus
}
#endif
#endif /* BIGDRAND_H_ */

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,318 +1,318 @@
/* $Id: bigdigitsRand.c $ */
/***** BEGIN LICENSE BLOCK *****
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Copyright (c) 2001-16 David Ireland, D.I. Management Services Pty Limited
* <http://www.di-mgt.com.au/bigdigits.html>. All rights reserved.
*
***** END LICENSE BLOCK *****/
/*
* Last updated:
* $Date: 2016-03-31 09:51:00 $
* $Revision: 2.6.1 $
* $Author: dai $
*/
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "bigdigits.h"
#include "bigdigitsRand.h"
static uint32_t btrrand(void);
/**********************/
/* EXPORTED FUNCTIONS */
/**********************/
DIGIT_T spBetterRand(void)
{ /* Returns a "better" pseudo-random digit. */
return (DIGIT_T)btrrand();
}
/* Added [v2.2] */
size_t mpRandomBits(DIGIT_T a[], size_t ndigits, size_t nbits)
/* Generate a random mp number <= 2^{nbits}-1 using internal RNG */
{
const int bits_per_digit = BITS_PER_DIGIT;
size_t i;
int j;
DIGIT_T r;
mpSetZero(a, ndigits);
r = spBetterRand();
j = bits_per_digit;
for (i = 0; i < nbits; i++)
{
if (j <= 0)
{
r = spBetterRand();
j = bits_per_digit;
}
mpSetBit(a, ndigits, i, r & 0x1);
r >>= 1;
j--;
}
return i;
}
/** Generate array of random octets (bytes) using internal RNG.
This function is in the correct form for BD_RANDFUNC.
Seed is ignored here.
*/
int mpRandomOctets(unsigned char *bytes, size_t nbytes, const unsigned char *seed, size_t seedlen)
{
const int octets_per_digit = sizeof(DIGIT_T);
size_t i;
int j;
DIGIT_T r;
r = spBetterRand();
j = octets_per_digit;
for (i = 0; i < nbytes; i++)
{
if (j <= 0)
{
r = spBetterRand();
j = octets_per_digit;
}
bytes[i] = r & 0xFF;
r >>= 8;
j--;
}
return (int)i;
}
/**********************/
/* INTERNAL FUNCTIONS */
/**********************/
/******************************************************************************
Generates a pseudo-random DIGIT value using the generator algorithm from
ANSI X9.31 Appendix A.2.4 "Generating Pseudo Random Numbers Using the DEA"
(formerly ANSI X9.17, Appendix C) but with the `Tiny Encryption Algorithm` (TEAX)
replacing the `DES E-D-E two-key triple-encryption` algorithm (Double DES)
This variant has much less code, and is faster.
CAUTION: not thread-safe as it uses a static variable.
This is "pretty good", but not quite cryptographically secure since the seed is
only generated from the current time and process ID.
However, it is much better than just using the plain-old-rand() function.
The output should always pass the FIPS 140-2 statistical test.
Users can make their own call as to the security of this approach.
It's certainly sufficient for generating random digits for tests.
******************************************************************************/
/******************************************************************************
ANSI X9.17/X9.31 ALGORITHM:
Given
* D, a 64-bit representation of the current date-time
* S, a secret 64-bit seed that will be updated by this process
* K, a secret encryption key
Step 1. Compute the 64-bit block X = G(S, K, D) as follows:
1. I = E(D, K)
2. X = E(I XOR S, K)
3. S' = E(X XOR I, K)
where E(p, K) is the encryption of the 64-bit block p using key K.
Step 2. Return X and set S = S' for the next cycle.
******************************************************************************
THIS VARIANT:
1. Replace `Double DES` algorithm with `TEAX`.
2. Replace effective 112-bit Double DES key with 128-bit TEAX key.
******************************************************************************/
#define KEY_WORDS 4
static void encipher(uint32_t *const v,uint32_t *const w, const uint32_t *const k);
/* CAUTION: We use a static structure to store our values in. */
static struct {
int seeded;
uint32_t seed[2];
uint32_t key[KEY_WORDS];
} m_generator;
#if !(defined(ONLY_ANSI)) && (defined(_WIN32) || defined(WIN32))
#define WIN32_LEAN_AND_MEAN
#define STRICT
#include <windows.h>
#elif !(defined(ONLY_ANSI)) && (defined(unix) || defined (linux) || defined(__linux))
#else
#endif
/* Cross-platform ways to get a 64-bit time value and the process ID */
#if defined(unix) || defined(__unix__) || defined(linux) || defined(__linux__)
static void get_time64(uint32_t t[2])
{
#include <sys/time.h>
struct timeval tv;
gettimeofday(&tv, NULL);
memcpy(t, &tv, 2*sizeof(uint32_t));
}
#include <unistd.h>
#define processid getpid
#elif defined(_WIN32) || defined(WIN32)
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
static void get_time64(uint32_t t[2])
{
FILETIME ft;
GetSystemTimeAsFileTime (&ft);
t[0] = ft.dwHighDateTime;
t[1] = ft.dwLowDateTime;
}
#define processid GetCurrentProcessId
#else /* ANSI FALLBACK */
static void get_time64(uint32_t t[2])
{
/* Best we can do with strict ANSI */
/* [v2.2] added clock() as well as time() to improve precision.
* OK, so this isn't actually the time, but it's an independent value accurate to
* one millisecond, which is what we want.
*/
t[0] = (uint32_t)time(NULL);
t[1] = (uint32_t)clock();
}
unsigned long processid(void)
{ return 0; }
#endif
/* Given a 32-bit random seed, create a 64-bit seed S and 128-bit key K for the global generator */
static void btrseed(uint32_t seed)
{
int i;
uint32_t t[2];
/* Use plain old rand function to generate our global 64-bit seed S and initial 128-bit key K_0 */
srand(seed);
/* Only trust the lowest 8 bits from rand()... */
for (i = 0; i < 2; i++)
m_generator.seed[i] = (rand()&0xFF)<<24|(rand()&0xFF)<<16|(rand()&0xFF)<<8|(rand()&0xFF);
for (i = 0; i < KEY_WORDS; i++)
m_generator.key[i] = (rand()&0xFF)<<24|(rand()&0xFF)<<16|(rand()&0xFF)<<8|(rand()&0xFF);
/* Set flag so we only do this once */
m_generator.seeded = 1;
/* [v2.4] Blend in the current 64-bit time and re-encrypt the key with itself */
/* Note that the `block` in E(block, key) is 64 bits, but the `key` is 128 bits */
/* T = E(time, K_0) -- encrypt 64-bit time using K_0 */
get_time64(t);
encipher(t, t, m_generator.key);
/* K_1[0..63] = E(T XOR K_0[0..63], K_0)
-- encrypt left 64 bits of K_0 using K_0 --> left 64 bits of K_1
-- right 64 bits of K_0 --> right 64 bits of K_1 */
m_generator.key[0] ^= t[0];
m_generator.key[1] ^= t[1];
encipher(&m_generator.key[0], &m_generator.key[0], m_generator.key);
/* K_2[64..127] = E(T XOR K_1[64..127], K_1)
-- encrypt right 64 bits of K_1 using K_1 --> right 64 bits of K_2
-- left 64 bits of K_! --> left 64 bits of K_2 */
m_generator.key[2] ^= t[0];
m_generator.key[3] ^= t[1];
encipher(&m_generator.key[2], &m_generator.key[2], m_generator.key);
/* Output global key K = K_2 */
}
static uint32_t btrrand(void)
/* Returns one 32-bit word */
{
uint32_t inter[2], x[2];
/* Set seed if not already seeded */
if (!m_generator.seeded)
{ /* [v2.4] added process ID so processes launched at same time should give different values */
btrseed((uint32_t)time(NULL)<<16 ^ ((uint32_t)clock()<<8) ^ (uint32_t)processid());
}
/* I = E(D, K) */
get_time64(inter);
encipher(inter, inter, m_generator.key);
/* X = E(I XOR S, K) */
x[0] = inter[0] ^ m_generator.seed[0];
x[1] = inter[1] ^ m_generator.seed[1];
encipher(x, x, m_generator.key);
/* S' = E(X XOR I, K) */
inter[0] ^= x[0];
inter[1] ^= x[1];
encipher(inter, m_generator.seed, m_generator.key);
return x[0];
}
/************************************************
The Tiny Encryption Algorithm (TEA) by
David Wheeler and Roger Needham of the
Cambridge Computer Laboratory.
Placed in the Public Domain by
David Wheeler and Roger Needham.
**** ANSI C VERSION (New Variant) ****
Notes:
TEA is a Feistel cipher with XOR and
and addition as the non-linear mixing
functions.
Takes 64 bits of data in v[0] and v[1].
Returns 64 bits of data in w[0] and w[1].
Takes 128 bits of key in k[0] - k[3].
TEA can be operated in any of the modes
of DES. Cipher Block Chaining is, for example,
simple to implement.
n is the number of iterations. 32 is ample,
16 is sufficient, as few as eight may be OK.
The algorithm achieves good dispersion after
six iterations. The iteration count can be
made variable if required.
Note this is optimised for 32-bit CPUs with
fast shift capabilities. It can very easily
be ported to assembly language on most CPUs.
delta is chosen to be the real part of (the
golden ratio Sqrt(5/4) - 1/2 ~ 0.618034
multiplied by 2^32).
This version has been amended to foil two
weaknesses identified by David A. Wagner
(daw@cs.berkeley.edu): 1) effective key
length of old-variant TEA was 126 not 128
bits 2) a related key attack was possible
although impractical.
************************************************/
static void encipher(uint32_t *const v,uint32_t *const w, const uint32_t *const k)
{
register uint32_t y=v[0],z=v[1],sum=0,delta=0x9E3779B9,n=32;
while(n-->0)
{
y+= (((z<<4) ^ (z>>5)) + z) ^ (sum + k[sum & 3]);
sum += delta;
z+= (((y<<4) ^ (y>>5)) + y) ^ (sum + k[sum>>11 & 3]);
}
w[0]=y; w[1]=z;
}
/* $Id: bigdigitsRand.c $ */
/***** BEGIN LICENSE BLOCK *****
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Copyright (c) 2001-16 David Ireland, D.I. Management Services Pty Limited
* <http://www.di-mgt.com.au/bigdigits.html>. All rights reserved.
*
***** END LICENSE BLOCK *****/
/*
* Last updated:
* $Date: 2016-03-31 09:51:00 $
* $Revision: 2.6.1 $
* $Author: dai $
*/
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "bigdigits.h"
#include "bigdigitsRand.h"
static uint32_t btrrand(void);
/**********************/
/* EXPORTED FUNCTIONS */
/**********************/
DIGIT_T spBetterRand(void)
{ /* Returns a "better" pseudo-random digit. */
return (DIGIT_T)btrrand();
}
/* Added [v2.2] */
size_t mpRandomBits(DIGIT_T a[], size_t ndigits, size_t nbits)
/* Generate a random mp number <= 2^{nbits}-1 using internal RNG */
{
const int bits_per_digit = BITS_PER_DIGIT;
size_t i;
int j;
DIGIT_T r;
mpSetZero(a, ndigits);
r = spBetterRand();
j = bits_per_digit;
for (i = 0; i < nbits; i++)
{
if (j <= 0)
{
r = spBetterRand();
j = bits_per_digit;
}
mpSetBit(a, ndigits, i, r & 0x1);
r >>= 1;
j--;
}
return i;
}
/** Generate array of random octets (bytes) using internal RNG.
This function is in the correct form for BD_RANDFUNC.
Seed is ignored here.
*/
int mpRandomOctets(unsigned char *bytes, size_t nbytes, const unsigned char *seed, size_t seedlen)
{
const int octets_per_digit = sizeof(DIGIT_T);
size_t i;
int j;
DIGIT_T r;
r = spBetterRand();
j = octets_per_digit;
for (i = 0; i < nbytes; i++)
{
if (j <= 0)
{
r = spBetterRand();
j = octets_per_digit;
}
bytes[i] = r & 0xFF;
r >>= 8;
j--;
}
return (int)i;
}
/**********************/
/* INTERNAL FUNCTIONS */
/**********************/
/******************************************************************************
Generates a pseudo-random DIGIT value using the generator algorithm from
ANSI X9.31 Appendix A.2.4 "Generating Pseudo Random Numbers Using the DEA"
(formerly ANSI X9.17, Appendix C) but with the `Tiny Encryption Algorithm` (TEAX)
replacing the `DES E-D-E two-key triple-encryption` algorithm (Double DES)
This variant has much less code, and is faster.
CAUTION: not thread-safe as it uses a static variable.
This is "pretty good", but not quite cryptographically secure since the seed is
only generated from the current time and process ID.
However, it is much better than just using the plain-old-rand() function.
The output should always pass the FIPS 140-2 statistical test.
Users can make their own call as to the security of this approach.
It's certainly sufficient for generating random digits for tests.
******************************************************************************/
/******************************************************************************
ANSI X9.17/X9.31 ALGORITHM:
Given
* D, a 64-bit representation of the current date-time
* S, a secret 64-bit seed that will be updated by this process
* K, a secret encryption key
Step 1. Compute the 64-bit block X = G(S, K, D) as follows:
1. I = E(D, K)
2. X = E(I XOR S, K)
3. S' = E(X XOR I, K)
where E(p, K) is the encryption of the 64-bit block p using key K.
Step 2. Return X and set S = S' for the next cycle.
******************************************************************************
THIS VARIANT:
1. Replace `Double DES` algorithm with `TEAX`.
2. Replace effective 112-bit Double DES key with 128-bit TEAX key.
******************************************************************************/
#define KEY_WORDS 4
static void encipher(uint32_t *const v,uint32_t *const w, const uint32_t *const k);
/* CAUTION: We use a static structure to store our values in. */
static struct {
int seeded;
uint32_t seed[2];
uint32_t key[KEY_WORDS];
} m_generator;
#if !(defined(ONLY_ANSI)) && (defined(_WIN32) || defined(WIN32))
#define WIN32_LEAN_AND_MEAN
#define STRICT
#include <windows.h>
#elif !(defined(ONLY_ANSI)) && (defined(unix) || defined (linux) || defined(__linux))
#else
#endif
/* Cross-platform ways to get a 64-bit time value and the process ID */
#if defined(unix) || defined(__unix__) || defined(linux) || defined(__linux__)
static void get_time64(uint32_t t[2])
{
#include <sys/time.h>
struct timeval tv;
gettimeofday(&tv, NULL);
memcpy(t, &tv, 2*sizeof(uint32_t));
}
#include <unistd.h>
#define processid getpid
#elif defined(_WIN32) || defined(WIN32)
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
static void get_time64(uint32_t t[2])
{
FILETIME ft;
GetSystemTimeAsFileTime (&ft);
t[0] = ft.dwHighDateTime;
t[1] = ft.dwLowDateTime;
}
#define processid GetCurrentProcessId
#else /* ANSI FALLBACK */
static void get_time64(uint32_t t[2])
{
/* Best we can do with strict ANSI */
/* [v2.2] added clock() as well as time() to improve precision.
* OK, so this isn't actually the time, but it's an independent value accurate to
* one millisecond, which is what we want.
*/
t[0] = (uint32_t)time(NULL);
t[1] = (uint32_t)clock();
}
unsigned long processid(void)
{ return 0; }
#endif
/* Given a 32-bit random seed, create a 64-bit seed S and 128-bit key K for the global generator */
static void btrseed(uint32_t seed)
{
int i;
uint32_t t[2];
/* Use plain old rand function to generate our global 64-bit seed S and initial 128-bit key K_0 */
srand(seed);
/* Only trust the lowest 8 bits from rand()... */
for (i = 0; i < 2; i++)
m_generator.seed[i] = (rand()&0xFF)<<24|(rand()&0xFF)<<16|(rand()&0xFF)<<8|(rand()&0xFF);
for (i = 0; i < KEY_WORDS; i++)
m_generator.key[i] = (rand()&0xFF)<<24|(rand()&0xFF)<<16|(rand()&0xFF)<<8|(rand()&0xFF);
/* Set flag so we only do this once */
m_generator.seeded = 1;
/* [v2.4] Blend in the current 64-bit time and re-encrypt the key with itself */
/* Note that the `block` in E(block, key) is 64 bits, but the `key` is 128 bits */
/* T = E(time, K_0) -- encrypt 64-bit time using K_0 */
get_time64(t);
encipher(t, t, m_generator.key);
/* K_1[0..63] = E(T XOR K_0[0..63], K_0)
-- encrypt left 64 bits of K_0 using K_0 --> left 64 bits of K_1
-- right 64 bits of K_0 --> right 64 bits of K_1 */
m_generator.key[0] ^= t[0];
m_generator.key[1] ^= t[1];
encipher(&m_generator.key[0], &m_generator.key[0], m_generator.key);
/* K_2[64..127] = E(T XOR K_1[64..127], K_1)
-- encrypt right 64 bits of K_1 using K_1 --> right 64 bits of K_2
-- left 64 bits of K_! --> left 64 bits of K_2 */
m_generator.key[2] ^= t[0];
m_generator.key[3] ^= t[1];
encipher(&m_generator.key[2], &m_generator.key[2], m_generator.key);
/* Output global key K = K_2 */
}
static uint32_t btrrand(void)
/* Returns one 32-bit word */
{
uint32_t inter[2], x[2];
/* Set seed if not already seeded */
if (!m_generator.seeded)
{ /* [v2.4] added process ID so processes launched at same time should give different values */
btrseed((uint32_t)time(NULL)<<16 ^ ((uint32_t)clock()<<8) ^ (uint32_t)processid());
}
/* I = E(D, K) */
get_time64(inter);
encipher(inter, inter, m_generator.key);
/* X = E(I XOR S, K) */
x[0] = inter[0] ^ m_generator.seed[0];
x[1] = inter[1] ^ m_generator.seed[1];
encipher(x, x, m_generator.key);
/* S' = E(X XOR I, K) */
inter[0] ^= x[0];
inter[1] ^= x[1];
encipher(inter, m_generator.seed, m_generator.key);
return x[0];
}
/************************************************
The Tiny Encryption Algorithm (TEA) by
David Wheeler and Roger Needham of the
Cambridge Computer Laboratory.
Placed in the Public Domain by
David Wheeler and Roger Needham.
**** ANSI C VERSION (New Variant) ****
Notes:
TEA is a Feistel cipher with XOR and
and addition as the non-linear mixing
functions.
Takes 64 bits of data in v[0] and v[1].
Returns 64 bits of data in w[0] and w[1].
Takes 128 bits of key in k[0] - k[3].
TEA can be operated in any of the modes
of DES. Cipher Block Chaining is, for example,
simple to implement.
n is the number of iterations. 32 is ample,
16 is sufficient, as few as eight may be OK.
The algorithm achieves good dispersion after
six iterations. The iteration count can be
made variable if required.
Note this is optimised for 32-bit CPUs with
fast shift capabilities. It can very easily
be ported to assembly language on most CPUs.
delta is chosen to be the real part of (the
golden ratio Sqrt(5/4) - 1/2 ~ 0.618034
multiplied by 2^32).
This version has been amended to foil two
weaknesses identified by David A. Wagner
(daw@cs.berkeley.edu): 1) effective key
length of old-variant TEA was 126 not 128
bits 2) a related key attack was possible
although impractical.
************************************************/
static void encipher(uint32_t *const v,uint32_t *const w, const uint32_t *const k)
{
register uint32_t y=v[0],z=v[1],sum=0,delta=0x9E3779B9,n=32;
while(n-->0)
{
y+= (((z<<4) ^ (z>>5)) + z) ^ (sum + k[sum & 3]);
sum += delta;
z+= (((y<<4) ^ (y>>5)) + y) ^ (sum + k[sum>>11 & 3]);
}
w[0]=y; w[1]=z;
}

View File

@@ -1,56 +1,56 @@
/* $Id: bigdigitsRand.h $ */
/** @file
Interface for BigDigits "mp" random number functions using a "pretty-good" internal RNG
*/
/***** BEGIN LICENSE BLOCK *****
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Copyright (c) 2001-16 David Ireland, D.I. Management Services Pty Limited
* <http://www.di-mgt.com.au/bigdigits.html>. All rights reserved.
*
***** END LICENSE BLOCK *****/
/*
* Last updated:
* $Date: 2016-03-31 09:51:00 $
* $Revision: 2.6.1 $
* $Author: dai $
*/
/* [v2.2] changed name from spRandom to bigdigitsRand */
#ifndef BIGDIGITSRAND_H_
#define BIGDIGITSRAND_H_ 1
#include "bigdigits.h"
#ifdef __cplusplus
extern "C" {
#endif
/** Returns a "better" pseudo-random digit using internal RNG. */
DIGIT_T spBetterRand(void);
/** Generate a random mp number of bit length at most \c nbits using internal RNG
@param[out] a to receive generated random number
@param[in] ndigits number of digits in a
@param[in] nbits maximum number of bits
@returns Number of digits actually set
*/
size_t mpRandomBits(DIGIT_T a[], size_t ndigits, size_t nbits);
/* Added in [v2.4] */
/** Generate array of random octets (bytes) using internal RNG
* @remarks This function is in the correct form for BD_RANDFUNC to use in bdRandomSeeded().
* \c seed is ignored. */
int mpRandomOctets(unsigned char *bytes, size_t nbytes, const unsigned char *seed, size_t seedlen);
#ifdef __cplusplus
}
#endif
#endif /* BIGDIGITSRAND_H_ */
/* $Id: bigdigitsRand.h $ */
/** @file
Interface for BigDigits "mp" random number functions using a "pretty-good" internal RNG
*/
/***** BEGIN LICENSE BLOCK *****
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Copyright (c) 2001-16 David Ireland, D.I. Management Services Pty Limited
* <http://www.di-mgt.com.au/bigdigits.html>. All rights reserved.
*
***** END LICENSE BLOCK *****/
/*
* Last updated:
* $Date: 2016-03-31 09:51:00 $
* $Revision: 2.6.1 $
* $Author: dai $
*/
/* [v2.2] changed name from spRandom to bigdigitsRand */
#ifndef BIGDIGITSRAND_H_
#define BIGDIGITSRAND_H_ 1
#include "bigdigits.h"
#ifdef __cplusplus
extern "C" {
#endif
/** Returns a "better" pseudo-random digit using internal RNG. */
DIGIT_T spBetterRand(void);
/** Generate a random mp number of bit length at most \c nbits using internal RNG
@param[out] a to receive generated random number
@param[in] ndigits number of digits in a
@param[in] nbits maximum number of bits
@returns Number of digits actually set
*/
size_t mpRandomBits(DIGIT_T a[], size_t ndigits, size_t nbits);
/* Added in [v2.4] */
/** Generate array of random octets (bytes) using internal RNG
* @remarks This function is in the correct form for BD_RANDFUNC to use in bdRandomSeeded().
* \c seed is ignored. */
int mpRandomOctets(unsigned char *bytes, size_t nbytes, const unsigned char *seed, size_t seedlen);
#ifdef __cplusplus
}
#endif
#endif /* BIGDIGITSRAND_H_ */

View File

@@ -1,303 +1,303 @@
/* spExtras.c */
/***** BEGIN LICENSE BLOCK *****
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Copyright (c) 2001-15 David Ireland, D.I. Management Services Pty Limited
* <http://www.di-mgt.com.au/bigdigits.html>. All rights reserved.
*
***** END LICENSE BLOCK *****/
/*
* Last updated:
* $Date: 2015-10-22 10:23:00 $
* $Revision: 2.5.0 $
* $Author: dai $
*/
#include <assert.h>
#include "bigdigits.h"
#include "spExtras.h"
int spModMult(DIGIT_T *a, DIGIT_T x, DIGIT_T y, DIGIT_T m)
{ /* Computes a = (x * y) mod m */
/* Calc p[2] = x * y */
DIGIT_T p[2];
spMultiply(p, x, y);
/* Then modulo */
*a = mpShortMod(p, m, 2);
return 0;
}
DIGIT_T spGcd_old(DIGIT_T x, DIGIT_T y)
{ /* Returns gcd(x, y) */
/* Ref: Schneier 2nd ed, p245 */
DIGIT_T g;
if (x + y == 0)
return 0; /* Error */
g = y;
while (x > 0)
{
g = x;
x = y % x;
y = g;
}
return g;
}
DIGIT_T spGcd(DIGIT_T a, DIGIT_T b)
{ /* Returns gcd(a, b) */
/* Ref: Cohen, Algorithm 1.3.5 (Binary GCD)
and Menezes, Algorithm 14.54 */
DIGIT_T r, t;
unsigned int k;
/* 1. [Reduce size once] */
if (a < b)
{ /* exchange a and b */
t = a;
a = b;
b = t;
}
if (0 == b)
{
return a;
}
r = a % b;
a = b;
b = r;
if (0 == b)
{
return a;
}
/* 2. [Compute power of 2] */
k = 0;
while (ISEVEN(a) && ISEVEN(b))
{
a >>= 1; /* a <-- a/2 */
b >>= 1; /* b <-- b/2 */
k++; /* g <-- 2g */
}
while (a != 0)
{
while (ISEVEN(a))
{
a >>= 1; /* a <-- a/2 until a is odd */
}
while (ISEVEN(b))
{
b >>= 1; /* b <-- a/2 until b is odd */
}
/* t <-- |a-b|/2 */
if (b > a)
t = (b - a) >> 1;
else
t = (a - b) >> 1;
/* If a >= b then a = t, otherwise b = t */
if (a >= b)
a = t;
else
b = t;
}
/* Output (2^k.b) */
return (b << k);
}
/* spIsPrime */
static DIGIT_T SMALL_PRIMES[] = { 2, 3, 5, 7, 11, 13, 17, 19 };
#define N_SMALL_PRIMES sizeof(SMALL_PRIMES)/sizeof(DIGIT_T)
int spIsPrime(DIGIT_T w, size_t t)
{ /* Returns true if w is a probable prime
Carries out t iterations
(Use t = 50 for DSS Standard)
*/
/* Uses Rabin-Miller Probabilistic Primality Test,
Ref: FIPS-186-2 Appendix 2.
Also Schneier 2nd ed p 260 & Knuth Vol 2, p 379
and ANSI 9.42-2003 Annex B.1.1.
*/
unsigned int i, j;
DIGIT_T m, a, b, z;
int failed;
/* First check for small primes */
for (i = 0; i < N_SMALL_PRIMES; i++)
{
if (w % SMALL_PRIMES[i] == 0)
return 0; /* Failed */
}
/* Now do Rabin-Miller */
/* Step 2. Find a and m where w = 1 + (2^a)m
m is odd and 2^a is largest power of 2 dividing w - 1 */
m = w - 1;
for (a = 0; ISEVEN(m); a++)
m >>= 1; /* Divide by 2 until m is odd */
/*
assert((1 << a) * m + 1 == w);
*/
for (i = 0; i < t; i++)
{
failed = 1; /* Assume fail unless passed in loop */
/* Step 3. Generate a random integer 1 < b < w */
/* [v2.1] changed to 1 < b < w-1 */
b = spSimpleRand(2, w - 2);
/*
assert(1 < b && b < w-1);
*/
/* Step 4. Set j = 0 and z = b^m mod w */
j = 0;
spModExp(&z, b, m, w);
do
{
/* Step 5. If j = 0 and z = 1, or if z = w - 1 */
if ((j == 0 && z == 1) || (z == w - 1))
{ /* Passes on this loop - go to Step 9 */
failed = 0;
break;
}
/* Step 6. If j > 0 and z = 1 */
if (j > 0 && z == 1)
{ /* Fails - go to Step 8 */
failed = 1;
break;
}
/* Step 7. j = j + 1. If j < a set z = z^2 mod w */
j++;
if (j < a)
spModMult(&z, z, z, w);
/* Loop: if j < a go to Step 5 */
} while (j < a);
if (failed)
{ /* Step 8. Not a prime - stop */
return 0;
}
} /* Step 9. Go to Step 3 until i >= n */
/* If got here, probably prime => success */
return 1;
}
/* spModExp */
/* Two alternative functions for spModExp */
int spModExpK(DIGIT_T *exp, DIGIT_T x,
DIGIT_T n, DIGIT_T d)
{ /* Computes exp = x^n mod d */
/* Ref: Knuth Vol 2 Ch 4.6.3 p 462 Algorithm A
*/
DIGIT_T y = 1; /* Step A1. Initialise */
while (n > 0)
{ /* Step A2. Halve N */
if (n & 0x1) /* If odd */
spModMult(&y, y, x, d); /* Step A3. Multiply Y by Z */
n >>= 1; /* Halve N */
if (n > 0) /* Step A4. N = 0? Y is answer */
spModMult(&x, x, x, d); /* Step A5. Square Z */
}
*exp = y;
return 0;
}
int spModExpB(DIGIT_T *exp, DIGIT_T x,
DIGIT_T e, DIGIT_T m)
{ /* Computes exp = x^e mod m */
/* Binary left-to-right method
*/
DIGIT_T mask;
DIGIT_T y; /* Temp variable */
/* Find most significant bit in e */
for (mask = HIBITMASK; mask > 0; mask >>= 1)
{
if (e & mask)
break;
}
y = x;
/* For j = k-2 downto 0 step -1 */
for (mask >>= 1; mask > 0; mask >>= 1)
{
spModMult(&y, y, y, m); /* Square */
if (e & mask)
spModMult(&y, y, x, m); /* Multiply */
}
*exp = y;
return 0;
}
int spModInv(DIGIT_T *inv, DIGIT_T u, DIGIT_T v)
{ /* Computes inv = u^(-1) mod v */
/* Ref: Knuth Algorithm X Vol 2 p 342
ignoring u2, v2, t2
and avoiding negative numbers
*/
DIGIT_T u1, u3, v1, v3, t1, t3, q, w;
int bIterations = 1;
int result;
/* Step X1. Initialise */
u1 = 1;
u3 = u;
v1 = 0;
v3 = v;
while (v3 != 0) /* Step X2. */
{ /* Step X3. */
q = u3 / v3; /* Divide and */
t3 = u3 % v3;
w = q * v1; /* "Subtract" */
t1 = u1 + w;
/* Swap */
u1 = v1;
v1 = t1;
u3 = v3;
v3 = t3;
bIterations = -bIterations;
}
if (bIterations < 0)
*inv = v - u1;
else
*inv = u1;
/* Make sure u3 = gcd(u,v) == 1 */
if (u3 != 1)
{
result = 1;
*inv = 0;
}
else
result = 0;
return result;
}
/* spExtras.c */
/***** BEGIN LICENSE BLOCK *****
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Copyright (c) 2001-15 David Ireland, D.I. Management Services Pty Limited
* <http://www.di-mgt.com.au/bigdigits.html>. All rights reserved.
*
***** END LICENSE BLOCK *****/
/*
* Last updated:
* $Date: 2015-10-22 10:23:00 $
* $Revision: 2.5.0 $
* $Author: dai $
*/
#include <assert.h>
#include "bigdigits.h"
#include "spExtras.h"
int spModMult(DIGIT_T *a, DIGIT_T x, DIGIT_T y, DIGIT_T m)
{ /* Computes a = (x * y) mod m */
/* Calc p[2] = x * y */
DIGIT_T p[2];
spMultiply(p, x, y);
/* Then modulo */
*a = mpShortMod(p, m, 2);
return 0;
}
DIGIT_T spGcd_old(DIGIT_T x, DIGIT_T y)
{ /* Returns gcd(x, y) */
/* Ref: Schneier 2nd ed, p245 */
DIGIT_T g;
if (x + y == 0)
return 0; /* Error */
g = y;
while (x > 0)
{
g = x;
x = y % x;
y = g;
}
return g;
}
DIGIT_T spGcd(DIGIT_T a, DIGIT_T b)
{ /* Returns gcd(a, b) */
/* Ref: Cohen, Algorithm 1.3.5 (Binary GCD)
and Menezes, Algorithm 14.54 */
DIGIT_T r, t;
unsigned int k;
/* 1. [Reduce size once] */
if (a < b)
{ /* exchange a and b */
t = a;
a = b;
b = t;
}
if (0 == b)
{
return a;
}
r = a % b;
a = b;
b = r;
if (0 == b)
{
return a;
}
/* 2. [Compute power of 2] */
k = 0;
while (ISEVEN(a) && ISEVEN(b))
{
a >>= 1; /* a <-- a/2 */
b >>= 1; /* b <-- b/2 */
k++; /* g <-- 2g */
}
while (a != 0)
{
while (ISEVEN(a))
{
a >>= 1; /* a <-- a/2 until a is odd */
}
while (ISEVEN(b))
{
b >>= 1; /* b <-- a/2 until b is odd */
}
/* t <-- |a-b|/2 */
if (b > a)
t = (b - a) >> 1;
else
t = (a - b) >> 1;
/* If a >= b then a = t, otherwise b = t */
if (a >= b)
a = t;
else
b = t;
}
/* Output (2^k.b) */
return (b << k);
}
/* spIsPrime */
static DIGIT_T SMALL_PRIMES[] = { 2, 3, 5, 7, 11, 13, 17, 19 };
#define N_SMALL_PRIMES sizeof(SMALL_PRIMES)/sizeof(DIGIT_T)
int spIsPrime(DIGIT_T w, size_t t)
{ /* Returns true if w is a probable prime
Carries out t iterations
(Use t = 50 for DSS Standard)
*/
/* Uses Rabin-Miller Probabilistic Primality Test,
Ref: FIPS-186-2 Appendix 2.
Also Schneier 2nd ed p 260 & Knuth Vol 2, p 379
and ANSI 9.42-2003 Annex B.1.1.
*/
unsigned int i, j;
DIGIT_T m, a, b, z;
int failed;
/* First check for small primes */
for (i = 0; i < N_SMALL_PRIMES; i++)
{
if (w % SMALL_PRIMES[i] == 0)
return 0; /* Failed */
}
/* Now do Rabin-Miller */
/* Step 2. Find a and m where w = 1 + (2^a)m
m is odd and 2^a is largest power of 2 dividing w - 1 */
m = w - 1;
for (a = 0; ISEVEN(m); a++)
m >>= 1; /* Divide by 2 until m is odd */
/*
assert((1 << a) * m + 1 == w);
*/
for (i = 0; i < t; i++)
{
failed = 1; /* Assume fail unless passed in loop */
/* Step 3. Generate a random integer 1 < b < w */
/* [v2.1] changed to 1 < b < w-1 */
b = spSimpleRand(2, w - 2);
/*
assert(1 < b && b < w-1);
*/
/* Step 4. Set j = 0 and z = b^m mod w */
j = 0;
spModExp(&z, b, m, w);
do
{
/* Step 5. If j = 0 and z = 1, or if z = w - 1 */
if ((j == 0 && z == 1) || (z == w - 1))
{ /* Passes on this loop - go to Step 9 */
failed = 0;
break;
}
/* Step 6. If j > 0 and z = 1 */
if (j > 0 && z == 1)
{ /* Fails - go to Step 8 */
failed = 1;
break;
}
/* Step 7. j = j + 1. If j < a set z = z^2 mod w */
j++;
if (j < a)
spModMult(&z, z, z, w);
/* Loop: if j < a go to Step 5 */
} while (j < a);
if (failed)
{ /* Step 8. Not a prime - stop */
return 0;
}
} /* Step 9. Go to Step 3 until i >= n */
/* If got here, probably prime => success */
return 1;
}
/* spModExp */
/* Two alternative functions for spModExp */
int spModExpK(DIGIT_T *exp, DIGIT_T x,
DIGIT_T n, DIGIT_T d)
{ /* Computes exp = x^n mod d */
/* Ref: Knuth Vol 2 Ch 4.6.3 p 462 Algorithm A
*/
DIGIT_T y = 1; /* Step A1. Initialise */
while (n > 0)
{ /* Step A2. Halve N */
if (n & 0x1) /* If odd */
spModMult(&y, y, x, d); /* Step A3. Multiply Y by Z */
n >>= 1; /* Halve N */
if (n > 0) /* Step A4. N = 0? Y is answer */
spModMult(&x, x, x, d); /* Step A5. Square Z */
}
*exp = y;
return 0;
}
int spModExpB(DIGIT_T *exp, DIGIT_T x,
DIGIT_T e, DIGIT_T m)
{ /* Computes exp = x^e mod m */
/* Binary left-to-right method
*/
DIGIT_T mask;
DIGIT_T y; /* Temp variable */
/* Find most significant bit in e */
for (mask = HIBITMASK; mask > 0; mask >>= 1)
{
if (e & mask)
break;
}
y = x;
/* For j = k-2 downto 0 step -1 */
for (mask >>= 1; mask > 0; mask >>= 1)
{
spModMult(&y, y, y, m); /* Square */
if (e & mask)
spModMult(&y, y, x, m); /* Multiply */
}
*exp = y;
return 0;
}
int spModInv(DIGIT_T *inv, DIGIT_T u, DIGIT_T v)
{ /* Computes inv = u^(-1) mod v */
/* Ref: Knuth Algorithm X Vol 2 p 342
ignoring u2, v2, t2
and avoiding negative numbers
*/
DIGIT_T u1, u3, v1, v3, t1, t3, q, w;
int bIterations = 1;
int result;
/* Step X1. Initialise */
u1 = 1;
u3 = u;
v1 = 0;
v3 = v;
while (v3 != 0) /* Step X2. */
{ /* Step X3. */
q = u3 / v3; /* Divide and */
t3 = u3 % v3;
w = q * v1; /* "Subtract" */
t1 = u1 + w;
/* Swap */
u1 = v1;
v1 = t1;
u3 = v3;
v3 = t3;
bIterations = -bIterations;
}
if (bIterations < 0)
*inv = v - u1;
else
*inv = u1;
/* Make sure u3 = gcd(u,v) == 1 */
if (u3 != 1)
{
result = 1;
*inv = 0;
}
else
result = 0;
return result;
}

View File

@@ -1,55 +1,55 @@
/* spExtras.h */
/***** BEGIN LICENSE BLOCK *****
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Copyright (c) 2001-15 David Ireland, D.I. Management Services Pty Limited
* <http://www.di-mgt.com.au/bigdigits.html>. All rights reserved.
*
***** END LICENSE BLOCK *****/
/*
* Last updated:
* $Date: 2015-10-22 10:23:00 $
* $Revision: 2.5.0 $
* $Author: dai $
*/
/* Interface to extra BigDigits "sp" functions that operate with single digits */
#ifndef SPEXTRAS_H_
#define SPEXTRAS_H_ 1
#include "bigdigits.h"
int spModMult(DIGIT_T *a, DIGIT_T x, DIGIT_T y, DIGIT_T m);
/* Computes a = (x * y) mod m */
int spModInv(DIGIT_T *inv, DIGIT_T u, DIGIT_T v);
/* Computes inv = u^-1 mod v */
DIGIT_T spGcd(DIGIT_T x, DIGIT_T y);
/* Returns gcd(x, y) */
int spIsPrime(DIGIT_T w, size_t t);
/* Returns true if w is a probable prime, else false; t tests */
/* int spModExp(DIGIT_T *exp, DIGIT_T x, DIGIT_T n, DIGIT_T d); */
/* Computes exp = x^n mod d */
/* Two alternatives for spModExp:
define USE_KNUTH_MODEXP before <spExtras.h> to use Knuth method,
otherwise defaults to use Binary left-to-right method */
#ifdef USE_KNUTH_MODEXP
#define spModExp spModExpK
#else
#define spModExp spModExpB
#endif /* USE_KNUTH_MODEXP */
int spModExpK(DIGIT_T *exp, DIGIT_T x, DIGIT_T n, DIGIT_T d);
int spModExpB(DIGIT_T *exp, DIGIT_T x, DIGIT_T n, DIGIT_T d);
#endif /* SPEXTRAS_H_ */
/* spExtras.h */
/***** BEGIN LICENSE BLOCK *****
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Copyright (c) 2001-15 David Ireland, D.I. Management Services Pty Limited
* <http://www.di-mgt.com.au/bigdigits.html>. All rights reserved.
*
***** END LICENSE BLOCK *****/
/*
* Last updated:
* $Date: 2015-10-22 10:23:00 $
* $Revision: 2.5.0 $
* $Author: dai $
*/
/* Interface to extra BigDigits "sp" functions that operate with single digits */
#ifndef SPEXTRAS_H_
#define SPEXTRAS_H_ 1
#include "bigdigits.h"
int spModMult(DIGIT_T *a, DIGIT_T x, DIGIT_T y, DIGIT_T m);
/* Computes a = (x * y) mod m */
int spModInv(DIGIT_T *inv, DIGIT_T u, DIGIT_T v);
/* Computes inv = u^-1 mod v */
DIGIT_T spGcd(DIGIT_T x, DIGIT_T y);
/* Returns gcd(x, y) */
int spIsPrime(DIGIT_T w, size_t t);
/* Returns true if w is a probable prime, else false; t tests */
/* int spModExp(DIGIT_T *exp, DIGIT_T x, DIGIT_T n, DIGIT_T d); */
/* Computes exp = x^n mod d */
/* Two alternatives for spModExp:
define USE_KNUTH_MODEXP before <spExtras.h> to use Knuth method,
otherwise defaults to use Binary left-to-right method */
#ifdef USE_KNUTH_MODEXP
#define spModExp spModExpK
#else
#define spModExp spModExpB
#endif /* USE_KNUTH_MODEXP */
int spModExpK(DIGIT_T *exp, DIGIT_T x, DIGIT_T n, DIGIT_T d);
int spModExpB(DIGIT_T *exp, DIGIT_T x, DIGIT_T n, DIGIT_T d);
#endif /* SPEXTRAS_H_ */

View File

@@ -1,75 +1,75 @@
/* $Id: t_bdCPP.c $ */
/***** BEGIN LICENSE BLOCK *****
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Copyright (c) 2001-15 David Ireland, D.I. Management Services Pty Limited
* <http://www.di-mgt.com.au/bigdigits.html>. All rights reserved.
*
***** END LICENSE BLOCK *****/
/*
* Last updated:
* $Date: 2015-10-22 10:23:00 $
* $Revision: 2.5.0 $
* $Author: dai $
*/
#include "bigd.h"
#include "bigdRand.h"
#include <iostream>
using namespace std;
int main()
{
int ver;
ver = bdVersion();
cout << "bdVersion = " << ver << "\n";
BIGD u, v, w;
/* Create new BIGD objects */
u = bdNew();
v = bdNew();
w = bdNew();
/* Compute 2 * 0xdeadbeefface */
bdSetShort(u, 2);
bdConvFromHex(v, "deadbeefface");
bdMultiply(w, u, v);
/* Display the result */
bdPrintHex("", u, " * ");
bdPrintHex("0x", v, " = ");
bdPrintHex("0x", w, "\n");
/* and again in decimal format */
bdPrintDecimal("", u, " * ");
bdPrintDecimal("", v, " = ");
bdPrintDecimal("", w, "\n");
/* Add with digit overflow */
/* ffffffff+ffffffff=00000001 fffffffe */
bdSetShort(u, 0xffffffff);
bdSetShort(v, 0xffffffff);
bdAdd(w, u, v);
bdPrintHex("", u, "+");
bdPrintHex("", v, "=");
bdPrintHex("", w, "\n");
/* Generate some random digits using internal RNG */
cout << "Some random numbers:\n";
bdSetShort(u, bdRandDigit());
bdPrintHex("short: ", u, "\n");
bdRandomBits(u, 512);
bdPrintHex("512 bits: ", u, "\n");
/* Free all objects we made */
bdFree(&u);
bdFree(&v);
bdFree(&w);
return 0;
}
/* $Id: t_bdCPP.c $ */
/***** BEGIN LICENSE BLOCK *****
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Copyright (c) 2001-15 David Ireland, D.I. Management Services Pty Limited
* <http://www.di-mgt.com.au/bigdigits.html>. All rights reserved.
*
***** END LICENSE BLOCK *****/
/*
* Last updated:
* $Date: 2015-10-22 10:23:00 $
* $Revision: 2.5.0 $
* $Author: dai $
*/
#include "bigd.h"
#include "bigdRand.h"
#include <iostream>
using namespace std;
int main()
{
int ver;
ver = bdVersion();
cout << "bdVersion = " << ver << "\n";
BIGD u, v, w;
/* Create new BIGD objects */
u = bdNew();
v = bdNew();
w = bdNew();
/* Compute 2 * 0xdeadbeefface */
bdSetShort(u, 2);
bdConvFromHex(v, "deadbeefface");
bdMultiply(w, u, v);
/* Display the result */
bdPrintHex("", u, " * ");
bdPrintHex("0x", v, " = ");
bdPrintHex("0x", w, "\n");
/* and again in decimal format */
bdPrintDecimal("", u, " * ");
bdPrintDecimal("", v, " = ");
bdPrintDecimal("", w, "\n");
/* Add with digit overflow */
/* ffffffff+ffffffff=00000001 fffffffe */
bdSetShort(u, 0xffffffff);
bdSetShort(v, 0xffffffff);
bdAdd(w, u, v);
bdPrintHex("", u, "+");
bdPrintHex("", v, "=");
bdPrintHex("", w, "\n");
/* Generate some random digits using internal RNG */
cout << "Some random numbers:\n";
bdSetShort(u, bdRandDigit());
bdPrintHex("short: ", u, "\n");
bdRandomBits(u, 512);
bdPrintHex("512 bits: ", u, "\n");
/* Free all objects we made */
bdFree(&u);
bdFree(&v);
bdFree(&w);
return 0;
}

View File

@@ -1,182 +1,182 @@
/* $Id: t_bdDSA.c $ */
/***** BEGIN LICENSE BLOCK *****
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Copyright (c) 2001-15 David Ireland, D.I. Management Services Pty Limited
* <http://www.di-mgt.com.au/bigdigits.html>. All rights reserved.
*
***** END LICENSE BLOCK *****/
/*
* Last updated:
* $Date: 2015-10-22 10:23:00 $
* $Revision: 2.5.0 $
* $Author: dai $
*/
/* EXAMPLE OF THE DSA from APPENDIX 5 FIPS PUB 186-2
"DIGITAL SIGNATURE STANDARD (DSS)", 27 January 2000 */
#if _MSC_VER >= 1100
/* Detect memory leaks in MSVC++ */
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#else
#include <stdlib.h>
#endif
#include <stdio.h>
#include <assert.h>
#include "bigd.h"
int main(void)
{
BIGD p, q, g;
BIGD x, k;
BIGD hashm;
BIGD k1, y, tmp;
BIGD r, s;
BIGD w, u1, u2, v, gg, yy;
/* MSVC memory leak checking stuff */
#if _MSC_VER >= 1100
_CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
_CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_FILE );
_CrtSetReportFile( _CRT_WARN, _CRTDBG_FILE_STDOUT );
_CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_FILE );
_CrtSetReportFile( _CRT_ERROR, _CRTDBG_FILE_STDOUT );
_CrtSetReportMode( _CRT_ASSERT, _CRTDBG_MODE_FILE );
_CrtSetReportFile( _CRT_ASSERT, _CRTDBG_FILE_STDOUT );
#endif
printf("EXAMPLE OF THE DSA from APPENDIX 5 FIPS PUB 186-2 'DIGITAL SIGNATURE STANDARD'\n");
/* Initialise variables */
p = bdNew();
q = bdNew();
g = bdNew();
x = bdNew();
k = bdNew();
k1 = bdNew();
y = bdNew();
tmp = bdNew();
hashm= bdNew();
r= bdNew();
s= bdNew();
w = bdNew();
u1 = bdNew();
u2 = bdNew();
v = bdNew();
gg = bdNew();
yy = bdNew();
/* INPUT */
/* Convert integers from hex format to BIGD (spaces are ignored) */
bdConvFromHex(p, "8df2a494 492276aa 3d25759b b06869cb eac0d83a fb8d0cf7"
"cbb8324f 0d7882e5 d0762fc5 b7210eaf c2e9adac 32ab7aac"
"49693dfb f83724c2 ec0736ee 31c80291");
bdConvFromHex(q, "c773218c 737ec8ee 993b4f2d ed30f48e dace915f");
bdConvFromHex(g, "626d0278 39ea0a13 413163a5 5b4cb500 299d5522 956cefcb"
"3bff10f3 99ce2c2e 71cb9de5 fa24babf 58e5b795 21925c9c"
"c42e9f6f 464b088c c572af53 e6d78802");
bdConvFromHex(x, "2070b322 3dba372f de1c0ffc 7b2e3b49 8b260614");
bdConvFromHex(k, "358dad57 1462710f 50e254cf 1a376b2b deaadfbf");
/* M = ASCII form of "abc" (See FIPS PUB 180-1, Appendix A)
(SHA-1)(M) = <pre-computed value> */
bdConvFromHex(hashm, "a9993e36 4706816a ba3e2571 7850c26c 9cd0d89d");
bdPrintHex("p=", p, "\n");
bdPrintHex("q=", q, "\n");
bdPrintHex("g=", g, "\n");
bdPrintHex("x=", x, "\n");
bdPrintHex("k=", k, "\n");
bdPrintHex("SHA-1(M)=", hashm, "\n");
/* COMPUTATION BY SIGNER */
/* (p, q, g) are public, common values
x is signer's private key
k is a random integer 0 < k < q
Keep (x, k) secret
*/
/* Compute k' = k^-1 mod q */
bdModInv(k1, k, q);
bdPrintHex("k^-1=", k1, "\n");
/* Compute y = g^x mod p */
bdModExp(y, g, x, p);
bdPrintHex("y=", y, "\n");
/* Compute r = (g^k mod p) mod q */
bdModExp(tmp, g, k, p);
bdModulo(r, tmp, q);
bdPrintHex("r=", r, "\n");
/* Compute s = (k^-1(SHA-1(M) + xr)) mod q */
bdModMult(tmp, x, r, q);
bdAdd(tmp, tmp, hashm);
bdModMult(s, k1, tmp, q);
bdPrintHex("s=", s, "\n");
/* VERIFICATION BY RECEIVER */
/* (p, q, g) are public, common values
y is signer's public key
(r,s) = signature(M)
Receiver receives (M', r', s').
Receiver recomputes SHA-1(M') for received message M'
*/
/* Check 0 < r' < q and 0 < s' < q */
assert(bdCompare(q, r) > 0);
assert(bdCompare(q, s) > 0);
/* Compute w = s^-1 mod q */
bdModInv(w, s, q);
bdPrintHex("w=", w, "\n");
/* Compute u1 = ((SHA-1(M'))w) mod q */
bdModMult(u1, hashm, w, q);
bdPrintHex("u1=", u1, "\n");
/* Compute u2 = ((r')w) mod q */
bdModMult(u2, r, w, q);
bdPrintHex("u2=", u2, "\n");
/* Compute g^u1 mod p */
bdModExp(gg, g, u1, p);
bdPrintHex("g^u1 mod p=\n", gg, "\n");
/* Compute y^u2 mod p */
bdModExp(yy, y, u2, p);
bdPrintHex("y^u2 mod p=\n", yy, "\n");
/* Compute v = (((g^u1)(y^u2)) mod p) mod q */
bdModMult(tmp, gg, yy, p);
bdModulo(v, tmp, q);
bdPrintHex("v=", v, "\n");
/* Verify that v = r' */
if (bdIsEqual(v, r))
printf("Signature verified OK\n");
else
printf("Signature verification FAILED!\n");
assert(bdIsEqual(v, r));
/* Clean up */
bdFree(&p);
bdFree(&q);
bdFree(&g);
bdFree(&x);
bdFree(&k);
bdFree(&k1);
bdFree(&y);
bdFree(&tmp);
bdFree(&hashm);
bdFree(&r);
bdFree(&s);
bdFree(&w);
bdFree(&u1);
bdFree(&u2);
bdFree(&v);
bdFree(&gg);
bdFree(&yy);
printf("OK, successfully completed tests.\n");
return 0;
}
/* $Id: t_bdDSA.c $ */
/***** BEGIN LICENSE BLOCK *****
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Copyright (c) 2001-15 David Ireland, D.I. Management Services Pty Limited
* <http://www.di-mgt.com.au/bigdigits.html>. All rights reserved.
*
***** END LICENSE BLOCK *****/
/*
* Last updated:
* $Date: 2015-10-22 10:23:00 $
* $Revision: 2.5.0 $
* $Author: dai $
*/
/* EXAMPLE OF THE DSA from APPENDIX 5 FIPS PUB 186-2
"DIGITAL SIGNATURE STANDARD (DSS)", 27 January 2000 */
#if _MSC_VER >= 1100
/* Detect memory leaks in MSVC++ */
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#else
#include <stdlib.h>
#endif
#include <stdio.h>
#include <assert.h>
#include "bigd.h"
int main(void)
{
BIGD p, q, g;
BIGD x, k;
BIGD hashm;
BIGD k1, y, tmp;
BIGD r, s;
BIGD w, u1, u2, v, gg, yy;
/* MSVC memory leak checking stuff */
#if _MSC_VER >= 1100
_CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
_CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_FILE );
_CrtSetReportFile( _CRT_WARN, _CRTDBG_FILE_STDOUT );
_CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_FILE );
_CrtSetReportFile( _CRT_ERROR, _CRTDBG_FILE_STDOUT );
_CrtSetReportMode( _CRT_ASSERT, _CRTDBG_MODE_FILE );
_CrtSetReportFile( _CRT_ASSERT, _CRTDBG_FILE_STDOUT );
#endif
printf("EXAMPLE OF THE DSA from APPENDIX 5 FIPS PUB 186-2 'DIGITAL SIGNATURE STANDARD'\n");
/* Initialise variables */
p = bdNew();
q = bdNew();
g = bdNew();
x = bdNew();
k = bdNew();
k1 = bdNew();
y = bdNew();
tmp = bdNew();
hashm= bdNew();
r= bdNew();
s= bdNew();
w = bdNew();
u1 = bdNew();
u2 = bdNew();
v = bdNew();
gg = bdNew();
yy = bdNew();
/* INPUT */
/* Convert integers from hex format to BIGD (spaces are ignored) */
bdConvFromHex(p, "8df2a494 492276aa 3d25759b b06869cb eac0d83a fb8d0cf7"
"cbb8324f 0d7882e5 d0762fc5 b7210eaf c2e9adac 32ab7aac"
"49693dfb f83724c2 ec0736ee 31c80291");
bdConvFromHex(q, "c773218c 737ec8ee 993b4f2d ed30f48e dace915f");
bdConvFromHex(g, "626d0278 39ea0a13 413163a5 5b4cb500 299d5522 956cefcb"
"3bff10f3 99ce2c2e 71cb9de5 fa24babf 58e5b795 21925c9c"
"c42e9f6f 464b088c c572af53 e6d78802");
bdConvFromHex(x, "2070b322 3dba372f de1c0ffc 7b2e3b49 8b260614");
bdConvFromHex(k, "358dad57 1462710f 50e254cf 1a376b2b deaadfbf");
/* M = ASCII form of "abc" (See FIPS PUB 180-1, Appendix A)
(SHA-1)(M) = <pre-computed value> */
bdConvFromHex(hashm, "a9993e36 4706816a ba3e2571 7850c26c 9cd0d89d");
bdPrintHex("p=", p, "\n");
bdPrintHex("q=", q, "\n");
bdPrintHex("g=", g, "\n");
bdPrintHex("x=", x, "\n");
bdPrintHex("k=", k, "\n");
bdPrintHex("SHA-1(M)=", hashm, "\n");
/* COMPUTATION BY SIGNER */
/* (p, q, g) are public, common values
x is signer's private key
k is a random integer 0 < k < q
Keep (x, k) secret
*/
/* Compute k' = k^-1 mod q */
bdModInv(k1, k, q);
bdPrintHex("k^-1=", k1, "\n");
/* Compute y = g^x mod p */
bdModExp(y, g, x, p);
bdPrintHex("y=", y, "\n");
/* Compute r = (g^k mod p) mod q */
bdModExp(tmp, g, k, p);
bdModulo(r, tmp, q);
bdPrintHex("r=", r, "\n");
/* Compute s = (k^-1(SHA-1(M) + xr)) mod q */
bdModMult(tmp, x, r, q);
bdAdd(tmp, tmp, hashm);
bdModMult(s, k1, tmp, q);
bdPrintHex("s=", s, "\n");
/* VERIFICATION BY RECEIVER */
/* (p, q, g) are public, common values
y is signer's public key
(r,s) = signature(M)
Receiver receives (M', r', s').
Receiver recomputes SHA-1(M') for received message M'
*/
/* Check 0 < r' < q and 0 < s' < q */
assert(bdCompare(q, r) > 0);
assert(bdCompare(q, s) > 0);
/* Compute w = s^-1 mod q */
bdModInv(w, s, q);
bdPrintHex("w=", w, "\n");
/* Compute u1 = ((SHA-1(M'))w) mod q */
bdModMult(u1, hashm, w, q);
bdPrintHex("u1=", u1, "\n");
/* Compute u2 = ((r')w) mod q */
bdModMult(u2, r, w, q);
bdPrintHex("u2=", u2, "\n");
/* Compute g^u1 mod p */
bdModExp(gg, g, u1, p);
bdPrintHex("g^u1 mod p=\n", gg, "\n");
/* Compute y^u2 mod p */
bdModExp(yy, y, u2, p);
bdPrintHex("y^u2 mod p=\n", yy, "\n");
/* Compute v = (((g^u1)(y^u2)) mod p) mod q */
bdModMult(tmp, gg, yy, p);
bdModulo(v, tmp, q);
bdPrintHex("v=", v, "\n");
/* Verify that v = r' */
if (bdIsEqual(v, r))
printf("Signature verified OK\n");
else
printf("Signature verification FAILED!\n");
assert(bdIsEqual(v, r));
/* Clean up */
bdFree(&p);
bdFree(&q);
bdFree(&g);
bdFree(&x);
bdFree(&k);
bdFree(&k1);
bdFree(&y);
bdFree(&tmp);
bdFree(&hashm);
bdFree(&r);
bdFree(&s);
bdFree(&w);
bdFree(&u1);
bdFree(&u2);
bdFree(&v);
bdFree(&gg);
bdFree(&yy);
printf("OK, successfully completed tests.\n");
return 0;
}

View File

@@ -1,65 +1,65 @@
/* $Id: t_bdQuickRandBits.c $ */
/* $Id: t_bdQuickRandBits.c $ */
/***** BEGIN LICENSE BLOCK *****
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Copyright (c) 2001-16 David Ireland, D.I. Management Services Pty Limited
* <http://www.di-mgt.com.au/bigdigits.html>. All rights reserved.
*
***** END LICENSE BLOCK *****/
/*
* Last updated:
* $Date: 2016-03-31 09:51:00 $
* $Revision: 2.6.1 $
* $Author: dai $
*/
/*
What is the difference between bdQuickRandBits and bdRandomBits?
bdRandomBits() uses the "pretty-good" internal RNG and requires you to include bigdRand.h
and compile with bigdRand.c and bigdigitsRand.c.
You can be pretty sure that the numbers generated will pass all statistical tests for randomness.
bdQuickRandBits() just needs the standard bigd.h include file and you do not need to
add the modules bigdRand.c and bigdigitsRand.c to your project.
It uses the stdlib rand() function, which is by no means secure, but it will quickly fill up a number
with the required number of random-looking bits.
It might repeat if you call twice in quick succession. It's quick and dirty, as advertised.
If you *really* want a secure random number, then use bdRandomSeeded() and call your own super-secure
random number generator, throwing in your own bit of extra entropy with the seed.
*/
#include <stdio.h>
#include <assert.h>
#include "bigd.h"
#include "bigdRand.h"
int main(void)
{
BIGD a;
int i;
/***** BEGIN LICENSE BLOCK *****
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Copyright (c) 2001-16 David Ireland, D.I. Management Services Pty Limited
* <http://www.di-mgt.com.au/bigdigits.html>. All rights reserved.
*
***** END LICENSE BLOCK *****/
/*
* Last updated:
* $Date: 2016-03-31 09:51:00 $
* $Revision: 2.6.1 $
* $Author: dai $
*/
/*
What is the difference between bdQuickRandBits and bdRandomBits?
bdRandomBits() uses the "pretty-good" internal RNG and requires you to include bigdRand.h
and compile with bigdRand.c and bigdigitsRand.c.
You can be pretty sure that the numbers generated will pass all statistical tests for randomness.
bdQuickRandBits() just needs the standard bigd.h include file and you do not need to
add the modules bigdRand.c and bigdigitsRand.c to your project.
It uses the stdlib rand() function, which is by no means secure, but it will quickly fill up a number
with the required number of random-looking bits.
It might repeat if you call twice in quick succession. It's quick and dirty, as advertised.
If you *really* want a secure random number, then use bdRandomSeeded() and call your own super-secure
random number generator, throwing in your own bit of extra entropy with the seed.
*/
#include <stdio.h>
#include <assert.h>
#include "bigd.h"
#include "bigdRand.h"
int main(void)
{
BIGD a;
int i;
a = bdNew();
// Test bdQuickRandBits (quick-and-dirty)
printf("Testing bdQuickRandBits...\n");
for (i = 0; i < 10; i++)
{
bdQuickRandBits(a, 128);
bdPrintHex("", a, "\n");
}
// Test bdRandomBits (more secure)
printf("Testing bdRandomBits...\n");
for (i = 0; i < 10; i++)
{
bdRandomBits(a, 128);
bdPrintHex("", a, "\n");
}
return 0;
}
a = bdNew();
// Test bdQuickRandBits (quick-and-dirty)
printf("Testing bdQuickRandBits...\n");
for (i = 0; i < 10; i++)
{
bdQuickRandBits(a, 128);
bdPrintHex("", a, "\n");
}
// Test bdRandomBits (more secure)
printf("Testing bdRandomBits...\n");
for (i = 0; i < 10; i++)
{
bdRandomBits(a, 128);
bdPrintHex("", a, "\n");
}
return 0;
}

View File

@@ -1,220 +1,220 @@
/* $Id: t_bdRDSA.c $ */
/***** BEGIN LICENSE BLOCK *****
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Copyright (c) 2001-15 David Ireland, D.I. Management Services Pty Limited
* <http://www.di-mgt.com.au/bigdigits.html>. All rights reserved.
*
***** END LICENSE BLOCK *****/
/*
* Last updated:
* $Date: 2015-10-22 10:23:00 $
* $Revision: 2.5.0 $
* $Author: dai $
*/
/* EXAMPLE OF THE rDSA from ANSI X9.31 -1998
Digital Signatures Using Reversible Public Key
Cryptography for the Financial Services Industry (rDSA),
September 9, 1998
Appendix D.1 Odd e = 3 with 1024-bit n
and D.3 Odd e =3 with 2048-bit n
*/
#if _MSC_VER >= 1100
/* Detect memory leaks in MSVC++ */
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#else
#include <stdlib.h>
#endif
#include <stdio.h>
#include <assert.h>
#include "bigd.h"
int rDSA_SignAndVerify(BIGD ir, BIGD n, BIGD e, BIGD d)
{
BIGD s;
BIGD tmp;
BIGD rr, ir1, rr1;
int result;
/* Initialise variables */
s = bdNew();
rr = bdNew();
ir1 = bdNew();
rr1 = bdNew();
tmp = bdNew();
bdPrintHex("n=\n", n, "\n");
bdPrintHex("e=", e, "\n");
bdPrintHex("d=\n", d, "\n");
bdPrintHex("IR=\n", ir, "\n");
/* COMPUTATION BY SIGNER */
/* (n, e) is the public key
(n, d) is the private key
IR is the encoded message
Keep d secret
*/
/* For odd e, RR = IR. The value RR^d mod n is now computed */
bdModExp(tmp, ir, d, n);
bdPrintHex("RR^d mod n=\n", tmp, "\n");
/* S = min { RR^d mod n, n-(RR^d mod n) } */
/* i.e. if this value > n/2, the signature S = n - (RR^d mod n) */
bdSubtract(s, n, tmp);
if (bdCompare(s, tmp) > 0)
bdSetEqual(s, tmp);
bdPrintHex("S=\n", s, "\n");
/* D.1.3 Signature Verification */
/* The value (S')^e mod n is computed to yield RR'. */
bdModExp(rr, s, e, n);
bdPrintHex("RR'=\n", rr, "\n");
/* If RR' = 12 mod 16, then IR' = RR';
If n - RR' = 12 mod 16, then IR' = n - RR'; */
if (bdShortMod(tmp, rr, 16) == 12)
bdSetEqual(ir1, rr);
else
bdSubtract(ir1, n, rr);
bdPrintHex("IR'=\n", ir1, "\n");
/* Since IR' is identical to the computed hash IR, and the signature verification is
successful. */
result = bdIsEqual(ir1, ir);
if (result)
printf("Signature verified OK\n");
else
printf("Signature verification FAILED!\n");
/* Clean up */
bdFree(&s);
bdFree(&rr);
bdFree(&ir1);
bdFree(&rr1);
bdFree(&tmp);
return result; /* TRUE = success */
}
int main(void)
{
BIGD e, n, d;
BIGD ir;
int result;
/* MSVC memory leak checking stuff */
#if _MSC_VER >= 1100
_CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
_CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_FILE );
_CrtSetReportFile( _CRT_WARN, _CRTDBG_FILE_STDOUT );
_CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_FILE );
_CrtSetReportFile( _CRT_ERROR, _CRTDBG_FILE_STDOUT );
_CrtSetReportMode( _CRT_ASSERT, _CRTDBG_MODE_FILE );
_CrtSetReportFile( _CRT_ASSERT, _CRTDBG_FILE_STDOUT );
#endif
printf("EXAMPLE OF THE rDSA from ANSI X9.31-1998 Appendix D\n");
/* Initialise variables */
e = bdNew();
n = bdNew();
d = bdNew();
ir = bdNew();
/* INPUT */
/* Convert integers from hex format to BIGD (spaces are ignored) */
bdConvFromHex(n, "ACD1CC46 DFE54FE8 F9786672 664CA269 0D0AD7E5"
"003BC642 7954D939 EEE8B271 52E6A947 450D7FA9"
"80172DE0 64D6569A 28A83FE7 0FA840F5 E9802CB8"
"984AB34B D5C1E639 9EC21E4D 3A3A69BE 4E676F39"
"5AAFEF7C 4925FD4F AEE9F9E5 E48AF431 5DF0EC2D"
"B9AD7A35 0B3DF2F4 D15DC003 9846D1AC A3527B1A"
"75049E3F E34F43BD");
bdConvFromHex(d, "1CCDA20B CFFB8D51 7EE96668 66621B11 822C7950"
"D55F4BB5 BEE37989 A7D17312 E326718B E0D79546"
"EAAE87A5 6623B919 B1715FFB D7F16028 FC400774"
"1961C88C 5D7B4DAA AC8D36A9 8C9EFBB2 6C8A4A0E"
"6BC15B35 8E528A1A C9D0F042 BEB93BCA 16B541B3"
"3F80C933 A3B76928 5C462ED5 677BFE89 DF07BED5"
"C127FD13 241D3C4B");
bdConvFromHex(ir, "6BBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB"
"BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB"
"BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB"
"BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB"
"BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB"
"BBBBBBBB BBBAA999 3E364706 816ABA3E 25717850"
"C26C9CD0 D89D33CC");
/* Set e = 3 directly */
bdSetShort(e, 3);
result = rDSA_SignAndVerify(ir, n, e, d);
assert(result);
/* Repeat for D.3 Odd e =3 with 2048-bit n */
bdConvFromHex(n, "BCCA30CA 5280BC51 E758DBAF FEDFE46A 5D2A78D8"
"3969E154 780F9B27 AD4E76E6 3E8FA960 29C04DE3"
"F2C4B01F ECBEBB44 FC2F5F8A C69BD0E3 278FF065"
"8A6F9AC2 3BCFB2C9 AAAF1AC4 D5571A55 D3B1EC35"
"50CF34D8 F789235D D3B5C4E2 F3DF1761 19D918F2"
"D35E805B 62FC35FE E5FD0785 4824B984 6DC1665E"
"35A31873 BF6A24FE 50842D0A A0305C35 D0F45B0D"
"7C2F1E94 32D850D6 7956D383 BBEF52FC 2ACBF7AE"
"6F7CA214 88A56456 BDF66726 96EE037C 3CAA2199"
"904E37AA 40134E10 155FC813 93A225BD 129C4B3B"
"C91AD3A5 FC958A6A BCABE355 0390B677 87625D78"
"F8D3172B 673C4482 CE354B89 51D7E8C4 DDCE5D4C"
"DFA6790C 6CE8C02C 8D807AE2 6F27FE33");
bdConvFromHex(d, "7DDC2086 E1AB2836 9A3B3D1F FF3FED9C 3E1C5090"
"26469638 500A676F C8DEF9EE D45FC640 1BD58942"
"A1D8756A 9DD47CD8 A81F9507 2F128B42 1A5FF599"
"06F511D6 D28A7731 1C74BC83 38E4BC39 37CBF2CE"
"35DF7890 A5061793 E2792DEC A294BA40 BBE610A1"
"E23F003C ECA823FF 43FE0503 856DD102 F3D6443E"
"CE6CBAF7 D4F16DFD BAF7C2F8 CB4955E2 F2DF29FD"
"A7A4DD7B 93785252 E2CA4AAD 14E8B1A1 7881D381"
"DAD9061E C8AB50DD CBF8B56A FA464F01 D28DFDFF"
"0CAFF6B5 588E8F77 6FA128DE 7C102494 7D5D8067"
"3F545A5C 73FBC16B 609A33A1 1021DD8F 37A4E7C4"
"78AA19E3 BCB1BBD8 F4AA9232 65F1F1D5 5236753A"
"C8C10D60 F0FAB073 66439A90 5E2C63AB");
bdConvFromHex(ir, "6BBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB"
"BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB"
"BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB"
"BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB"
"BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB"
"BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB"
"BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB"
"BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB"
"BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB"
"BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB"
"BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB"
"BBBBBBBB BBBBBBBB BBBBBBBB BBBAA999 3E364706"
"816ABA3E 25717850 C26C9CD0 D89D33CC");
result = rDSA_SignAndVerify(ir, n, e, d);
assert(result);
/* Clean up */
bdFree(&e);
bdFree(&n);
bdFree(&d);
bdFree(&ir);
printf("OK, successfully completed tests.\n");
return 0;
}
/* $Id: t_bdRDSA.c $ */
/***** BEGIN LICENSE BLOCK *****
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Copyright (c) 2001-15 David Ireland, D.I. Management Services Pty Limited
* <http://www.di-mgt.com.au/bigdigits.html>. All rights reserved.
*
***** END LICENSE BLOCK *****/
/*
* Last updated:
* $Date: 2015-10-22 10:23:00 $
* $Revision: 2.5.0 $
* $Author: dai $
*/
/* EXAMPLE OF THE rDSA from ANSI X9.31 -1998
Digital Signatures Using Reversible Public Key
Cryptography for the Financial Services Industry (rDSA),
September 9, 1998
Appendix D.1 Odd e = 3 with 1024-bit n
and D.3 Odd e =3 with 2048-bit n
*/
#if _MSC_VER >= 1100
/* Detect memory leaks in MSVC++ */
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#else
#include <stdlib.h>
#endif
#include <stdio.h>
#include <assert.h>
#include "bigd.h"
int rDSA_SignAndVerify(BIGD ir, BIGD n, BIGD e, BIGD d)
{
BIGD s;
BIGD tmp;
BIGD rr, ir1, rr1;
int result;
/* Initialise variables */
s = bdNew();
rr = bdNew();
ir1 = bdNew();
rr1 = bdNew();
tmp = bdNew();
bdPrintHex("n=\n", n, "\n");
bdPrintHex("e=", e, "\n");
bdPrintHex("d=\n", d, "\n");
bdPrintHex("IR=\n", ir, "\n");
/* COMPUTATION BY SIGNER */
/* (n, e) is the public key
(n, d) is the private key
IR is the encoded message
Keep d secret
*/
/* For odd e, RR = IR. The value RR^d mod n is now computed */
bdModExp(tmp, ir, d, n);
bdPrintHex("RR^d mod n=\n", tmp, "\n");
/* S = min { RR^d mod n, n-(RR^d mod n) } */
/* i.e. if this value > n/2, the signature S = n - (RR^d mod n) */
bdSubtract(s, n, tmp);
if (bdCompare(s, tmp) > 0)
bdSetEqual(s, tmp);
bdPrintHex("S=\n", s, "\n");
/* D.1.3 Signature Verification */
/* The value (S')^e mod n is computed to yield RR'. */
bdModExp(rr, s, e, n);
bdPrintHex("RR'=\n", rr, "\n");
/* If RR' = 12 mod 16, then IR' = RR';
If n - RR' = 12 mod 16, then IR' = n - RR'; */
if (bdShortMod(tmp, rr, 16) == 12)
bdSetEqual(ir1, rr);
else
bdSubtract(ir1, n, rr);
bdPrintHex("IR'=\n", ir1, "\n");
/* Since IR' is identical to the computed hash IR, and the signature verification is
successful. */
result = bdIsEqual(ir1, ir);
if (result)
printf("Signature verified OK\n");
else
printf("Signature verification FAILED!\n");
/* Clean up */
bdFree(&s);
bdFree(&rr);
bdFree(&ir1);
bdFree(&rr1);
bdFree(&tmp);
return result; /* TRUE = success */
}
int main(void)
{
BIGD e, n, d;
BIGD ir;
int result;
/* MSVC memory leak checking stuff */
#if _MSC_VER >= 1100
_CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
_CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_FILE );
_CrtSetReportFile( _CRT_WARN, _CRTDBG_FILE_STDOUT );
_CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_FILE );
_CrtSetReportFile( _CRT_ERROR, _CRTDBG_FILE_STDOUT );
_CrtSetReportMode( _CRT_ASSERT, _CRTDBG_MODE_FILE );
_CrtSetReportFile( _CRT_ASSERT, _CRTDBG_FILE_STDOUT );
#endif
printf("EXAMPLE OF THE rDSA from ANSI X9.31-1998 Appendix D\n");
/* Initialise variables */
e = bdNew();
n = bdNew();
d = bdNew();
ir = bdNew();
/* INPUT */
/* Convert integers from hex format to BIGD (spaces are ignored) */
bdConvFromHex(n, "ACD1CC46 DFE54FE8 F9786672 664CA269 0D0AD7E5"
"003BC642 7954D939 EEE8B271 52E6A947 450D7FA9"
"80172DE0 64D6569A 28A83FE7 0FA840F5 E9802CB8"
"984AB34B D5C1E639 9EC21E4D 3A3A69BE 4E676F39"
"5AAFEF7C 4925FD4F AEE9F9E5 E48AF431 5DF0EC2D"
"B9AD7A35 0B3DF2F4 D15DC003 9846D1AC A3527B1A"
"75049E3F E34F43BD");
bdConvFromHex(d, "1CCDA20B CFFB8D51 7EE96668 66621B11 822C7950"
"D55F4BB5 BEE37989 A7D17312 E326718B E0D79546"
"EAAE87A5 6623B919 B1715FFB D7F16028 FC400774"
"1961C88C 5D7B4DAA AC8D36A9 8C9EFBB2 6C8A4A0E"
"6BC15B35 8E528A1A C9D0F042 BEB93BCA 16B541B3"
"3F80C933 A3B76928 5C462ED5 677BFE89 DF07BED5"
"C127FD13 241D3C4B");
bdConvFromHex(ir, "6BBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB"
"BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB"
"BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB"
"BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB"
"BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB"
"BBBBBBBB BBBAA999 3E364706 816ABA3E 25717850"
"C26C9CD0 D89D33CC");
/* Set e = 3 directly */
bdSetShort(e, 3);
result = rDSA_SignAndVerify(ir, n, e, d);
assert(result);
/* Repeat for D.3 Odd e =3 with 2048-bit n */
bdConvFromHex(n, "BCCA30CA 5280BC51 E758DBAF FEDFE46A 5D2A78D8"
"3969E154 780F9B27 AD4E76E6 3E8FA960 29C04DE3"
"F2C4B01F ECBEBB44 FC2F5F8A C69BD0E3 278FF065"
"8A6F9AC2 3BCFB2C9 AAAF1AC4 D5571A55 D3B1EC35"
"50CF34D8 F789235D D3B5C4E2 F3DF1761 19D918F2"
"D35E805B 62FC35FE E5FD0785 4824B984 6DC1665E"
"35A31873 BF6A24FE 50842D0A A0305C35 D0F45B0D"
"7C2F1E94 32D850D6 7956D383 BBEF52FC 2ACBF7AE"
"6F7CA214 88A56456 BDF66726 96EE037C 3CAA2199"
"904E37AA 40134E10 155FC813 93A225BD 129C4B3B"
"C91AD3A5 FC958A6A BCABE355 0390B677 87625D78"
"F8D3172B 673C4482 CE354B89 51D7E8C4 DDCE5D4C"
"DFA6790C 6CE8C02C 8D807AE2 6F27FE33");
bdConvFromHex(d, "7DDC2086 E1AB2836 9A3B3D1F FF3FED9C 3E1C5090"
"26469638 500A676F C8DEF9EE D45FC640 1BD58942"
"A1D8756A 9DD47CD8 A81F9507 2F128B42 1A5FF599"
"06F511D6 D28A7731 1C74BC83 38E4BC39 37CBF2CE"
"35DF7890 A5061793 E2792DEC A294BA40 BBE610A1"
"E23F003C ECA823FF 43FE0503 856DD102 F3D6443E"
"CE6CBAF7 D4F16DFD BAF7C2F8 CB4955E2 F2DF29FD"
"A7A4DD7B 93785252 E2CA4AAD 14E8B1A1 7881D381"
"DAD9061E C8AB50DD CBF8B56A FA464F01 D28DFDFF"
"0CAFF6B5 588E8F77 6FA128DE 7C102494 7D5D8067"
"3F545A5C 73FBC16B 609A33A1 1021DD8F 37A4E7C4"
"78AA19E3 BCB1BBD8 F4AA9232 65F1F1D5 5236753A"
"C8C10D60 F0FAB073 66439A90 5E2C63AB");
bdConvFromHex(ir, "6BBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB"
"BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB"
"BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB"
"BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB"
"BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB"
"BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB"
"BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB"
"BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB"
"BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB"
"BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB"
"BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB"
"BBBBBBBB BBBBBBBB BBBBBBBB BBBAA999 3E364706"
"816ABA3E 25717850 C26C9CD0 D89D33CC");
result = rDSA_SignAndVerify(ir, n, e, d);
assert(result);
/* Clean up */
bdFree(&e);
bdFree(&n);
bdFree(&d);
bdFree(&ir);
printf("OK, successfully completed tests.\n");
return 0;
}

View File

@@ -1,454 +1,454 @@
/* $Id: t_bdRSA.c $ */
/* Test BigDigits "bd" functions using a new RSA key and random data */
/***** BEGIN LICENSE BLOCK *****
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Copyright (c) 2001-15 David Ireland, D.I. Management Services Pty Limited
* <http://www.di-mgt.com.au/bigdigits.html>. All rights reserved.
*
***** END LICENSE BLOCK *****/
/*
* Last updated:
* $Date: 2015-10-22 10:23:00 $
* $Revision: 2.5.0 $
* $Author: dai $
*/
#if _MSC_VER >= 1100
/* Detect memory leaks in MSVC++ */
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#else
#include <stdlib.h>
#endif
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <assert.h>
#include "bigd.h"
static int my_rand(unsigned char *bytes, size_t nbytes, const unsigned char *seed, size_t seedlen)
/* Our own (very insecure) random generator func using good old rand()
but in the required format for BD_RANDFUNC
-- replace this in practice with your own cryptographically-secure function
-- or use bdRandomOctets() in bigdRand.h
*/
{
unsigned int myseed;
size_t i;
int offset;
/* Use time for 32-bit seed - then blend in user-supplied seed, if any */
myseed = (unsigned)time(NULL) ^ (unsigned)clock();
if (seed)
{
for (offset = 0, i = 0; i < seedlen; i++, offset = (offset + 1) % sizeof(unsigned))
myseed ^= ((unsigned int)seed[i] << (offset * 8));
}
srand(myseed);
while (nbytes--)
{
*bytes++ = rand() & 0xFF;
}
return 0;
}
#define give_a_sign(c) putchar((c))
static bdigit_t SMALL_PRIMES[] = {
3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43,
47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101,
103, 107, 109, 113,
127, 131, 137, 139, 149, 151, 157, 163, 167, 173,
179, 181, 191, 193, 197, 199, 211, 223, 227, 229,
233, 239, 241, 251, 257, 263, 269, 271, 277, 281,
283, 293, 307, 311, 313, 317, 331, 337, 347, 349,
353, 359, 367, 373, 379, 383, 389, 397, 401, 409,
419, 421, 431, 433, 439, 443, 449, 457, 461, 463,
467, 479, 487, 491, 499, 503, 509, 521, 523, 541,
547, 557, 563, 569, 571, 577, 587, 593, 599, 601,
607, 613, 617, 619, 631, 641, 643, 647, 653, 659,
661, 673, 677, 683, 691, 701, 709, 719, 727, 733,
739, 743, 751, 757, 761, 769, 773, 787, 797, 809,
811, 821, 823, 827, 829, 839, 853, 857, 859, 863,
877, 881, 883, 887, 907, 911, 919, 929, 937, 941,
947, 953, 967, 971, 977, 983, 991, 997,
};
#define N_SMALL_PRIMES (sizeof(SMALL_PRIMES)/sizeof(bdigit_t))
int generateRSAPrime(BIGD p, size_t nbits, bdigit_t e, size_t ntests,
const unsigned char *seed, size_t seedlen, BD_RANDFUNC randFunc)
/* Create a prime p such that gcd(p-1, e) = 1.
Returns # prime tests carried out or -1 if failed.
Sets the TWO highest bits to ensure that the
product pq will always have its high bit set.
e MUST be a prime > 2.
This function assumes that e is prime so we can
do the less expensive test p mod e != 1 instead
of gcd(p-1, e) == 1.
Uses improvement in trial division from Menezes 4.51.
*/
{
BIGD u;
size_t i, j, iloop, maxloops, maxodd;
int done, overflow, failedtrial;
int count = 0;
bdigit_t r[N_SMALL_PRIMES];
/* Create a temp */
u = bdNew();
maxodd = nbits * 100;
maxloops = 5;
done = 0;
for (iloop = 0; !done && iloop < maxloops; iloop++)
{
/* Set candidate n0 as random odd number */
bdRandomSeeded(p, nbits, seed, seedlen, randFunc);
/* Set two highest and low bits */
bdSetBit(p, nbits - 1, 1);
bdSetBit(p, nbits - 2, 1);
bdSetBit(p, 0, 1);
/* To improve trial division, compute table R[q] = n0 mod q
for each odd prime q <= B
*/
for (i = 0; i < N_SMALL_PRIMES; i++)
{
r[i] = bdShortMod(u, p, SMALL_PRIMES[i]);
}
done = overflow = 0;
/* Try every odd number n0, n0+2, n0+4,... until we succeed */
for (j = 0; j < maxodd; j++, overflow = bdShortAdd(p, p, 2))
{
/* Check for overflow */
if (overflow)
break;
give_a_sign('.');
count++;
/* Each time 2 is added to the current candidate
update table R[q] = (R[q] + 2) mod q */
if (j > 0)
{
for (i = 0; i < N_SMALL_PRIMES; i++)
{
r[i] = (r[i] + 2) % SMALL_PRIMES[i];
}
}
/* Candidate passes the trial division stage if and only if
NONE of the R[q] values equal zero */
for (failedtrial = 0, i = 0; i < N_SMALL_PRIMES; i++)
{
if (r[i] == 0)
{
failedtrial = 1;
break;
}
}
if (failedtrial)
continue;
/* If p mod e = 1 then gcd(p, e) > 1, so try again */
bdShortMod(u, p, e);
if (bdShortCmp(u, 1) == 0)
continue;
/* Do expensive primality test */
give_a_sign('*');
if (bdRabinMiller(p, ntests))
{ /* Success! - we have a prime */
done = 1;
break;
}
}
}
/* Clear up */
bdFree(&u);
printf("\n");
return (done ? count : -1);
}
int generateRSAKey(BIGD n, BIGD e, BIGD d, BIGD p, BIGD q, BIGD dP, BIGD dQ, BIGD qInv,
size_t nbits, bdigit_t ee, size_t ntests, unsigned char *seed, size_t seedlen,
BD_RANDFUNC randFunc)
{
BIGD g, p1, q1, phi;
size_t np, nq;
unsigned char *myseed = NULL;
clock_t start, finish;
double duration, tmake;
long ptests;
int res;
/* Initialise */
g = bdNew();
p1 = bdNew();
q1 = bdNew();
phi = bdNew();
printf("Generating a %d-bit RSA key...\n", nbits);
/* We add an extra byte to the user-supplied seed */
myseed = malloc(seedlen + 1);
if (!myseed) return -1;
memcpy(myseed, seed, seedlen);
/* Do (p, q) in two halves, approx equal */
nq = nbits / 2 ;
np = nbits - nq;
/* Make sure seeds are slightly different for p and q */
myseed[seedlen] = 0x01;
start = clock();
res = generateRSAPrime(p, np, ee, ntests, myseed, seedlen+1, randFunc);
finish = clock();
bdPrintHex("p=", p, "\n");
assert(res > 0);
duration = (double)(finish - start) / CLOCKS_PER_SEC;
printf("generateRSAPrime took %.3f secs and %d prime candidates (%.4f s/test)\n", duration, res, duration / res);
ptests = res;
tmake = duration;
printf("p is %d bits\n", bdBitLength(p));
myseed[seedlen] = 0xff;
start = clock();
res = generateRSAPrime(q, nq, ee, ntests, myseed, seedlen+1, randFunc);
finish = clock();
bdPrintHex("q=", q, "\n");
assert(res > 0);
duration = (double)(finish - start) / CLOCKS_PER_SEC;
printf("generateRSAPrime took %.3f secs and %d prime candidates (%.4f s/test)\n", duration, res, duration / res);
ptests += res;
tmake += duration;
printf("q is %d bits\n", bdBitLength(q));
/* Check that p != q (if so, RNG is faulty!) */
assert(!bdIsEqual(p, q));
bdSetShort(e, ee);
bdPrintHex("e=", e, "\n");
/* If q > p swap p and q so p > q */
if (bdCompare(p, q) < 1)
{
bdSetEqual(g, p);
bdSetEqual(p, q);
bdSetEqual(q, g);
}
/* Calc p-1 and q-1 */
bdSetEqual(p1, p);
bdDecrement(p1);
bdPrintHex("p-1=\n", p1, "\n");
bdSetEqual(q1, q);
bdDecrement(q1);
bdPrintHex("q-1=\n", q1, "\n");
/* Check gcd(p-1, e) = 1 */
bdGcd(g, p1, e);
bdPrintHex("gcd(p-1,e)=", g, "\n");
assert(bdShortCmp(g, 1) == 0);
bdGcd(g, q1, e);
bdPrintHex("gcd(q-1,e)=", g, "\n");
assert(bdShortCmp(g, 1) == 0);
/* Compute n = pq */
bdMultiply(n, p, q);
bdPrintHex("n=\n", n, "\n");
/* Compute d = e^-1 mod (p-1)(q-1) */
bdMultiply(phi, p1, q1);
bdPrintHex("phi=\n", phi, "\n");
res = bdModInv(d, e, phi);
assert(res == 0);
bdPrintHex("d=\n", d, "\n");
/* Check ed = 1 mod phi */
bdModMult(g, e, d, phi);
bdPrintHex("ed mod phi=", g, "\n");
assert(bdShortCmp(g, 1) == 0);
/* Calculate CRT key values */
printf("CRT values:\n");
bdModInv(dP, e, p1);
bdModInv(dQ, e, q1);
bdModInv(qInv, q, p);
bdPrintHex("dP=", dP, "\n");
bdPrintHex("dQ=", dQ, "\n");
bdPrintHex("qInv=", qInv, "\n");
printf("\nTime to create key = %.3f secs with %ld prime candidates (%.4f s/test)\n\n", tmake, ptests, tmake / ptests);
printf("n is %d bits\n", bdBitLength(n));
/* Clean up */
if (myseed) free(myseed);
bdFree(&g);
bdFree(&p1);
bdFree(&q1);
bdFree(&phi);
return 0;
}
static int debug = 0;
int main(void)
{
size_t nbits = 1025; /* (use an odd modulus size to see if it breaks anything!) */
unsigned ee = 0x3;
size_t ntests = 50;
unsigned char *seed = NULL;
size_t seedlen = 0;
BIGD n, e, d, p, q, dP, dQ, qInv;
BIGD m, c, s, hq, h, m1, m2;
int res;
clock_t start, finish;
double tinv, tcrt;
/* MSVC memory leak checking stuff */
#if _MSC_VER >= 1100
_CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
_CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_FILE );
_CrtSetReportFile( _CRT_WARN, _CRTDBG_FILE_STDOUT );
_CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_FILE );
_CrtSetReportFile( _CRT_ERROR, _CRTDBG_FILE_STDOUT );
_CrtSetReportMode( _CRT_ASSERT, _CRTDBG_MODE_FILE );
_CrtSetReportFile( _CRT_ASSERT, _CRTDBG_FILE_STDOUT );
#endif
printf("Test BIGDIGITS with a new %d-bit RSA key and random data.\n", nbits);
/* Initialise */
p = bdNew();
q = bdNew();
n = bdNew();
e = bdNew();
d = bdNew();
dP= bdNew();
dQ= bdNew();
qInv= bdNew();
m = bdNew();
c = bdNew();
s = bdNew();
m1 = bdNew();
m2 = bdNew();
h = bdNew();
hq = bdNew();
/* Create RSA key pair (n, e),(d, p, q, dP, dQ, qInv) */
/* NB we use simple my_rand() here -- you should use a proper cryptographically-secure RNG */
res = generateRSAKey(n, e, d, p, q, dP, dQ, qInv, nbits, ee, ntests, seed, seedlen, my_rand);
if (res != 0)
{
printf("Failed to generate RSA key!\n");
goto clean_up;
}
/* Set a random message m < n */
bdRandomSeeded(m, bdBitLength(n)-1, NULL, 0, my_rand);
bdPrintHex("m=\n", m, "\n");
/* Encrypt c = m^e mod n */
bdModExp(c, m, e, n);
bdPrintHex("c=\n", c, "\n");
/* Check decrypt m1 = c^d mod n */
start = clock();
bdModExp(m1, c, d, n);
finish = clock();
tinv = (double)(finish - start) / CLOCKS_PER_SEC;
bdPrintHex("m'=\n", m1, "\n");
res = bdCompare(m1, m);
printf("Decryption %s\n", (res == 0 ? "OK" : "FAILED!"));
assert(res == 0);
printf("Decrypt by inversion took %.3f secs\n", tinv);
/* Sign s = m^d mod n */
bdModExp(s, m, d, n);
bdPrintHex("s=\n", s, "\n");
/* Check verify m1 = s^e mod n */
bdModExp(m1, s, e, n);
bdPrintHex("m'=\n", m1, "\n");
res = bdCompare(m1, m);
printf("Verification %s\n", (res == 0 ? "OK" : "FAILED!"));
assert(res == 0);
/* Decrypt using CRT method - Ref: PKCS #1 */
bdPrintHex("m=", m, "\n");
bdPrintHex("c=", c, "\n");
bdPrintHex("p=", p, "\n");
bdPrintHex("q=", q, "\n");
start = clock();
/* Let m_1 = c^dP mod p. */
bdModExp(m1, c, dP, p);
if(debug)bdPrintHex("m_1=c^dP mod p=", m1, "\n");
/* Let m_2 = c^dQ mod q. */
bdModExp(m2, c, dQ, q);
if(debug)bdPrintHex("m_2=c^dQ mod q=", m2, "\n");
if (bdCompare(m1, m2) < 0)
bdAdd(m1, m1, p);
bdSubtract(m1, m1, m2);
if(debug)bdPrintHex("m_1 - m_2=", m1, "\n");
/* Let h = qInv ( m_1 - m_2 ) mod p. */
bdModMult(h, qInv, m1, p);
if(debug)bdPrintHex("h=qInv(m1-m2) mod p=", h, "\n");
bdMultiply(hq, h, q);
if(debug)bdPrintHex("hq=", hq, "\n");
/* Let m = m_2 + hq. */
bdAdd(m1, m2, hq);
finish = clock();
tcrt = (double)(finish - start) / CLOCKS_PER_SEC;
if(debug)bdPrintHex("m'=m_2 + hq=", m1, "\n");
bdPrintHex("(CRT)m'=\n", m1, "\n");
res = bdCompare(m1, m);
printf("CRT Decryption %s\n", (res == 0 ? "OK" : "FAILED!"));
assert(res == 0);
printf("Decrypt by CRT took %.3f secs\n", tcrt);
printf("c.f. Decrypt by inversion %.3f secs (factor = %.1f)\n",
tinv, (tcrt ? tinv / tcrt : 0));
printf("n is %d bits\n", bdBitLength(n));
/* Clean up */
clean_up:
bdFree(&n);
bdFree(&e);
bdFree(&d);
bdFree(&p);
bdFree(&q);
bdFree(&dP);
bdFree(&dQ);
bdFree(&qInv);
bdFree(&m);
bdFree(&c);
bdFree(&s);
bdFree(&m1);
bdFree(&m2);
bdFree(&h);
bdFree(&hq);
printf("OK, successfully completed tests.\n");
return 0;
}
/* $Id: t_bdRSA.c $ */
/* Test BigDigits "bd" functions using a new RSA key and random data */
/***** BEGIN LICENSE BLOCK *****
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Copyright (c) 2001-15 David Ireland, D.I. Management Services Pty Limited
* <http://www.di-mgt.com.au/bigdigits.html>. All rights reserved.
*
***** END LICENSE BLOCK *****/
/*
* Last updated:
* $Date: 2015-10-22 10:23:00 $
* $Revision: 2.5.0 $
* $Author: dai $
*/
#if _MSC_VER >= 1100
/* Detect memory leaks in MSVC++ */
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#else
#include <stdlib.h>
#endif
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <assert.h>
#include "bigd.h"
static int my_rand(unsigned char *bytes, size_t nbytes, const unsigned char *seed, size_t seedlen)
/* Our own (very insecure) random generator func using good old rand()
but in the required format for BD_RANDFUNC
-- replace this in practice with your own cryptographically-secure function
-- or use bdRandomOctets() in bigdRand.h
*/
{
unsigned int myseed;
size_t i;
int offset;
/* Use time for 32-bit seed - then blend in user-supplied seed, if any */
myseed = (unsigned)time(NULL) ^ (unsigned)clock();
if (seed)
{
for (offset = 0, i = 0; i < seedlen; i++, offset = (offset + 1) % sizeof(unsigned))
myseed ^= ((unsigned int)seed[i] << (offset * 8));
}
srand(myseed);
while (nbytes--)
{
*bytes++ = rand() & 0xFF;
}
return 0;
}
#define give_a_sign(c) putchar((c))
static bdigit_t SMALL_PRIMES[] = {
3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43,
47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101,
103, 107, 109, 113,
127, 131, 137, 139, 149, 151, 157, 163, 167, 173,
179, 181, 191, 193, 197, 199, 211, 223, 227, 229,
233, 239, 241, 251, 257, 263, 269, 271, 277, 281,
283, 293, 307, 311, 313, 317, 331, 337, 347, 349,
353, 359, 367, 373, 379, 383, 389, 397, 401, 409,
419, 421, 431, 433, 439, 443, 449, 457, 461, 463,
467, 479, 487, 491, 499, 503, 509, 521, 523, 541,
547, 557, 563, 569, 571, 577, 587, 593, 599, 601,
607, 613, 617, 619, 631, 641, 643, 647, 653, 659,
661, 673, 677, 683, 691, 701, 709, 719, 727, 733,
739, 743, 751, 757, 761, 769, 773, 787, 797, 809,
811, 821, 823, 827, 829, 839, 853, 857, 859, 863,
877, 881, 883, 887, 907, 911, 919, 929, 937, 941,
947, 953, 967, 971, 977, 983, 991, 997,
};
#define N_SMALL_PRIMES (sizeof(SMALL_PRIMES)/sizeof(bdigit_t))
int generateRSAPrime(BIGD p, size_t nbits, bdigit_t e, size_t ntests,
const unsigned char *seed, size_t seedlen, BD_RANDFUNC randFunc)
/* Create a prime p such that gcd(p-1, e) = 1.
Returns # prime tests carried out or -1 if failed.
Sets the TWO highest bits to ensure that the
product pq will always have its high bit set.
e MUST be a prime > 2.
This function assumes that e is prime so we can
do the less expensive test p mod e != 1 instead
of gcd(p-1, e) == 1.
Uses improvement in trial division from Menezes 4.51.
*/
{
BIGD u;
size_t i, j, iloop, maxloops, maxodd;
int done, overflow, failedtrial;
int count = 0;
bdigit_t r[N_SMALL_PRIMES];
/* Create a temp */
u = bdNew();
maxodd = nbits * 100;
maxloops = 5;
done = 0;
for (iloop = 0; !done && iloop < maxloops; iloop++)
{
/* Set candidate n0 as random odd number */
bdRandomSeeded(p, nbits, seed, seedlen, randFunc);
/* Set two highest and low bits */
bdSetBit(p, nbits - 1, 1);
bdSetBit(p, nbits - 2, 1);
bdSetBit(p, 0, 1);
/* To improve trial division, compute table R[q] = n0 mod q
for each odd prime q <= B
*/
for (i = 0; i < N_SMALL_PRIMES; i++)
{
r[i] = bdShortMod(u, p, SMALL_PRIMES[i]);
}
done = overflow = 0;
/* Try every odd number n0, n0+2, n0+4,... until we succeed */
for (j = 0; j < maxodd; j++, overflow = bdShortAdd(p, p, 2))
{
/* Check for overflow */
if (overflow)
break;
give_a_sign('.');
count++;
/* Each time 2 is added to the current candidate
update table R[q] = (R[q] + 2) mod q */
if (j > 0)
{
for (i = 0; i < N_SMALL_PRIMES; i++)
{
r[i] = (r[i] + 2) % SMALL_PRIMES[i];
}
}
/* Candidate passes the trial division stage if and only if
NONE of the R[q] values equal zero */
for (failedtrial = 0, i = 0; i < N_SMALL_PRIMES; i++)
{
if (r[i] == 0)
{
failedtrial = 1;
break;
}
}
if (failedtrial)
continue;
/* If p mod e = 1 then gcd(p, e) > 1, so try again */
bdShortMod(u, p, e);
if (bdShortCmp(u, 1) == 0)
continue;
/* Do expensive primality test */
give_a_sign('*');
if (bdRabinMiller(p, ntests))
{ /* Success! - we have a prime */
done = 1;
break;
}
}
}
/* Clear up */
bdFree(&u);
printf("\n");
return (done ? count : -1);
}
int generateRSAKey(BIGD n, BIGD e, BIGD d, BIGD p, BIGD q, BIGD dP, BIGD dQ, BIGD qInv,
size_t nbits, bdigit_t ee, size_t ntests, unsigned char *seed, size_t seedlen,
BD_RANDFUNC randFunc)
{
BIGD g, p1, q1, phi;
size_t np, nq;
unsigned char *myseed = NULL;
clock_t start, finish;
double duration, tmake;
long ptests;
int res;
/* Initialise */
g = bdNew();
p1 = bdNew();
q1 = bdNew();
phi = bdNew();
printf("Generating a %d-bit RSA key...\n", nbits);
/* We add an extra byte to the user-supplied seed */
myseed = malloc(seedlen + 1);
if (!myseed) return -1;
memcpy(myseed, seed, seedlen);
/* Do (p, q) in two halves, approx equal */
nq = nbits / 2 ;
np = nbits - nq;
/* Make sure seeds are slightly different for p and q */
myseed[seedlen] = 0x01;
start = clock();
res = generateRSAPrime(p, np, ee, ntests, myseed, seedlen+1, randFunc);
finish = clock();
bdPrintHex("p=", p, "\n");
assert(res > 0);
duration = (double)(finish - start) / CLOCKS_PER_SEC;
printf("generateRSAPrime took %.3f secs and %d prime candidates (%.4f s/test)\n", duration, res, duration / res);
ptests = res;
tmake = duration;
printf("p is %d bits\n", bdBitLength(p));
myseed[seedlen] = 0xff;
start = clock();
res = generateRSAPrime(q, nq, ee, ntests, myseed, seedlen+1, randFunc);
finish = clock();
bdPrintHex("q=", q, "\n");
assert(res > 0);
duration = (double)(finish - start) / CLOCKS_PER_SEC;
printf("generateRSAPrime took %.3f secs and %d prime candidates (%.4f s/test)\n", duration, res, duration / res);
ptests += res;
tmake += duration;
printf("q is %d bits\n", bdBitLength(q));
/* Check that p != q (if so, RNG is faulty!) */
assert(!bdIsEqual(p, q));
bdSetShort(e, ee);
bdPrintHex("e=", e, "\n");
/* If q > p swap p and q so p > q */
if (bdCompare(p, q) < 1)
{
bdSetEqual(g, p);
bdSetEqual(p, q);
bdSetEqual(q, g);
}
/* Calc p-1 and q-1 */
bdSetEqual(p1, p);
bdDecrement(p1);
bdPrintHex("p-1=\n", p1, "\n");
bdSetEqual(q1, q);
bdDecrement(q1);
bdPrintHex("q-1=\n", q1, "\n");
/* Check gcd(p-1, e) = 1 */
bdGcd(g, p1, e);
bdPrintHex("gcd(p-1,e)=", g, "\n");
assert(bdShortCmp(g, 1) == 0);
bdGcd(g, q1, e);
bdPrintHex("gcd(q-1,e)=", g, "\n");
assert(bdShortCmp(g, 1) == 0);
/* Compute n = pq */
bdMultiply(n, p, q);
bdPrintHex("n=\n", n, "\n");
/* Compute d = e^-1 mod (p-1)(q-1) */
bdMultiply(phi, p1, q1);
bdPrintHex("phi=\n", phi, "\n");
res = bdModInv(d, e, phi);
assert(res == 0);
bdPrintHex("d=\n", d, "\n");
/* Check ed = 1 mod phi */
bdModMult(g, e, d, phi);
bdPrintHex("ed mod phi=", g, "\n");
assert(bdShortCmp(g, 1) == 0);
/* Calculate CRT key values */
printf("CRT values:\n");
bdModInv(dP, e, p1);
bdModInv(dQ, e, q1);
bdModInv(qInv, q, p);
bdPrintHex("dP=", dP, "\n");
bdPrintHex("dQ=", dQ, "\n");
bdPrintHex("qInv=", qInv, "\n");
printf("\nTime to create key = %.3f secs with %ld prime candidates (%.4f s/test)\n\n", tmake, ptests, tmake / ptests);
printf("n is %d bits\n", bdBitLength(n));
/* Clean up */
if (myseed) free(myseed);
bdFree(&g);
bdFree(&p1);
bdFree(&q1);
bdFree(&phi);
return 0;
}
static int debug = 0;
int main(void)
{
size_t nbits = 1025; /* (use an odd modulus size to see if it breaks anything!) */
unsigned ee = 0x3;
size_t ntests = 50;
unsigned char *seed = NULL;
size_t seedlen = 0;
BIGD n, e, d, p, q, dP, dQ, qInv;
BIGD m, c, s, hq, h, m1, m2;
int res;
clock_t start, finish;
double tinv, tcrt;
/* MSVC memory leak checking stuff */
#if _MSC_VER >= 1100
_CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
_CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_FILE );
_CrtSetReportFile( _CRT_WARN, _CRTDBG_FILE_STDOUT );
_CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_FILE );
_CrtSetReportFile( _CRT_ERROR, _CRTDBG_FILE_STDOUT );
_CrtSetReportMode( _CRT_ASSERT, _CRTDBG_MODE_FILE );
_CrtSetReportFile( _CRT_ASSERT, _CRTDBG_FILE_STDOUT );
#endif
printf("Test BIGDIGITS with a new %d-bit RSA key and random data.\n", nbits);
/* Initialise */
p = bdNew();
q = bdNew();
n = bdNew();
e = bdNew();
d = bdNew();
dP= bdNew();
dQ= bdNew();
qInv= bdNew();
m = bdNew();
c = bdNew();
s = bdNew();
m1 = bdNew();
m2 = bdNew();
h = bdNew();
hq = bdNew();
/* Create RSA key pair (n, e),(d, p, q, dP, dQ, qInv) */
/* NB we use simple my_rand() here -- you should use a proper cryptographically-secure RNG */
res = generateRSAKey(n, e, d, p, q, dP, dQ, qInv, nbits, ee, ntests, seed, seedlen, my_rand);
if (res != 0)
{
printf("Failed to generate RSA key!\n");
goto clean_up;
}
/* Set a random message m < n */
bdRandomSeeded(m, bdBitLength(n)-1, NULL, 0, my_rand);
bdPrintHex("m=\n", m, "\n");
/* Encrypt c = m^e mod n */
bdModExp(c, m, e, n);
bdPrintHex("c=\n", c, "\n");
/* Check decrypt m1 = c^d mod n */
start = clock();
bdModExp(m1, c, d, n);
finish = clock();
tinv = (double)(finish - start) / CLOCKS_PER_SEC;
bdPrintHex("m'=\n", m1, "\n");
res = bdCompare(m1, m);
printf("Decryption %s\n", (res == 0 ? "OK" : "FAILED!"));
assert(res == 0);
printf("Decrypt by inversion took %.3f secs\n", tinv);
/* Sign s = m^d mod n */
bdModExp(s, m, d, n);
bdPrintHex("s=\n", s, "\n");
/* Check verify m1 = s^e mod n */
bdModExp(m1, s, e, n);
bdPrintHex("m'=\n", m1, "\n");
res = bdCompare(m1, m);
printf("Verification %s\n", (res == 0 ? "OK" : "FAILED!"));
assert(res == 0);
/* Decrypt using CRT method - Ref: PKCS #1 */
bdPrintHex("m=", m, "\n");
bdPrintHex("c=", c, "\n");
bdPrintHex("p=", p, "\n");
bdPrintHex("q=", q, "\n");
start = clock();
/* Let m_1 = c^dP mod p. */
bdModExp(m1, c, dP, p);
if(debug)bdPrintHex("m_1=c^dP mod p=", m1, "\n");
/* Let m_2 = c^dQ mod q. */
bdModExp(m2, c, dQ, q);
if(debug)bdPrintHex("m_2=c^dQ mod q=", m2, "\n");
if (bdCompare(m1, m2) < 0)
bdAdd(m1, m1, p);
bdSubtract(m1, m1, m2);
if(debug)bdPrintHex("m_1 - m_2=", m1, "\n");
/* Let h = qInv ( m_1 - m_2 ) mod p. */
bdModMult(h, qInv, m1, p);
if(debug)bdPrintHex("h=qInv(m1-m2) mod p=", h, "\n");
bdMultiply(hq, h, q);
if(debug)bdPrintHex("hq=", hq, "\n");
/* Let m = m_2 + hq. */
bdAdd(m1, m2, hq);
finish = clock();
tcrt = (double)(finish - start) / CLOCKS_PER_SEC;
if(debug)bdPrintHex("m'=m_2 + hq=", m1, "\n");
bdPrintHex("(CRT)m'=\n", m1, "\n");
res = bdCompare(m1, m);
printf("CRT Decryption %s\n", (res == 0 ? "OK" : "FAILED!"));
assert(res == 0);
printf("Decrypt by CRT took %.3f secs\n", tcrt);
printf("c.f. Decrypt by inversion %.3f secs (factor = %.1f)\n",
tinv, (tcrt ? tinv / tcrt : 0));
printf("n is %d bits\n", bdBitLength(n));
/* Clean up */
clean_up:
bdFree(&n);
bdFree(&e);
bdFree(&d);
bdFree(&p);
bdFree(&q);
bdFree(&dP);
bdFree(&dQ);
bdFree(&qInv);
bdFree(&m);
bdFree(&c);
bdFree(&s);
bdFree(&m1);
bdFree(&m2);
bdFree(&h);
bdFree(&hq);
printf("OK, successfully completed tests.\n");
return 0;
}

View File

@@ -1,402 +1,402 @@
/* $Id: t_bdRSA1.c $ */
/***** BEGIN LICENSE BLOCK *****
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Copyright (c) 2001-15 David Ireland, D.I. Management Services Pty Limited
* <http://www.di-mgt.com.au/bigdigits.html>. All rights reserved.
*
***** END LICENSE BLOCK *****/
/*
* Last updated:
* $Date: 2015-10-22 10:23:00 $
* $Revision: 2.5.0 $
* $Author: dai $
*/
/* Test BigDigits "bd" functions using a new RSA key and user input plaintext
NOTE: this uses a different algorithm to generate the random number (a better one,
still not quite cryptographically secure, but much better than using rand()).
It also uses a more convenient key length of 1024 which is an exact multiple of 8.
The "message" to be encrypted is accepted from the command-line or defaults to "abc".
The message length is restricted to 117 bytes by the size of the key (|n|-11).
*/
#if _MSC_VER >= 1100
/* Detect memory leaks in MSVC++ */
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#else
#include <stdlib.h>
#endif
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <assert.h>
#include "bigd.h"
#include "bigdRand.h"
static void pr_bytesmsg(char *msg, unsigned char *bytes, size_t len)
{
size_t i;
printf("%s", msg);
for (i = 0; i < len; i++)
printf("%02x", bytes[i]);
printf("\n");
}
int generateRSAKey(BIGD n, BIGD e, BIGD d, BIGD p, BIGD q, BIGD dP, BIGD dQ, BIGD qInv,
size_t nbits, bdigit_t ee, size_t ntests, unsigned char *seed, size_t seedlen,
BD_RANDFUNC randFunc)
{
BIGD g, p1, q1, phi;
size_t np, nq;
unsigned char *myseed = NULL;
clock_t start, finish;
double duration, tmake;
int res;
/* Initialise */
g = bdNew();
p1 = bdNew();
q1 = bdNew();
phi = bdNew();
printf("Generating a %d-bit RSA key...\n", nbits);
/* Set e as a BigDigit from short value ee */
bdSetShort(e, ee);
bdPrintHex("e=", e, "\n");
/* We add an extra byte to the user-supplied seed */
myseed = malloc(seedlen + 1);
if (!myseed) return -1;
memcpy(myseed, seed, seedlen);
/* Make sure seeds are slightly different for p and q */
myseed[seedlen] = 0x01;
/* Do (p, q) in two halves, approx equal */
nq = nbits / 2 ;
np = nbits - nq;
/* Compute two primes of required length with p mod e > 1 and *second* highest bit set */
start = clock();
do {
bdGeneratePrime(p, np, ntests, myseed, seedlen+1, randFunc);
bdPrintHex("Try p=", p, "\n");
} while ((bdShortMod(g, p, ee) == 1) || bdGetBit(p, np-2) == 0);
finish = clock();
duration = (double)(finish - start) / CLOCKS_PER_SEC;
tmake = duration;
printf("p is %d bits, bit(%d) is %d\n", bdBitLength(p), np-2, bdGetBit(p,np-2));
myseed[seedlen] = 0xff;
start = clock();
do {
bdGeneratePrime(q, nq, ntests, myseed, seedlen+1, randFunc);
bdPrintHex("Try q=", q, "\n");
} while ((bdShortMod(g, q, ee) == 1) || bdGetBit(q, nq-2) == 0);
finish = clock();
duration = (double)(finish - start) / CLOCKS_PER_SEC;
tmake += duration;
printf("q is %d bits, bit(%d) is %d\n", bdBitLength(q), nq-2, bdGetBit(q,nq-2));
printf("Prime generation took %.3f secs\n", duration);
/* Compute n = pq */
bdMultiply(n, p, q);
bdPrintHex("n=\n", n, "\n");
printf("n is %d bits\n", bdBitLength(n));
assert(bdBitLength(n) == nbits);
/* Check that p != q (if so, RNG is faulty!) */
assert(!bdIsEqual(p, q));
/* If q > p swap p and q so p > q */
if (bdCompare(p, q) < 1)
{
printf("Swopping p and q so p > q...\n");
bdSetEqual(g, p);
bdSetEqual(p, q);
bdSetEqual(q, g);
}
bdPrintHex("p=", p, "\n");
bdPrintHex("q=", q, "\n");
/* Calc p-1 and q-1 */
bdSetEqual(p1, p);
bdDecrement(p1);
bdPrintHex("p-1=\n", p1, "\n");
bdSetEqual(q1, q);
bdDecrement(q1);
bdPrintHex("q-1=\n", q1, "\n");
/* Compute phi = (p-1)(q-1) */
bdMultiply(phi, p1, q1);
bdPrintHex("phi=\n", phi, "\n");
/* Check gcd(phi, e) == 1 */
bdGcd(g, phi, e);
bdPrintHex("gcd(phi,e)=", g, "\n");
assert(bdShortCmp(g, 1) == 0);
/* Compute inverse of e modulo phi: d = 1/e mod (p-1)(q-1) */
res = bdModInv(d, e, phi);
assert(res == 0);
bdPrintHex("d=\n", d, "\n");
/* Check ed = 1 mod phi */
bdModMult(g, e, d, phi);
bdPrintHex("ed mod phi=", g, "\n");
assert(bdShortCmp(g, 1) == 0);
/* Calculate CRT key values */
printf("CRT values:\n");
bdModInv(dP, e, p1);
bdModInv(dQ, e, q1);
bdModInv(qInv, q, p);
bdPrintHex("dP=", dP, "\n");
bdPrintHex("dQ=", dQ, "\n");
bdPrintHex("qInv=", qInv, "\n");
printf("n is %d bits\n", bdBitLength(n));
/* Clean up */
if (myseed) free(myseed);
bdFree(&g);
bdFree(&p1);
bdFree(&q1);
bdFree(&phi);
return 0;
}
#define KEYSIZE 1024
static int debug = 0;
int main(int argc, char *argv[])
{
size_t nbits = KEYSIZE; /* NB a multiple of 8 here */
int klen, mlen;
int npad, i;
unsigned char rb;
unsigned char block[(KEYSIZE+7)/8];
unsigned ee = 0x3;
size_t ntests = 50;
unsigned char *seed = NULL;
size_t seedlen = 0;
char msgstr[sizeof(block)];
int nchars;
unsigned char *pmsg = "abc"; /* Default message */
BIGD n, e, d, p, q, dP, dQ, qInv;
BIGD m, c, s, hq, h, m1, m2;
int res;
clock_t start, finish;
double tinv, tcrt;
/* MSVC memory leak checking stuff */
#if _MSC_VER >= 1100
_CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
_CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_FILE );
_CrtSetReportFile( _CRT_WARN, _CRTDBG_FILE_STDOUT );
_CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_FILE );
_CrtSetReportFile( _CRT_ERROR, _CRTDBG_FILE_STDOUT );
_CrtSetReportMode( _CRT_ASSERT, _CRTDBG_MODE_FILE );
_CrtSetReportFile( _CRT_ASSERT, _CRTDBG_FILE_STDOUT );
#endif
if (argc > 1)
{ /* Use message supplied in command line */
pmsg = (unsigned char*)argv[1];
}
printf("Test BIGDIGITS with a new %d-bit RSA key and given message data.\n", nbits);
/* Initialise */
p = bdNew();
q = bdNew();
n = bdNew();
e = bdNew();
d = bdNew();
dP= bdNew();
dQ= bdNew();
qInv= bdNew();
m = bdNew();
c = bdNew();
s = bdNew();
m1 = bdNew();
m2 = bdNew();
h = bdNew();
hq = bdNew();
/* Create RSA key pair (n, e),(d, p, q, dP, dQ, qInv) */
/* NB you should use a proper cryptographically-secure RNG */
res = generateRSAKey(n, e, d, p, q, dP, dQ, qInv, nbits, ee, ntests, seed, seedlen, bdRandomOctets);
if (res != 0)
{
printf("Failed to generate RSA key!\n");
goto clean_up;
}
/* Create a PKCS#1 v1.5 EME message block in octet format */
/*
|<-----------------(klen bytes)--------------->|
+--+--+-------+--+-----------------------------+
|00|02|PADDING|00| DATA TO ENCRYPT |
+--+--+-------+--+-----------------------------+
The padding is made up of _at least_ eight non-zero random bytes.
*/
/* How big is the key in octets (8-bit bytes)? */
klen = (nbits + 7) / 8;
/* CAUTION: make sure the block is at least klen bytes long */
memset(block, 0, klen);
mlen = strlen(pmsg);
npad = klen - mlen - 3;
if (npad < 8) /* Note npad is a signed int, not a size_t */
{
printf("Message is too long\n");
exit(1);
}
/* Display */
printf("Message='%s' ", pmsg);
pr_bytesmsg("0x", pmsg, strlen((char*)pmsg));
/* Create encryption block */
block[0] = 0x00;
block[1] = 0x02;
/* Generate npad non-zero padding bytes - rand() is OK */
srand((unsigned)time(NULL));
for (i = 0; i < npad; i++)
{
while ((rb = (rand() & 0xFF)) == 0)
;/* loop until non-zero*/
block[i+2] = rb;
}
block[npad+2] = 0x00;
memcpy(&block[npad+3], pmsg, mlen);
/* Convert to BIGD format */
bdConvFromOctets(m, block, klen);
bdPrintHex("m=\n", m, "\n");
/* Encrypt c = m^e mod n */
bdModExp(c, m, e, n);
bdPrintHex("c=\n", c, "\n");
/* Check decrypt m1 = c^d mod n */
start = clock();
bdModExp(m1, c, d, n);
finish = clock();
tinv = (double)(finish - start) / CLOCKS_PER_SEC;
bdPrintHex("m'=\n", m1, "\n");
res = bdCompare(m1, m);
printf("Decryption %s\n", (res == 0 ? "OK" : "FAILED!"));
assert(res == 0);
printf("Decrypt by inversion took %.3f secs\n", tinv);
/* Extract the message bytes from the decrypted block */
memset(block, 0, klen);
bdConvToOctets(m, block, klen);
assert(block[0] == 0x00);
assert(block[1] == 0x02);
for (i = 2; i < klen; i++)
{ /* Look for zero separating byte */
if (block[i] == 0x00)
break;
}
if (i >= klen)
printf("ERROR: failed to find message in decrypted block\n");
else
{
nchars = klen - i - 1;
memcpy(msgstr, &block[i+1], nchars);
msgstr[nchars] = '\0';
printf("Decrypted message is '%s'\n", msgstr);
}
/* Sign s = m^d mod n (NB m is not a valid PKCS-v1_5 signature block) */
bdModExp(s, m, d, n);
bdPrintHex("s=\n", s, "\n");
/* Continue as original t_bdRSA ... */
/* Check verify m1 = s^e mod n */
bdModExp(m1, s, e, n);
bdPrintHex("m'=\n", m1, "\n");
res = bdCompare(m1, m);
printf("Verification %s\n", (res == 0 ? "OK" : "FAILED!"));
assert(res == 0);
/* Decrypt using CRT method - Ref: PKCS #1 */
bdPrintHex("m=", m, "\n");
bdPrintHex("c=", c, "\n");
bdPrintHex("p=", p, "\n");
bdPrintHex("q=", q, "\n");
start = clock();
/* Let m_1 = c^dP mod p. */
bdModExp(m1, c, dP, p);
if(debug)bdPrintHex("m_1=c^dP mod p=", m1, "\n");
/* Let m_2 = c^dQ mod q. */
bdModExp(m2, c, dQ, q);
if(debug)bdPrintHex("m_2=c^dQ mod q=", m2, "\n");
if (bdCompare(m1, m2) < 0)
bdAdd(m1, m1, p);
bdSubtract(m1, m1, m2);
if(debug)bdPrintHex("m_1 - m_2=", m1, "\n");
/* Let h = qInv ( m_1 - m_2 ) mod p. */
bdModMult(h, qInv, m1, p);
if(debug)bdPrintHex("h=qInv(m1-m2) mod p=", h, "\n");
bdMultiply(hq, h, q);
if(debug)bdPrintHex("hq=", hq, "\n");
/* Let m = m_2 + hq. */
bdAdd(m1, m2, hq);
finish = clock();
tcrt = (double)(finish - start) / CLOCKS_PER_SEC;
if(debug)bdPrintHex("m'=m_2 + hq=", m1, "\n");
bdPrintHex("(CRT)m'=\n", m1, "\n");
res = bdCompare(m1, m);
printf("CRT Decryption %s\n", (res == 0 ? "OK" : "FAILED!"));
assert(res == 0);
printf("Decrypt by CRT took %.3f secs\n", tcrt);
printf("c.f. Decrypt by inversion %.3f secs (factor = %.1f)\n",
tinv, (tcrt ? tinv / tcrt : 0));
printf("n is %d bits\n", bdBitLength(n));
/* Clean up */
clean_up:
bdFree(&n);
bdFree(&e);
bdFree(&d);
bdFree(&p);
bdFree(&q);
bdFree(&dP);
bdFree(&dQ);
bdFree(&qInv);
bdFree(&m);
bdFree(&c);
bdFree(&s);
bdFree(&m1);
bdFree(&m2);
bdFree(&h);
bdFree(&hq);
/* Show the current version number */
printf("Version=%d\n", bdVersion());
printf("OK, successfully completed tests.\n");
return 0;
}
/* $Id: t_bdRSA1.c $ */
/***** BEGIN LICENSE BLOCK *****
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Copyright (c) 2001-15 David Ireland, D.I. Management Services Pty Limited
* <http://www.di-mgt.com.au/bigdigits.html>. All rights reserved.
*
***** END LICENSE BLOCK *****/
/*
* Last updated:
* $Date: 2015-10-22 10:23:00 $
* $Revision: 2.5.0 $
* $Author: dai $
*/
/* Test BigDigits "bd" functions using a new RSA key and user input plaintext
NOTE: this uses a different algorithm to generate the random number (a better one,
still not quite cryptographically secure, but much better than using rand()).
It also uses a more convenient key length of 1024 which is an exact multiple of 8.
The "message" to be encrypted is accepted from the command-line or defaults to "abc".
The message length is restricted to 117 bytes by the size of the key (|n|-11).
*/
#if _MSC_VER >= 1100
/* Detect memory leaks in MSVC++ */
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#else
#include <stdlib.h>
#endif
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <assert.h>
#include "bigd.h"
#include "bigdRand.h"
static void pr_bytesmsg(char *msg, unsigned char *bytes, size_t len)
{
size_t i;
printf("%s", msg);
for (i = 0; i < len; i++)
printf("%02x", bytes[i]);
printf("\n");
}
int generateRSAKey(BIGD n, BIGD e, BIGD d, BIGD p, BIGD q, BIGD dP, BIGD dQ, BIGD qInv,
size_t nbits, bdigit_t ee, size_t ntests, unsigned char *seed, size_t seedlen,
BD_RANDFUNC randFunc)
{
BIGD g, p1, q1, phi;
size_t np, nq;
unsigned char *myseed = NULL;
clock_t start, finish;
double duration, tmake;
int res;
/* Initialise */
g = bdNew();
p1 = bdNew();
q1 = bdNew();
phi = bdNew();
printf("Generating a %d-bit RSA key...\n", nbits);
/* Set e as a BigDigit from short value ee */
bdSetShort(e, ee);
bdPrintHex("e=", e, "\n");
/* We add an extra byte to the user-supplied seed */
myseed = malloc(seedlen + 1);
if (!myseed) return -1;
memcpy(myseed, seed, seedlen);
/* Make sure seeds are slightly different for p and q */
myseed[seedlen] = 0x01;
/* Do (p, q) in two halves, approx equal */
nq = nbits / 2 ;
np = nbits - nq;
/* Compute two primes of required length with p mod e > 1 and *second* highest bit set */
start = clock();
do {
bdGeneratePrime(p, np, ntests, myseed, seedlen+1, randFunc);
bdPrintHex("Try p=", p, "\n");
} while ((bdShortMod(g, p, ee) == 1) || bdGetBit(p, np-2) == 0);
finish = clock();
duration = (double)(finish - start) / CLOCKS_PER_SEC;
tmake = duration;
printf("p is %d bits, bit(%d) is %d\n", bdBitLength(p), np-2, bdGetBit(p,np-2));
myseed[seedlen] = 0xff;
start = clock();
do {
bdGeneratePrime(q, nq, ntests, myseed, seedlen+1, randFunc);
bdPrintHex("Try q=", q, "\n");
} while ((bdShortMod(g, q, ee) == 1) || bdGetBit(q, nq-2) == 0);
finish = clock();
duration = (double)(finish - start) / CLOCKS_PER_SEC;
tmake += duration;
printf("q is %d bits, bit(%d) is %d\n", bdBitLength(q), nq-2, bdGetBit(q,nq-2));
printf("Prime generation took %.3f secs\n", duration);
/* Compute n = pq */
bdMultiply(n, p, q);
bdPrintHex("n=\n", n, "\n");
printf("n is %d bits\n", bdBitLength(n));
assert(bdBitLength(n) == nbits);
/* Check that p != q (if so, RNG is faulty!) */
assert(!bdIsEqual(p, q));
/* If q > p swap p and q so p > q */
if (bdCompare(p, q) < 1)
{
printf("Swopping p and q so p > q...\n");
bdSetEqual(g, p);
bdSetEqual(p, q);
bdSetEqual(q, g);
}
bdPrintHex("p=", p, "\n");
bdPrintHex("q=", q, "\n");
/* Calc p-1 and q-1 */
bdSetEqual(p1, p);
bdDecrement(p1);
bdPrintHex("p-1=\n", p1, "\n");
bdSetEqual(q1, q);
bdDecrement(q1);
bdPrintHex("q-1=\n", q1, "\n");
/* Compute phi = (p-1)(q-1) */
bdMultiply(phi, p1, q1);
bdPrintHex("phi=\n", phi, "\n");
/* Check gcd(phi, e) == 1 */
bdGcd(g, phi, e);
bdPrintHex("gcd(phi,e)=", g, "\n");
assert(bdShortCmp(g, 1) == 0);
/* Compute inverse of e modulo phi: d = 1/e mod (p-1)(q-1) */
res = bdModInv(d, e, phi);
assert(res == 0);
bdPrintHex("d=\n", d, "\n");
/* Check ed = 1 mod phi */
bdModMult(g, e, d, phi);
bdPrintHex("ed mod phi=", g, "\n");
assert(bdShortCmp(g, 1) == 0);
/* Calculate CRT key values */
printf("CRT values:\n");
bdModInv(dP, e, p1);
bdModInv(dQ, e, q1);
bdModInv(qInv, q, p);
bdPrintHex("dP=", dP, "\n");
bdPrintHex("dQ=", dQ, "\n");
bdPrintHex("qInv=", qInv, "\n");
printf("n is %d bits\n", bdBitLength(n));
/* Clean up */
if (myseed) free(myseed);
bdFree(&g);
bdFree(&p1);
bdFree(&q1);
bdFree(&phi);
return 0;
}
#define KEYSIZE 1024
static int debug = 0;
int main(int argc, char *argv[])
{
size_t nbits = KEYSIZE; /* NB a multiple of 8 here */
int klen, mlen;
int npad, i;
unsigned char rb;
unsigned char block[(KEYSIZE+7)/8];
unsigned ee = 0x3;
size_t ntests = 50;
unsigned char *seed = NULL;
size_t seedlen = 0;
char msgstr[sizeof(block)];
int nchars;
unsigned char *pmsg = "abc"; /* Default message */
BIGD n, e, d, p, q, dP, dQ, qInv;
BIGD m, c, s, hq, h, m1, m2;
int res;
clock_t start, finish;
double tinv, tcrt;
/* MSVC memory leak checking stuff */
#if _MSC_VER >= 1100
_CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
_CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_FILE );
_CrtSetReportFile( _CRT_WARN, _CRTDBG_FILE_STDOUT );
_CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_FILE );
_CrtSetReportFile( _CRT_ERROR, _CRTDBG_FILE_STDOUT );
_CrtSetReportMode( _CRT_ASSERT, _CRTDBG_MODE_FILE );
_CrtSetReportFile( _CRT_ASSERT, _CRTDBG_FILE_STDOUT );
#endif
if (argc > 1)
{ /* Use message supplied in command line */
pmsg = (unsigned char*)argv[1];
}
printf("Test BIGDIGITS with a new %d-bit RSA key and given message data.\n", nbits);
/* Initialise */
p = bdNew();
q = bdNew();
n = bdNew();
e = bdNew();
d = bdNew();
dP= bdNew();
dQ= bdNew();
qInv= bdNew();
m = bdNew();
c = bdNew();
s = bdNew();
m1 = bdNew();
m2 = bdNew();
h = bdNew();
hq = bdNew();
/* Create RSA key pair (n, e),(d, p, q, dP, dQ, qInv) */
/* NB you should use a proper cryptographically-secure RNG */
res = generateRSAKey(n, e, d, p, q, dP, dQ, qInv, nbits, ee, ntests, seed, seedlen, bdRandomOctets);
if (res != 0)
{
printf("Failed to generate RSA key!\n");
goto clean_up;
}
/* Create a PKCS#1 v1.5 EME message block in octet format */
/*
|<-----------------(klen bytes)--------------->|
+--+--+-------+--+-----------------------------+
|00|02|PADDING|00| DATA TO ENCRYPT |
+--+--+-------+--+-----------------------------+
The padding is made up of _at least_ eight non-zero random bytes.
*/
/* How big is the key in octets (8-bit bytes)? */
klen = (nbits + 7) / 8;
/* CAUTION: make sure the block is at least klen bytes long */
memset(block, 0, klen);
mlen = strlen(pmsg);
npad = klen - mlen - 3;
if (npad < 8) /* Note npad is a signed int, not a size_t */
{
printf("Message is too long\n");
exit(1);
}
/* Display */
printf("Message='%s' ", pmsg);
pr_bytesmsg("0x", pmsg, strlen((char*)pmsg));
/* Create encryption block */
block[0] = 0x00;
block[1] = 0x02;
/* Generate npad non-zero padding bytes - rand() is OK */
srand((unsigned)time(NULL));
for (i = 0; i < npad; i++)
{
while ((rb = (rand() & 0xFF)) == 0)
;/* loop until non-zero*/
block[i+2] = rb;
}
block[npad+2] = 0x00;
memcpy(&block[npad+3], pmsg, mlen);
/* Convert to BIGD format */
bdConvFromOctets(m, block, klen);
bdPrintHex("m=\n", m, "\n");
/* Encrypt c = m^e mod n */
bdModExp(c, m, e, n);
bdPrintHex("c=\n", c, "\n");
/* Check decrypt m1 = c^d mod n */
start = clock();
bdModExp(m1, c, d, n);
finish = clock();
tinv = (double)(finish - start) / CLOCKS_PER_SEC;
bdPrintHex("m'=\n", m1, "\n");
res = bdCompare(m1, m);
printf("Decryption %s\n", (res == 0 ? "OK" : "FAILED!"));
assert(res == 0);
printf("Decrypt by inversion took %.3f secs\n", tinv);
/* Extract the message bytes from the decrypted block */
memset(block, 0, klen);
bdConvToOctets(m, block, klen);
assert(block[0] == 0x00);
assert(block[1] == 0x02);
for (i = 2; i < klen; i++)
{ /* Look for zero separating byte */
if (block[i] == 0x00)
break;
}
if (i >= klen)
printf("ERROR: failed to find message in decrypted block\n");
else
{
nchars = klen - i - 1;
memcpy(msgstr, &block[i+1], nchars);
msgstr[nchars] = '\0';
printf("Decrypted message is '%s'\n", msgstr);
}
/* Sign s = m^d mod n (NB m is not a valid PKCS-v1_5 signature block) */
bdModExp(s, m, d, n);
bdPrintHex("s=\n", s, "\n");
/* Continue as original t_bdRSA ... */
/* Check verify m1 = s^e mod n */
bdModExp(m1, s, e, n);
bdPrintHex("m'=\n", m1, "\n");
res = bdCompare(m1, m);
printf("Verification %s\n", (res == 0 ? "OK" : "FAILED!"));
assert(res == 0);
/* Decrypt using CRT method - Ref: PKCS #1 */
bdPrintHex("m=", m, "\n");
bdPrintHex("c=", c, "\n");
bdPrintHex("p=", p, "\n");
bdPrintHex("q=", q, "\n");
start = clock();
/* Let m_1 = c^dP mod p. */
bdModExp(m1, c, dP, p);
if(debug)bdPrintHex("m_1=c^dP mod p=", m1, "\n");
/* Let m_2 = c^dQ mod q. */
bdModExp(m2, c, dQ, q);
if(debug)bdPrintHex("m_2=c^dQ mod q=", m2, "\n");
if (bdCompare(m1, m2) < 0)
bdAdd(m1, m1, p);
bdSubtract(m1, m1, m2);
if(debug)bdPrintHex("m_1 - m_2=", m1, "\n");
/* Let h = qInv ( m_1 - m_2 ) mod p. */
bdModMult(h, qInv, m1, p);
if(debug)bdPrintHex("h=qInv(m1-m2) mod p=", h, "\n");
bdMultiply(hq, h, q);
if(debug)bdPrintHex("hq=", hq, "\n");
/* Let m = m_2 + hq. */
bdAdd(m1, m2, hq);
finish = clock();
tcrt = (double)(finish - start) / CLOCKS_PER_SEC;
if(debug)bdPrintHex("m'=m_2 + hq=", m1, "\n");
bdPrintHex("(CRT)m'=\n", m1, "\n");
res = bdCompare(m1, m);
printf("CRT Decryption %s\n", (res == 0 ? "OK" : "FAILED!"));
assert(res == 0);
printf("Decrypt by CRT took %.3f secs\n", tcrt);
printf("c.f. Decrypt by inversion %.3f secs (factor = %.1f)\n",
tinv, (tcrt ? tinv / tcrt : 0));
printf("n is %d bits\n", bdBitLength(n));
/* Clean up */
clean_up:
bdFree(&n);
bdFree(&e);
bdFree(&d);
bdFree(&p);
bdFree(&q);
bdFree(&dP);
bdFree(&dQ);
bdFree(&qInv);
bdFree(&m);
bdFree(&c);
bdFree(&s);
bdFree(&m1);
bdFree(&m2);
bdFree(&h);
bdFree(&hq);
/* Show the current version number */
printf("Version=%d\n", bdVersion());
printf("OK, successfully completed tests.\n");
return 0;
}

View File

@@ -1,245 +1,245 @@
/* $Id: t_bdRSA_blinded.c $ */
/* Carry out RSA calculations using constant-time exponentiation and blinding */
/***** BEGIN LICENSE BLOCK *****
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Copyright (c) 2001-16 David Ireland, D.I. Management Services Pty Limited
* <http://www.di-mgt.com.au/bigdigits.html>. All rights reserved.
*
***** END LICENSE BLOCK *****/
/*
* Last updated:
* $Date: 2016-03-31 09:51:00 $
* $Revision: 2.6.1 $
* $Author: dai $
*/
#if _MSC_VER >= 1100
/* Detect memory leaks in MSVC++ */
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#else
#include <stdlib.h>
#endif
#include <stdio.h>
#include <time.h>
#include <assert.h>
#include "bigd.h"
#include "bigdRand.h"
int main(void)
{
size_t nbits;
BIGD N, e, d;
BIGD m, c, r, g, R, S, x, z, y;
int isequal;
size_t i;
clock_t start, finish;
double tinv, tinv_ct, tblind;
int b;
const size_t ntimes = 3;
/* MSVC memory leak checking stuff */
#if _MSC_VER >= 1100
_CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
_CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_FILE );
_CrtSetReportFile( _CRT_WARN, _CRTDBG_FILE_STDOUT );
_CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_FILE );
_CrtSetReportFile( _CRT_ERROR, _CRTDBG_FILE_STDOUT );
_CrtSetReportMode( _CRT_ASSERT, _CRTDBG_MODE_FILE );
_CrtSetReportFile( _CRT_ASSERT, _CRTDBG_FILE_STDOUT );
#endif
printf("Carry out RSA calculation using constant-time exponentiation and blinding.\n");
/* Initialise */
bdNewVars(&N, &e, &d, &m, &c, &y, &r, &g, &R, &S, &x, &z);
/* Read in public and private keys as BIGDs */
/*
Source: Alice's 1024-bit RSA key from [RFC4134]:
/* $Id: t_bdRSA_blinded.c $ */
/* Carry out RSA calculations using constant-time exponentiation and blinding */
/***** BEGIN LICENSE BLOCK *****
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Copyright (c) 2001-16 David Ireland, D.I. Management Services Pty Limited
* <http://www.di-mgt.com.au/bigdigits.html>. All rights reserved.
*
***** END LICENSE BLOCK *****/
/*
* Last updated:
* $Date: 2016-03-31 09:51:00 $
* $Revision: 2.6.1 $
* $Author: dai $
*/
#if _MSC_VER >= 1100
/* Detect memory leaks in MSVC++ */
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#else
#include <stdlib.h>
#endif
#include <stdio.h>
#include <time.h>
#include <assert.h>
#include "bigd.h"
#include "bigdRand.h"
int main(void)
{
size_t nbits;
BIGD N, e, d;
BIGD m, c, r, g, R, S, x, z, y;
int isequal;
size_t i;
clock_t start, finish;
double tinv, tinv_ct, tblind;
int b;
const size_t ntimes = 3;
/* MSVC memory leak checking stuff */
#if _MSC_VER >= 1100
_CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
_CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_FILE );
_CrtSetReportFile( _CRT_WARN, _CRTDBG_FILE_STDOUT );
_CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_FILE );
_CrtSetReportFile( _CRT_ERROR, _CRTDBG_FILE_STDOUT );
_CrtSetReportMode( _CRT_ASSERT, _CRTDBG_MODE_FILE );
_CrtSetReportFile( _CRT_ASSERT, _CRTDBG_FILE_STDOUT );
#endif
printf("Carry out RSA calculation using constant-time exponentiation and blinding.\n");
/* Initialise */
bdNewVars(&N, &e, &d, &m, &c, &y, &r, &g, &R, &S, &x, &z);
/* Read in public and private keys as BIGDs */
/*
Source: Alice's 1024-bit RSA key from [RFC4134]:
Hoffman, P., Ed., "Examples of S/MIME Messages", RFC 4134, July 2005.
*/
bdConvFromHex(N, "E08973398DD8F5F5E88776397F4EB005BB5383DE0FB7ABDC7DC775290D052E6D12DFA68626D4D26FAA5829FC97ECFA82510F3080BEB1509E4644F12CBBD832CFC6686F07D9B060ACBEEE34096A13F5F7050593DF5EBA3556D961FF197FC981E6F86CEA874070EFAC6D2C749F2DFA553AB9997702A648528C4EF357385774575F");
bdConvFromHex(e, "010001");
bdConvFromHex(d, "A403C327477634346CA686B57949014B2E8AD2C862B2C7D748096A8B91F736F275D6E8CD15906027314735644D95CD6763CEB49F56AC2F376E1CEE0EBF282DF439906F34D86E085BD5656AD841F313D72D395EFE33CBFF29E4030B3D05A28FB7F18EA27637B07957D32F2BDE8706227D04665EC91BAF8B1AC3EC9144AB7F21");
printf("Public key:\n");
bdPrintHex("N=", N, "\n");
bdPrintHex("e=", e, "\n");
printf("Private key:\n");
bdPrintHex("d=", d, "\n");
nbits = bdBitLength(N);
printf("Key size = %d bits\n", nbits);
/* Set a random message m < N */
bdQuickRandBits(m, nbits-8);
bdPrintHex("Random plaintext m =\n", m, "\n");
/* Encrypt c = m^e mod N */
/* NB no need to use constant-time modexp when using public exponent */
bdModExp(c, m, e, N);
bdPrintHex("Ciphertext c=m^e mod N=\n", c, "\n");
printf("\nSIMPLE DECRYPTION USING PRIVATE EXPONENT...\n");
/* Check decrypt m1 = c^d mod N */
start = clock();
/* Use standard non-constant-time modexp with private exponent
=> faster but vulnerable to simple power attack (SPA) */
bdModExp(y, c, d, N);
finish = clock();
tinv = (double)(finish - start) / CLOCKS_PER_SEC;
bdPrintHex("y=c^d mod N (standard)\n", y, "\n");
isequal = bdCompare_ct(y, m);
printf("Decryption %s\n", (isequal == 0 ? "OK" : "FAILED!"));
assert(isequal == 0);
printf("Decryption by standard modexp took %.3f secs\n", tinv);
/* Now decrypt using constant-time modexp */
start = clock();
/* Resistant to simple power attack, but not differential power analysis (DPA) */
bdModExp_ct(y, c, d, N);
finish = clock();
tinv_ct = (double)(finish - start) / CLOCKS_PER_SEC;
bdPrintHex("y=c^d mod N (constant-time)\n", y, "\n");
isequal = bdCompare_ct(y, m);
printf("Decryption %s\n", (isequal == 0 ? "OK" : "FAILED!"));
assert(isequal == 0);
printf("Decryption by constant-time modexp took %.3f secs\n", tinv_ct);
printf("Ratio constant-time/standard = %.3f\n", tinv_ct / tinv);
/*
USE BLINDING TO DEFEAT DPA
Differential power analysis depends on the attacker knowing the base c of the exponentiation.
This can succeed even if constant-time exponentiation is used.
Ref: Jean-Sebastian Coron, "Resistance Against Differential Power Analysis for
Elliptic Curve Cryptosystems", August 1999.
-- This version adapted from Coron's elliptic curve point scalar multiplication
to RSA-style modular exponentiation.
*/
/* Algorithm: Modular exponentiation with blinding.
Input: RSA ciphertext c, private exponent d, public exponent e, modulus N
Output: RSA plaintext c^d mod N
1. Select a random integer r < N with gcd(r,N) = 1
2. Compute R = r^e mod N and S = r^-1 mod N
3. Compute x = c.R mod N
4. Compute z = x^d mod N
5. Compute y = S.z mod N
6. Return y
*/
/*
You could store the values R and S initially and refresh on each execution by
R <-- R^{2(-1)^b}
S <-- S^{2(-1)^b}
where b is a random bit generated at each new execution.
*/
printf("\nUSING BLINDING...\n");
start = clock();
printf("1. Select a random integer r < N with gcd(r,N) = 1 \n");
do {
bdRandomBits(r, nbits);
bdModulo(r, r, N);
bdGcd(g, r, N);
} while (bdShortCmp(g, 1) != 0);
bdPrintHex("r=", r, "\n");
bdPrintHex("[CHECK] gcd(r,n)=", g, "\n");
printf("2. Compute R = r^e mod N and S = r^-1 mod N \n");
bdModExp(R, r, e, N); /* NB public exponent, so no need for CT */
bdModInv(S, r, N);
bdPrintHex("R=r^e mod N=", R, "\n");
bdPrintHex("S=r^-1 mod N=", S, "\n");
printf("3. Compute x = c.R mod N \n");
bdModMult(x, c, R, N);
bdPrintHex("x = c.R mod N=", x, "\n");
printf("4. Compute z = x^d mod N \n");
bdModExp_ct(z, x, d, N);
bdPrintHex("z = b^d mod N=", z, "\n");
printf("5. Compute y = S.z mod N \n");
bdModMult(y, S, z, N);
bdPrintHex("y = S.z mod N=", y, "\n");
finish = clock(); /* Assume effect of printing is negligible (?) */
tblind = (double)(finish - start) / CLOCKS_PER_SEC;
printf("6. Return y = c^d mod N \n");
isequal = bdCompare_ct(y, m);
printf("Decryption %s\n", (isequal == 0 ? "OK" : "FAILED!"));
assert(isequal == 0);
printf("Decryption using blinding took %.3f secs\n", tblind);
printf("Ratio blinding/standard (with printing) = %.3f\n", tblind / tinv);
printf("\nREPEAT WITH REFRESHED R AND S...\n");
tblind = 0;
for (i = 0; i < ntimes; i++) {
printf("Iteration number %d:\n", i+1);
/* Generate a random bit */
b = bdRandDigit() & 0x1;
printf("Random bit b=%d\n", b);
start = clock();
/* R <-- R^{2(-1)^b}, S <-- S^{2(-1)^b} */
bdModMult(R, R, R, N);
bdModMult(S, S, S, N);
if (b) {
bdModInv(R, R, N);
bdModInv(S, S, N);
}
/* 3. Compute x = c.R mod N */
bdModMult(x, c, R, N);
/* 4. Compute z = x^d mod N */
bdModExp_ct(z, x, d, N);
/* 5. Compute y = S.z mod N */
bdModMult(y, S, z, N);
finish = clock();
tblind += (double)(finish - start) / CLOCKS_PER_SEC;
bdPrintHex("R <-- R^{2(-1)^b}=\n", R, "\n");
bdPrintHex("S <-- S^{2(-1)^b}=\n", S, "\n");
/* 6. Return y = c^d mod N */
bdPrintHex("Output y=\n", y, "\n");
isequal = bdCompare_ct(y, m);
printf("Decryption %s\n", (isequal == 0 ? "OK" : "FAILED!"));
assert(isequal == 0);
printf("\n");
}
tblind /= ntimes;
printf("Decryption using blinding took on average %.3f secs over %d repeats\n", tblind, ntimes);
printf("Ratio blinding/standard = %.3f\n", tblind / tinv);
/* Clean up */
bdFreeVars(&N, &e, &d, &m, &c, &y, &r, &g, &R, &S, &x, &z);
printf("\nOK, SUCCESSFULLY COMPLETED TESTS WITHOUT ERROR.\n");
return 0;
}
*/
bdConvFromHex(N, "E08973398DD8F5F5E88776397F4EB005BB5383DE0FB7ABDC7DC775290D052E6D12DFA68626D4D26FAA5829FC97ECFA82510F3080BEB1509E4644F12CBBD832CFC6686F07D9B060ACBEEE34096A13F5F7050593DF5EBA3556D961FF197FC981E6F86CEA874070EFAC6D2C749F2DFA553AB9997702A648528C4EF357385774575F");
bdConvFromHex(e, "010001");
bdConvFromHex(d, "A403C327477634346CA686B57949014B2E8AD2C862B2C7D748096A8B91F736F275D6E8CD15906027314735644D95CD6763CEB49F56AC2F376E1CEE0EBF282DF439906F34D86E085BD5656AD841F313D72D395EFE33CBFF29E4030B3D05A28FB7F18EA27637B07957D32F2BDE8706227D04665EC91BAF8B1AC3EC9144AB7F21");
printf("Public key:\n");
bdPrintHex("N=", N, "\n");
bdPrintHex("e=", e, "\n");
printf("Private key:\n");
bdPrintHex("d=", d, "\n");
nbits = bdBitLength(N);
printf("Key size = %d bits\n", nbits);
/* Set a random message m < N */
bdQuickRandBits(m, nbits-8);
bdPrintHex("Random plaintext m =\n", m, "\n");
/* Encrypt c = m^e mod N */
/* NB no need to use constant-time modexp when using public exponent */
bdModExp(c, m, e, N);
bdPrintHex("Ciphertext c=m^e mod N=\n", c, "\n");
printf("\nSIMPLE DECRYPTION USING PRIVATE EXPONENT...\n");
/* Check decrypt m1 = c^d mod N */
start = clock();
/* Use standard non-constant-time modexp with private exponent
=> faster but vulnerable to simple power attack (SPA) */
bdModExp(y, c, d, N);
finish = clock();
tinv = (double)(finish - start) / CLOCKS_PER_SEC;
bdPrintHex("y=c^d mod N (standard)\n", y, "\n");
isequal = bdCompare_ct(y, m);
printf("Decryption %s\n", (isequal == 0 ? "OK" : "FAILED!"));
assert(isequal == 0);
printf("Decryption by standard modexp took %.3f secs\n", tinv);
/* Now decrypt using constant-time modexp */
start = clock();
/* Resistant to simple power attack, but not differential power analysis (DPA) */
bdModExp_ct(y, c, d, N);
finish = clock();
tinv_ct = (double)(finish - start) / CLOCKS_PER_SEC;
bdPrintHex("y=c^d mod N (constant-time)\n", y, "\n");
isequal = bdCompare_ct(y, m);
printf("Decryption %s\n", (isequal == 0 ? "OK" : "FAILED!"));
assert(isequal == 0);
printf("Decryption by constant-time modexp took %.3f secs\n", tinv_ct);
printf("Ratio constant-time/standard = %.3f\n", tinv_ct / tinv);
/*
USE BLINDING TO DEFEAT DPA
Differential power analysis depends on the attacker knowing the base c of the exponentiation.
This can succeed even if constant-time exponentiation is used.
Ref: Jean-Sebastian Coron, "Resistance Against Differential Power Analysis for
Elliptic Curve Cryptosystems", August 1999.
-- This version adapted from Coron's elliptic curve point scalar multiplication
to RSA-style modular exponentiation.
*/
/* Algorithm: Modular exponentiation with blinding.
Input: RSA ciphertext c, private exponent d, public exponent e, modulus N
Output: RSA plaintext c^d mod N
1. Select a random integer r < N with gcd(r,N) = 1
2. Compute R = r^e mod N and S = r^-1 mod N
3. Compute x = c.R mod N
4. Compute z = x^d mod N
5. Compute y = S.z mod N
6. Return y
*/
/*
You could store the values R and S initially and refresh on each execution by
R <-- R^{2(-1)^b}
S <-- S^{2(-1)^b}
where b is a random bit generated at each new execution.
*/
printf("\nUSING BLINDING...\n");
start = clock();
printf("1. Select a random integer r < N with gcd(r,N) = 1 \n");
do {
bdRandomBits(r, nbits);
bdModulo(r, r, N);
bdGcd(g, r, N);
} while (bdShortCmp(g, 1) != 0);
bdPrintHex("r=", r, "\n");
bdPrintHex("[CHECK] gcd(r,n)=", g, "\n");
printf("2. Compute R = r^e mod N and S = r^-1 mod N \n");
bdModExp(R, r, e, N); /* NB public exponent, so no need for CT */
bdModInv(S, r, N);
bdPrintHex("R=r^e mod N=", R, "\n");
bdPrintHex("S=r^-1 mod N=", S, "\n");
printf("3. Compute x = c.R mod N \n");
bdModMult(x, c, R, N);
bdPrintHex("x = c.R mod N=", x, "\n");
printf("4. Compute z = x^d mod N \n");
bdModExp_ct(z, x, d, N);
bdPrintHex("z = b^d mod N=", z, "\n");
printf("5. Compute y = S.z mod N \n");
bdModMult(y, S, z, N);
bdPrintHex("y = S.z mod N=", y, "\n");
finish = clock(); /* Assume effect of printing is negligible (?) */
tblind = (double)(finish - start) / CLOCKS_PER_SEC;
printf("6. Return y = c^d mod N \n");
isequal = bdCompare_ct(y, m);
printf("Decryption %s\n", (isequal == 0 ? "OK" : "FAILED!"));
assert(isequal == 0);
printf("Decryption using blinding took %.3f secs\n", tblind);
printf("Ratio blinding/standard (with printing) = %.3f\n", tblind / tinv);
printf("\nREPEAT WITH REFRESHED R AND S...\n");
tblind = 0;
for (i = 0; i < ntimes; i++) {
printf("Iteration number %d:\n", i+1);
/* Generate a random bit */
b = bdRandDigit() & 0x1;
printf("Random bit b=%d\n", b);
start = clock();
/* R <-- R^{2(-1)^b}, S <-- S^{2(-1)^b} */
bdModMult(R, R, R, N);
bdModMult(S, S, S, N);
if (b) {
bdModInv(R, R, N);
bdModInv(S, S, N);
}
/* 3. Compute x = c.R mod N */
bdModMult(x, c, R, N);
/* 4. Compute z = x^d mod N */
bdModExp_ct(z, x, d, N);
/* 5. Compute y = S.z mod N */
bdModMult(y, S, z, N);
finish = clock();
tblind += (double)(finish - start) / CLOCKS_PER_SEC;
bdPrintHex("R <-- R^{2(-1)^b}=\n", R, "\n");
bdPrintHex("S <-- S^{2(-1)^b}=\n", S, "\n");
/* 6. Return y = c^d mod N */
bdPrintHex("Output y=\n", y, "\n");
isequal = bdCompare_ct(y, m);
printf("Decryption %s\n", (isequal == 0 ? "OK" : "FAILED!"));
assert(isequal == 0);
printf("\n");
}
tblind /= ntimes;
printf("Decryption using blinding took on average %.3f secs over %d repeats\n", tblind, ntimes);
printf("Ratio blinding/standard = %.3f\n", tblind / tinv);
/* Clean up */
bdFreeVars(&N, &e, &d, &m, &c, &y, &r, &g, &R, &S, &x, &z);
printf("\nOK, SUCCESSFULLY COMPLETED TESTS WITHOUT ERROR.\n");
return 0;
}

View File

@@ -1,124 +1,124 @@
/* $Id: t_bdRandomOctets.c $ */
/* Examples using the `bigdRand` functions:
bdRandomOctets()
bdRandomSeeded()
bdRandomNumber()
*/
/***** BEGIN LICENSE BLOCK *****
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Copyright (c) 2001-16 David Ireland, D.I. Management Services Pty Limited
* <http://www.di-mgt.com.au/bigdigits.html>. All rights reserved.
*
***** END LICENSE BLOCK *****/
/*
* Last updated:
* $Date: 2016-03-31 09:51:00 $
* $Revision: 2.6.1 $
* $Author: dai $
*/
#include <stdio.h>
#include <assert.h>
#include <math.h> // For sqrt in statistics
#include "bigd.h"
#include "bigdRand.h"
#define TEST_LEN 24
#define TEST_N 32
#define NTESTS (TEST_N * 10)
static void pr_byteshex(const char *prefix, const unsigned char *bytes, size_t nbytes, const char *suffix)
{
size_t i;
if (prefix) printf("%s", prefix);
for (i = 0; i < nbytes; i++)
{
printf("%02X", bytes[i]);
}
if (suffix) printf("%s", suffix);
}
int main(void)
{
unsigned char bytes[TEST_LEN];
size_t nbytes;
int ntests, itest, i;
BIGD a, p, N;
int score[TEST_N] = { 0 };
int t;
BIGD temp;
int themin, themax;
double mean, var, sd;
ntests = TEST_LEN;
printf("Testing bdRandomOctets...\n");
for (itest = 0; itest < ntests; itest++)
{
//printf("Test %d...\n", itest+1);
nbytes = TEST_LEN - itest;
bdRandomOctets(bytes, nbytes, NULL, 0);
pr_byteshex("", bytes, nbytes, "\n");
}
// Now test bdRandomSeeded calling internal fn bdRandomOctets
printf("Testing bdRandomSeeded with bdRandomOctets()...\n");
a = bdNew();
for (i = 0; i < 10; i++)
{
bdRandomSeeded(a, 128, NULL, 0, bdRandomOctets);
bdPrintHex("r=", a, "\n");
}
// And generate some primes
printf("Generating primes with bdGeneratePrime() calling bdRandomOctets()...\n");
p = bdNew();
for (i = 0; i < 4; i++)
{
bdGeneratePrime(p, 256, 128, NULL, 0, bdRandomOctets);
bdPrintHex("p=", p, "\n");
}
// Generate some random numbers in the range [0,N-1] where N = 32
// (and keep score of count for each value)
temp = bdNew();
N = bdNew();
bdSetShort(N, TEST_N);
bdPrintDecimal("Random numbers in the range [0,N-1] computed by bdRandomNumber(N), N=", N, ":\n");
for (i = 0; i < NTESTS; i++)
{
bdRandomNumber(a, N);
bdPrintDecimal("", a, " ");
/* Convert BIGD into an int */
t = (int)bdShortMod(temp, a, 0xFFFFFFFF);
assert(0 <= t && t < TEST_N);
score[t] += 1;
}
printf("\n");
printf("[Statistics] Distribution over %d tests (EV=%.1f):\n", NTESTS, (double)NTESTS / TEST_N);
mean = var = 0.0;
themin = 99999;
themax = 0;
for (i = 0; i < TEST_N; i++)
{
int v = score[i];
printf("%d ", v);
if (v > themax) themax = v;
if (v < themin) themin = v;
mean += (double)v;
var += v * v;
}
printf("\n");
mean /= TEST_N;
var = var / TEST_N - mean*mean;
sd = sqrt(var);
printf("mean=%.3f sd=%.3f min=%d (%.2f sd) max=%d (%+.2f sd)\n",
mean, sd, themin, (themin-mean)/sd, themax, (themax-mean)/sd);
return 0;
}
/* $Id: t_bdRandomOctets.c $ */
/* Examples using the `bigdRand` functions:
bdRandomOctets()
bdRandomSeeded()
bdRandomNumber()
*/
/***** BEGIN LICENSE BLOCK *****
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Copyright (c) 2001-16 David Ireland, D.I. Management Services Pty Limited
* <http://www.di-mgt.com.au/bigdigits.html>. All rights reserved.
*
***** END LICENSE BLOCK *****/
/*
* Last updated:
* $Date: 2016-03-31 09:51:00 $
* $Revision: 2.6.1 $
* $Author: dai $
*/
#include <stdio.h>
#include <assert.h>
#include <math.h> // For sqrt in statistics
#include "bigd.h"
#include "bigdRand.h"
#define TEST_LEN 24
#define TEST_N 32
#define NTESTS (TEST_N * 10)
static void pr_byteshex(const char *prefix, const unsigned char *bytes, size_t nbytes, const char *suffix)
{
size_t i;
if (prefix) printf("%s", prefix);
for (i = 0; i < nbytes; i++)
{
printf("%02X", bytes[i]);
}
if (suffix) printf("%s", suffix);
}
int main(void)
{
unsigned char bytes[TEST_LEN];
size_t nbytes;
int ntests, itest, i;
BIGD a, p, N;
int score[TEST_N] = { 0 };
int t;
BIGD temp;
int themin, themax;
double mean, var, sd;
ntests = TEST_LEN;
printf("Testing bdRandomOctets...\n");
for (itest = 0; itest < ntests; itest++)
{
//printf("Test %d...\n", itest+1);
nbytes = TEST_LEN - itest;
bdRandomOctets(bytes, nbytes, NULL, 0);
pr_byteshex("", bytes, nbytes, "\n");
}
// Now test bdRandomSeeded calling internal fn bdRandomOctets
printf("Testing bdRandomSeeded with bdRandomOctets()...\n");
a = bdNew();
for (i = 0; i < 10; i++)
{
bdRandomSeeded(a, 128, NULL, 0, bdRandomOctets);
bdPrintHex("r=", a, "\n");
}
// And generate some primes
printf("Generating primes with bdGeneratePrime() calling bdRandomOctets()...\n");
p = bdNew();
for (i = 0; i < 4; i++)
{
bdGeneratePrime(p, 256, 128, NULL, 0, bdRandomOctets);
bdPrintHex("p=", p, "\n");
}
// Generate some random numbers in the range [0,N-1] where N = 32
// (and keep score of count for each value)
temp = bdNew();
N = bdNew();
bdSetShort(N, TEST_N);
bdPrintDecimal("Random numbers in the range [0,N-1] computed by bdRandomNumber(N), N=", N, ":\n");
for (i = 0; i < NTESTS; i++)
{
bdRandomNumber(a, N);
bdPrintDecimal("", a, " ");
/* Convert BIGD into an int */
t = (int)bdShortMod(temp, a, 0xFFFFFFFF);
assert(0 <= t && t < TEST_N);
score[t] += 1;
}
printf("\n");
printf("[Statistics] Distribution over %d tests (EV=%.1f):\n", NTESTS, (double)NTESTS / TEST_N);
mean = var = 0.0;
themin = 99999;
themax = 0;
for (i = 0; i < TEST_N; i++)
{
int v = score[i];
printf("%d ", v);
if (v > themax) themax = v;
if (v < themin) themin = v;
mean += (double)v;
var += v * v;
}
printf("\n");
mean /= TEST_N;
var = var / TEST_N - mean*mean;
sd = sqrt(var);
printf("mean=%.3f sd=%.3f min=%d (%.2f sd) max=%d (%+.2f sd)\n",
mean, sd, themin, (themin-mean)/sd, themax, (themax-mean)/sd);
return 0;
}

View File

@@ -1,156 +1,156 @@
/* $Id: t_bdRsaCrack.c $ */
/*
This code uses the free BIGDIGITS library version 2.3 available from
http://di-mgt.com.au/bigdigits.html
to show how the Chinese Remainder Theorem and Gauss's Method can be used
to find a message encrypted by the RSA algorithm without having to factor
the modulus. The same message must have been encrypted with public exponent
e = 3 to three different recipients without any random padding.
Ref: http://www.di-mgt.com.au/crt.html#crackingrsa
Copyright (C) 2011 DI Management Services Pty Ltd. All rights reserved.
*/
/*
Last updated:
$Date: 2011-11-11 11:11:11 $
$Author: dai $
*/
#include <stdio.h>
#include "bigd.h"
int debug = 0;
int main(void)
{
BIGD m, e, n1, n2, n3, c1, c2, c3, N, N1, N2, N3, d1, d2, d3, s, t, x;
m = bdNew();
e = bdNew();
n1 = bdNew();
n2 = bdNew();
n3 = bdNew();
c1 = bdNew();
c2 = bdNew();
c3 = bdNew();
N = bdNew();
N1 = bdNew();
N2 = bdNew();
N3 = bdNew();
d1 = bdNew();
d2 = bdNew();
d3 = bdNew();
s = bdNew();
t = bdNew();
x = bdNew();
/* Read in modulus values for three 512-bit public keys */
bdConvFromHex(n1, "A9C737DD808D02866FBF1ACF05DE2EB124137007A4965EC4DCBFA6D02F97E0123A8FD3691E414A1382F38AB39B09975705ECEAF1131A283C937B309F1C1417F9");
bdConvFromHex(n2, "B7E9E114A08ADFF12F762D7F0E1F16202E1EB7A7F2852369BDF44865783D19111E6D61B31DE987BCB9775099E220A798D4F99CD3E5F04C64F87A35C0268A83E9");
bdConvFromHex(n3, "C2BDBD4E36BA20D37D5D1E968F09F2FC7B41A97F3052274E4892D50D5FB337C923048AED7D393135EE55711E5C74975867F13D3845BAC9588B4BE170D08BAB57");
//bdSetShort(n1, 87);
//bdSetShort(n2, 115);
//bdSetShort(n3, 187);
printf("Three public modulus values, 512 bits each...\n");
bdPrintHex("n1=", n1, "\n");
bdPrintHex("n2=", n2, "\n");
bdPrintHex("n3=", n3, "\n");
/* The three public keys all have public exponent e = 3 */
bdSetShort(e, 3);
bdPrintHex("e=", e, "\n");
/* Set the common message m with no random padding (but large enough so m^3 > n_i) */
bdConvFromHex(m, "02ffffffffffffffffffffffffffffffffffffffffff0000deadbeefcafe");
//bdSetShort(m, 10);
printf("Message to be encrypted...\n");
bdPrintHex("m=", m, "\n");
/* Create three ciphertexts, c_i = m^e mod n_i */
bdModExp(c1, m, e, n1);
bdModExp(c2, m, e, n2);
bdModExp(c3, m, e, n3);
printf("Three ciphertexts...\n");
bdPrintHex("c1=", c1, "\n");
bdPrintHex("c2=", c2, "\n");
bdPrintHex("c3=", c3, "\n");
/* An eavedropper has the public values n1, n2, n3, c1, c2 and c3 */
/* Check that n1, n2, n3 are coprime in pairs */
bdGcd(t, n1, n2);
bdPrintHex("gcd(n1,n2)=", t, "\n");
bdGcd(t, n2, n3);
bdPrintHex("gcd(n2,n3)=", t, "\n");
bdGcd(t, n3, n1);
bdPrintHex("gcd(n3,n1)=", t, "\n");
/* Compute N = n1 * n2 * n3 */
bdMultiply(t, n1, n2);
bdMultiply(N, t, n3);
if (debug) bdPrintDecimal("N=", N, "\n");
/* Compute N_i = N/n_i for i = 1,2,3 */
bdMultiply(N1, n2, n3);
bdMultiply(N2, n1, n3);
bdMultiply(N3, n1, n2);
if (debug) bdPrintDecimal("N1=", N1, "\n");
if (debug) bdPrintDecimal("N2=", N2, "\n");
if (debug) bdPrintDecimal("N3=", N3, "\n");
/* Compute d_i = N_i^{-1} mod n_i for i = 1,2,3 */
bdModInv(d1, N1, n1);
bdModInv(d2, N2, n2);
bdModInv(d3, N3, n3);
if (debug) bdPrintDecimal("d1=", d1, "\n");
if (debug) bdPrintDecimal("d2=", d2, "\n");
if (debug) bdPrintDecimal("d3=", d3, "\n");
/* Compute x = c_1 N_1 d_1 + c_2 N_2 d_2 + c_3 N_3 d_3 (mod N) */
bdModMult(s, c1, N1, N);
bdModMult(x, s, d1, N);
bdModMult(s, c2, N2, N);
bdModMult(t, s, d2, N);
bdAdd_s(x, x, t);
bdModMult(s, c3, N3, N);
bdModMult(t, s, d3, N);
bdAdd_s(s, x, t);
bdModulo(x, s, N);
printf("Computed value of x = c_1 N_1 d_1 + c_2 N_2 d_2 + c_3 N_3 d_3 (mod N)...\n");
bdPrintHex("x=", x, "\n");
/* Compute the integer cube root of x */
bdCubeRoot(t, x);
bdPrintHex("m'=cuberoot(x)=", t, "\n");
/* Do we have the correct answer? */
if (bdCompare(t, m) == 0)
printf("HOORAY! We have found the correct answer, m' = m.\n");
else
printf("OH BU**AR! We didn't find the correct answer.\n");
//clean_up:
bdFree(&m);
bdFree(&e);
bdFree(&n1);
bdFree(&n2);
bdFree(&n3);
bdFree(&c1);
bdFree(&c2);
bdFree(&c3);
bdFree(&N);
bdFree(&N1);
bdFree(&N2);
bdFree(&N3);
bdFree(&d1);
bdFree(&d2);
bdFree(&d3);
bdFree(&s);
bdFree(&t);
bdFree(&x);
return 0;
}
/* $Id: t_bdRsaCrack.c $ */
/*
This code uses the free BIGDIGITS library version 2.3 available from
http://di-mgt.com.au/bigdigits.html
to show how the Chinese Remainder Theorem and Gauss's Method can be used
to find a message encrypted by the RSA algorithm without having to factor
the modulus. The same message must have been encrypted with public exponent
e = 3 to three different recipients without any random padding.
Ref: http://www.di-mgt.com.au/crt.html#crackingrsa
Copyright (C) 2011 DI Management Services Pty Ltd. All rights reserved.
*/
/*
Last updated:
$Date: 2011-11-11 11:11:11 $
$Author: dai $
*/
#include <stdio.h>
#include "bigd.h"
int debug = 0;
int main(void)
{
BIGD m, e, n1, n2, n3, c1, c2, c3, N, N1, N2, N3, d1, d2, d3, s, t, x;
m = bdNew();
e = bdNew();
n1 = bdNew();
n2 = bdNew();
n3 = bdNew();
c1 = bdNew();
c2 = bdNew();
c3 = bdNew();
N = bdNew();
N1 = bdNew();
N2 = bdNew();
N3 = bdNew();
d1 = bdNew();
d2 = bdNew();
d3 = bdNew();
s = bdNew();
t = bdNew();
x = bdNew();
/* Read in modulus values for three 512-bit public keys */
bdConvFromHex(n1, "A9C737DD808D02866FBF1ACF05DE2EB124137007A4965EC4DCBFA6D02F97E0123A8FD3691E414A1382F38AB39B09975705ECEAF1131A283C937B309F1C1417F9");
bdConvFromHex(n2, "B7E9E114A08ADFF12F762D7F0E1F16202E1EB7A7F2852369BDF44865783D19111E6D61B31DE987BCB9775099E220A798D4F99CD3E5F04C64F87A35C0268A83E9");
bdConvFromHex(n3, "C2BDBD4E36BA20D37D5D1E968F09F2FC7B41A97F3052274E4892D50D5FB337C923048AED7D393135EE55711E5C74975867F13D3845BAC9588B4BE170D08BAB57");
//bdSetShort(n1, 87);
//bdSetShort(n2, 115);
//bdSetShort(n3, 187);
printf("Three public modulus values, 512 bits each...\n");
bdPrintHex("n1=", n1, "\n");
bdPrintHex("n2=", n2, "\n");
bdPrintHex("n3=", n3, "\n");
/* The three public keys all have public exponent e = 3 */
bdSetShort(e, 3);
bdPrintHex("e=", e, "\n");
/* Set the common message m with no random padding (but large enough so m^3 > n_i) */
bdConvFromHex(m, "02ffffffffffffffffffffffffffffffffffffffffff0000deadbeefcafe");
//bdSetShort(m, 10);
printf("Message to be encrypted...\n");
bdPrintHex("m=", m, "\n");
/* Create three ciphertexts, c_i = m^e mod n_i */
bdModExp(c1, m, e, n1);
bdModExp(c2, m, e, n2);
bdModExp(c3, m, e, n3);
printf("Three ciphertexts...\n");
bdPrintHex("c1=", c1, "\n");
bdPrintHex("c2=", c2, "\n");
bdPrintHex("c3=", c3, "\n");
/* An eavedropper has the public values n1, n2, n3, c1, c2 and c3 */
/* Check that n1, n2, n3 are coprime in pairs */
bdGcd(t, n1, n2);
bdPrintHex("gcd(n1,n2)=", t, "\n");
bdGcd(t, n2, n3);
bdPrintHex("gcd(n2,n3)=", t, "\n");
bdGcd(t, n3, n1);
bdPrintHex("gcd(n3,n1)=", t, "\n");
/* Compute N = n1 * n2 * n3 */
bdMultiply(t, n1, n2);
bdMultiply(N, t, n3);
if (debug) bdPrintDecimal("N=", N, "\n");
/* Compute N_i = N/n_i for i = 1,2,3 */
bdMultiply(N1, n2, n3);
bdMultiply(N2, n1, n3);
bdMultiply(N3, n1, n2);
if (debug) bdPrintDecimal("N1=", N1, "\n");
if (debug) bdPrintDecimal("N2=", N2, "\n");
if (debug) bdPrintDecimal("N3=", N3, "\n");
/* Compute d_i = N_i^{-1} mod n_i for i = 1,2,3 */
bdModInv(d1, N1, n1);
bdModInv(d2, N2, n2);
bdModInv(d3, N3, n3);
if (debug) bdPrintDecimal("d1=", d1, "\n");
if (debug) bdPrintDecimal("d2=", d2, "\n");
if (debug) bdPrintDecimal("d3=", d3, "\n");
/* Compute x = c_1 N_1 d_1 + c_2 N_2 d_2 + c_3 N_3 d_3 (mod N) */
bdModMult(s, c1, N1, N);
bdModMult(x, s, d1, N);
bdModMult(s, c2, N2, N);
bdModMult(t, s, d2, N);
bdAdd_s(x, x, t);
bdModMult(s, c3, N3, N);
bdModMult(t, s, d3, N);
bdAdd_s(s, x, t);
bdModulo(x, s, N);
printf("Computed value of x = c_1 N_1 d_1 + c_2 N_2 d_2 + c_3 N_3 d_3 (mod N)...\n");
bdPrintHex("x=", x, "\n");
/* Compute the integer cube root of x */
bdCubeRoot(t, x);
bdPrintHex("m'=cuberoot(x)=", t, "\n");
/* Do we have the correct answer? */
if (bdCompare(t, m) == 0)
printf("HOORAY! We have found the correct answer, m' = m.\n");
else
printf("OH BU**AR! We didn't find the correct answer.\n");
//clean_up:
bdFree(&m);
bdFree(&e);
bdFree(&n1);
bdFree(&n2);
bdFree(&n3);
bdFree(&c1);
bdFree(&c2);
bdFree(&c3);
bdFree(&N);
bdFree(&N1);
bdFree(&N2);
bdFree(&N3);
bdFree(&d1);
bdFree(&d2);
bdFree(&d3);
bdFree(&s);
bdFree(&t);
bdFree(&x);
return 0;
}

View File

@@ -1,226 +1,226 @@
/* $Id: t_bdRsaFactorN.c $ */
/*
This code uses the free BIGDIGITS library version 2.3 available from
http://di-mgt.com.au/bigdigits.html
to show how to factor the RSA modulus n given the secret exponent d
Copyright (C) 2012 DI Management Services Pty Ltd. All rights reserved.
*/
/*
Last updated:
$Date: 2012-12-24 16:13 $
$Revision: 1.0.1 $
$Author: dai $
*/
#include <stdio.h>
#include "bigd.h"
int debug = 1;
#define DBDPRINT(pre, x, post) if(debug)bdPrintDecimal((pre),(x),(post))
const int primes[] = {
2, 3, 5, 7, 11, 13, 17, 19, 23, 29,
31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
73, 79, 83, 89, 97, 101, 103, 107, 109, 113,
127, 131, 137, 139, 149, 151, 157, 163, 167, 173,
179, 181, 191, 193, 197, 199, 211, 223, 227, 229,
233, 239, 241, 251, 257, 263, 269, 271, 277, 281,
};
#define NPRIMES (sizeof(primes)/sizeof(primes[0]))
int find_factors_of_n(BIGD p, BIGD q, BIGD n, BIGD e, BIGD d)
{
BIGD k, t, g, x, y, r;
int i, isdone;
k = bdNew();
t = bdNew();
g = bdNew();
x = bdNew();
y = bdNew();
r = bdNew();
bdSetZero(p);
bdSetZero(q);
/* 1. [Initialize] Set k <-- de - 1 */
bdMultiply(k, d, e);
bdDecrement(k);
DBDPRINT("k=de-1=", k, "\n");
/* 2. [Try a random g] Choose g at random from {2, ..., N-1} */
/* (we cheat a bit here and just try the first primes in order) */
for (isdone = 0, i = 0; !isdone && i < NPRIMES; i++)
{
bdSetShort(g, primes[i]);
DBDPRINT("Trying g=", g, "\n");
/* Set t <-- k */
bdSetEqual(t, k);
/* 3. [Next t] If t is divisible by 2 ... */
while (bdIsEven(t))
{
/* Set t <-- t / 2 */
bdShiftRight(t, t, 1);
DBDPRINT("t=", t, "\n");
/* Set x = g^t mod N */
bdModExp(x, g, t, n);
DBDPRINT("x=g^t mod N=", x, "\n");
/* 4. [Finished?] If x > 1 and y = gcd(x-1, N)
then set p <-- y and q <-- N/y, output (p,q) and stop.
*/
if (bdShortCmp(x, 1) > 0)
{
bdDecrement(x);
bdGcd(y, x, n);
DBDPRINT("y=gcd(x-1,N)=", y, "\n");
if (bdShortCmp(y, 1) > 0)
{ /* We have it */
bdSetEqual(p, y);
bdDivide(q, r, n, y);
isdone = 1;
break;
}
}
} /* 4a. ... otherwise go to step 3. */
} /* 3a. ... otherwise go to step 2. */
/* Finally, to be consistent with convention, we make sure p > q */
if (isdone && bdCompare(p, q) < 0)
{
bdSetEqual(r, p);
bdSetEqual(p, q);
bdSetEqual(q, r);
}
bdFree(&k);
bdFree(&t);
bdFree(&g);
bdFree(&x);
bdFree(&y);
bdFree(&r);
return isdone;
}
void test_simple(void)
{
BIGD n, e, d, p, q;
n = bdNew();
e = bdNew();
d = bdNew();
p = bdNew();
q = bdNew();
bdSetShort(n, 25777);
bdSetShort(e, 3);
bdSetShort(d, 16971);
printf("Input:\n");
bdPrintDecimal("n=", n, "\n");
bdPrintDecimal("e=", e, "\n");
bdPrintDecimal("d=", d, "\n");
find_factors_of_n(p, q, n, e, d);
printf("Output:\n");
bdPrintDecimal("p=", p, "\n");
bdPrintDecimal("q=", q, "\n");
//clean_up:
bdFree(&n);
bdFree(&e);
bdFree(&d);
bdFree(&p);
bdFree(&q);
}
void test_508(void)
{
BIGD n, e, d, p, q;
n = bdNew();
e = bdNew();
d = bdNew();
p = bdNew();
q = bdNew();
/*
Using 508-bit RSA key from
"Some Examples of the PKCS Standards"
An RSA Laboratories Technical Note,
Burton S. Kaliski Jr., November 1, 1993
/* $Id: t_bdRsaFactorN.c $ */
/*
This code uses the free BIGDIGITS library version 2.3 available from
http://di-mgt.com.au/bigdigits.html
to show how to factor the RSA modulus n given the secret exponent d
Copyright (C) 2012 DI Management Services Pty Ltd. All rights reserved.
*/
/*
Last updated:
$Date: 2012-12-24 16:13 $
$Revision: 1.0.1 $
$Author: dai $
*/
#include <stdio.h>
#include "bigd.h"
int debug = 1;
#define DBDPRINT(pre, x, post) if(debug)bdPrintDecimal((pre),(x),(post))
const int primes[] = {
2, 3, 5, 7, 11, 13, 17, 19, 23, 29,
31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
73, 79, 83, 89, 97, 101, 103, 107, 109, 113,
127, 131, 137, 139, 149, 151, 157, 163, 167, 173,
179, 181, 191, 193, 197, 199, 211, 223, 227, 229,
233, 239, 241, 251, 257, 263, 269, 271, 277, 281,
};
#define NPRIMES (sizeof(primes)/sizeof(primes[0]))
int find_factors_of_n(BIGD p, BIGD q, BIGD n, BIGD e, BIGD d)
{
BIGD k, t, g, x, y, r;
int i, isdone;
k = bdNew();
t = bdNew();
g = bdNew();
x = bdNew();
y = bdNew();
r = bdNew();
bdSetZero(p);
bdSetZero(q);
/* 1. [Initialize] Set k <-- de - 1 */
bdMultiply(k, d, e);
bdDecrement(k);
DBDPRINT("k=de-1=", k, "\n");
/* 2. [Try a random g] Choose g at random from {2, ..., N-1} */
/* (we cheat a bit here and just try the first primes in order) */
for (isdone = 0, i = 0; !isdone && i < NPRIMES; i++)
{
bdSetShort(g, primes[i]);
DBDPRINT("Trying g=", g, "\n");
/* Set t <-- k */
bdSetEqual(t, k);
/* 3. [Next t] If t is divisible by 2 ... */
while (bdIsEven(t))
{
/* Set t <-- t / 2 */
bdShiftRight(t, t, 1);
DBDPRINT("t=", t, "\n");
/* Set x = g^t mod N */
bdModExp(x, g, t, n);
DBDPRINT("x=g^t mod N=", x, "\n");
/* 4. [Finished?] If x > 1 and y = gcd(x-1, N)
then set p <-- y and q <-- N/y, output (p,q) and stop.
*/
if (bdShortCmp(x, 1) > 0)
{
bdDecrement(x);
bdGcd(y, x, n);
DBDPRINT("y=gcd(x-1,N)=", y, "\n");
if (bdShortCmp(y, 1) > 0)
{ /* We have it */
bdSetEqual(p, y);
bdDivide(q, r, n, y);
isdone = 1;
break;
}
}
} /* 4a. ... otherwise go to step 3. */
} /* 3a. ... otherwise go to step 2. */
/* Finally, to be consistent with convention, we make sure p > q */
if (isdone && bdCompare(p, q) < 0)
{
bdSetEqual(r, p);
bdSetEqual(p, q);
bdSetEqual(q, r);
}
bdFree(&k);
bdFree(&t);
bdFree(&g);
bdFree(&x);
bdFree(&y);
bdFree(&r);
return isdone;
}
void test_simple(void)
{
BIGD n, e, d, p, q;
n = bdNew();
e = bdNew();
d = bdNew();
p = bdNew();
q = bdNew();
bdSetShort(n, 25777);
bdSetShort(e, 3);
bdSetShort(d, 16971);
printf("Input:\n");
bdPrintDecimal("n=", n, "\n");
bdPrintDecimal("e=", e, "\n");
bdPrintDecimal("d=", d, "\n");
find_factors_of_n(p, q, n, e, d);
printf("Output:\n");
bdPrintDecimal("p=", p, "\n");
bdPrintDecimal("q=", q, "\n");
//clean_up:
bdFree(&n);
bdFree(&e);
bdFree(&d);
bdFree(&p);
bdFree(&q);
}
void test_508(void)
{
BIGD n, e, d, p, q;
n = bdNew();
e = bdNew();
d = bdNew();
p = bdNew();
q = bdNew();
/*
Using 508-bit RSA key from
"Some Examples of the PKCS Standards"
An RSA Laboratories Technical Note,
Burton S. Kaliski Jr., November 1, 1993
p = 33 d4 84 45 c8 59 e5 23 40 de 70 4b cd da 06 5f bb 40 58
d7 40 bd 1d 67 d2 9e 9c 14 6c 11 cf 61
q = 33 5e 84 08 86 6b 0f d3 8d c7 00 2d 3f 97 2c 67 38 9a 65
d5 d8 30 65 66 d5 c4 f2 a5 aa 52 62 8b
*/
bdConvFromHex(n, "0a66791dc6988168de7ab77419bb7fb0c001c62710270075142942e19a8d8c51d053b3e3782a1de5dc5af4ebe99468170114a1dfe67cdc9a9af55d655620bbab");
bdConvFromHex(e, "010001");
bdConvFromHex(d, "0123c5b61ba36edb1d3679904199a89ea80c09b9122e1400c09adcf7784676d01d23356a7d44d6bd8bd50e94bfc723fa87d8862b75177691c11d757692df8881");
printf("Input:\n");
bdPrintHex("n=", n, "\n");
bdPrintHex("e=", e, "\n");
bdPrintHex("d=", d, "\n");
find_factors_of_n(p, q, n, e, d);
printf("Output:\n");
bdPrintHex("p=", p, "\n");
bdPrintHex("q=", q, "\n");
//clean_up:
bdFree(&n);
bdFree(&e);
bdFree(&d);
bdFree(&p);
bdFree(&q);
}
void test_alice1024(void)
{
BIGD n, e, d, p, q;
n = bdNew();
e = bdNew();
d = bdNew();
p = bdNew();
q = bdNew();
/*
Using Alice's 1024-bit RSA key from [RFC4134]:
d5 d8 30 65 66 d5 c4 f2 a5 aa 52 62 8b
*/
bdConvFromHex(n, "0a66791dc6988168de7ab77419bb7fb0c001c62710270075142942e19a8d8c51d053b3e3782a1de5dc5af4ebe99468170114a1dfe67cdc9a9af55d655620bbab");
bdConvFromHex(e, "010001");
bdConvFromHex(d, "0123c5b61ba36edb1d3679904199a89ea80c09b9122e1400c09adcf7784676d01d23356a7d44d6bd8bd50e94bfc723fa87d8862b75177691c11d757692df8881");
printf("Input:\n");
bdPrintHex("n=", n, "\n");
bdPrintHex("e=", e, "\n");
bdPrintHex("d=", d, "\n");
find_factors_of_n(p, q, n, e, d);
printf("Output:\n");
bdPrintHex("p=", p, "\n");
bdPrintHex("q=", q, "\n");
//clean_up:
bdFree(&n);
bdFree(&e);
bdFree(&d);
bdFree(&p);
bdFree(&q);
}
void test_alice1024(void)
{
BIGD n, e, d, p, q;
n = bdNew();
e = bdNew();
d = bdNew();
p = bdNew();
q = bdNew();
/*
Using Alice's 1024-bit RSA key from [RFC4134]:
Hoffman, P., Ed., "Examples of S/MIME Messages", RFC 4134, July 2005.
*/
bdConvFromHex(n, "E08973398DD8F5F5E88776397F4EB005BB5383DE0FB7ABDC7DC775290D052E6D12DFA68626D4D26FAA5829FC97ECFA82510F3080BEB1509E4644F12CBBD832CFC6686F07D9B060ACBEEE34096A13F5F7050593DF5EBA3556D961FF197FC981E6F86CEA874070EFAC6D2C749F2DFA553AB9997702A648528C4EF357385774575F");
bdConvFromHex(e, "010001");
bdConvFromHex(d, "A403C327477634346CA686B57949014B2E8AD2C862B2C7D748096A8B91F736F275D6E8CD15906027314735644D95CD6763CEB49F56AC2F376E1CEE0EBF282DF439906F34D86E085BD5656AD841F313D72D395EFE33CBFF29E4030B3D05A28FB7F18EA27637B07957D32F2BDE8706227D04665EC91BAF8B1AC3EC9144AB7F21");
// p = F6D6E022214C5F0A70FF27FCE5B3506A9DE50FB58596C640FAA80AB49B9B0C55C2011DF937828A14C8F2930E92CDA56621B93CD206BFB45531C9DCADCA982DD1
// q = E8DEB0112509D2025101DE8AE89850F5777761A445936B085596735DF4C85B129322738B7FD3707FF5A4AABB74FD3C226ADA38912A865B6C14E8AE4C9EFA8E2F
printf("Input:\n");
bdPrintHex("n=", n, "\n");
bdPrintHex("e=", e, "\n");
bdPrintHex("d=", d, "\n");
find_factors_of_n(p, q, n, e, d);
printf("Output:\n");
bdPrintHex("p=", p, "\n");
bdPrintHex("q=", q, "\n");
//clean_up:
bdFree(&n);
bdFree(&e);
bdFree(&d);
bdFree(&p);
bdFree(&q);
}
int main(void)
{
test_simple();
test_508();
//test_alice1024();
return 0;
}
*/
bdConvFromHex(n, "E08973398DD8F5F5E88776397F4EB005BB5383DE0FB7ABDC7DC775290D052E6D12DFA68626D4D26FAA5829FC97ECFA82510F3080BEB1509E4644F12CBBD832CFC6686F07D9B060ACBEEE34096A13F5F7050593DF5EBA3556D961FF197FC981E6F86CEA874070EFAC6D2C749F2DFA553AB9997702A648528C4EF357385774575F");
bdConvFromHex(e, "010001");
bdConvFromHex(d, "A403C327477634346CA686B57949014B2E8AD2C862B2C7D748096A8B91F736F275D6E8CD15906027314735644D95CD6763CEB49F56AC2F376E1CEE0EBF282DF439906F34D86E085BD5656AD841F313D72D395EFE33CBFF29E4030B3D05A28FB7F18EA27637B07957D32F2BDE8706227D04665EC91BAF8B1AC3EC9144AB7F21");
// p = F6D6E022214C5F0A70FF27FCE5B3506A9DE50FB58596C640FAA80AB49B9B0C55C2011DF937828A14C8F2930E92CDA56621B93CD206BFB45531C9DCADCA982DD1
// q = E8DEB0112509D2025101DE8AE89850F5777761A445936B085596735DF4C85B129322738B7FD3707FF5A4AABB74FD3C226ADA38912A865B6C14E8AE4C9EFA8E2F
printf("Input:\n");
bdPrintHex("n=", n, "\n");
bdPrintHex("e=", e, "\n");
bdPrintHex("d=", d, "\n");
find_factors_of_n(p, q, n, e, d);
printf("Output:\n");
bdPrintHex("p=", p, "\n");
bdPrintHex("q=", q, "\n");
//clean_up:
bdFree(&n);
bdFree(&e);
bdFree(&d);
bdFree(&p);
bdFree(&q);
}
int main(void)
{
test_simple();
test_508();
//test_alice1024();
return 0;
}

View File

@@ -1,58 +1,58 @@
/* $Id: t_bdSimple.c $ */
/* A very simple test of some "bd" functions */
/***** BEGIN LICENSE BLOCK *****
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Copyright (c) 2001-15 David Ireland, D.I. Management Services Pty Limited
* <http://www.di-mgt.com.au/bigdigits.html>. All rights reserved.
*
***** END LICENSE BLOCK *****/
/*
* Last updated:
* $Date: 2015-10-22 10:23:00 $
* $Revision: 2.5.0 $
* $Author: dai $
*/
#include <stdio.h>
#include "bigd.h"
int main(void)
{
BIGD u, v, w;
/* Display the BigDigits version number */
printf("BigDigits version=%d\n", bdVersion());
/* Create new BIGD objects */
u = bdNew();
v = bdNew();
w = bdNew();
/* Compute 2 * 0xdeadbeefface */
bdSetShort(u, 2);
bdConvFromHex(v, "deadbeefface");
bdMultiply(w, u, v);
/* Display the result */
bdPrintHex("", u, " * ");
bdPrintHex("0x", v, " = ");
bdPrintHex("0x", w, "\n");
/* and again in decimal format */
bdPrintDecimal("", u, " * ");
bdPrintDecimal("", v, " = ");
bdPrintDecimal("", w, "\n");
/* Free all objects we made */
bdFree(&u);
bdFree(&v);
bdFree(&w);
return 0;
}
/* $Id: t_bdSimple.c $ */
/* A very simple test of some "bd" functions */
/***** BEGIN LICENSE BLOCK *****
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Copyright (c) 2001-15 David Ireland, D.I. Management Services Pty Limited
* <http://www.di-mgt.com.au/bigdigits.html>. All rights reserved.
*
***** END LICENSE BLOCK *****/
/*
* Last updated:
* $Date: 2015-10-22 10:23:00 $
* $Revision: 2.5.0 $
* $Author: dai $
*/
#include <stdio.h>
#include "bigd.h"
int main(void)
{
BIGD u, v, w;
/* Display the BigDigits version number */
printf("BigDigits version=%d\n", bdVersion());
/* Create new BIGD objects */
u = bdNew();
v = bdNew();
w = bdNew();
/* Compute 2 * 0xdeadbeefface */
bdSetShort(u, 2);
bdConvFromHex(v, "deadbeefface");
bdMultiply(w, u, v);
/* Display the result */
bdPrintHex("", u, " * ");
bdPrintHex("0x", v, " = ");
bdPrintHex("0x", w, "\n");
/* and again in decimal format */
bdPrintDecimal("", u, " * ");
bdPrintDecimal("", v, " = ");
bdPrintDecimal("", w, "\n");
/* Free all objects we made */
bdFree(&u);
bdFree(&v);
bdFree(&w);
return 0;
}

Some files were not shown because too many files have changed in this diff Show More