image.domain\encryption\image_encryption.mbt

86.2% · 131 / 152 points · 536 lines

Background color reports the state of each line. Underlined characters mark exact instrumented byte offsets; hover them to inspect the visit count.

  1. 1///|
  2. 2/// # 图像加密 encryption/image_encryption
  3. 3///
  4. 4/// 图像处理库子模块
  5. 5/// 图像处理库子模块 Image processing library submodule
  6. 6// 图像加密(v12.14.0)
  7. 7// 基于混沌的图像加密、Logistic 映射、加密质量评估
  8. 8
  9. 9///|
  10. 10/// 加密配置
  11. 11pub(all) struct EncryptionConfig {
  12. 12 method_type : String // "logistic" / "xor"
  13. 13 key : Double // 混沌系统初始值
  14. 14 mu : Double // Logistic 映射参数(通常 3.5699456 < mu <= 4)
  15. 15 iterations : Int32 // 混沌迭代次数
  16. 16}
  17. 17
  18. 18///|
  19. 19/// 创建默认加密配置
  20. 20pub fn encryption_default_config() -> EncryptionConfig {
  21. 21● EncryptionConfig::{
  22. 22 method_type: "logistic",
  23. 23 key: 0.123456789,
  24. 24 mu: 3.99,
  25. 25 iterations: 1000,
  26. 26 }
  27. 27}
  28. 28
  29. 29///|
  30. 30/// 简单的伪随机数生成器(线性同余)
  31. 31fn lcg_next(seed : Int32) -> (Int32, Int32) {
  32. 32● let a = 1103515245
  33. 33 let c = 12345
  34. 34 let m = 1073741824
  35. 35● let next = ((a * seed + c) % m).abs()
  36. 36 (next, next)
  37. 37}
  38. 38
  39. 39///|
  40. 40/// Logistic 混沌映射:x(n+1) = mu * x(n) * (1 - x(n))
  41. 41fn logistic_map(x : Double, mu : Double) -> Double {
  42. 42● mu * x * (1.0 - x)
  43. 43}
  44. 44
  45. 45///|
  46. 46/// 生成混沌序列
  47. 47fn generate_chaotic_sequence(
  48. 48 length : Int32,
  49. 49 key : Double,
  50. 50 mu : Double,
  51. 51 warmup~ : Int32 = 100,
  52. 52) -> Array[Double] {
  53. 53● let warm = warmup
  54. 54 let sequence : Array[Double] = []
  55. 55 let mut x = key
  56. 56 // 预热(丢弃前 warm 个值)
  57. 57 for _ in 0..<warm {
  58. 58● x = logistic_map(x, mu)
  59. 59 }
  60. 60 // 生成序列
  61. 61 for _ in 0..<length {
  62. 62● x = logistic_map(x, mu)
  63. 63● sequence.push(x)
  64. 64 }
  65. 65 sequence
  66. 66}
  67. 67
  68. 68///|
  69. 69/// 基于 Logistic 混沌映射的图像加密
  70. 70pub fn encrypt_image_logistic(
  71. 71 img : @types.Image,
  72. 72 key~ : Double = 0.123456789,
  73. 73 mu~ : Double = 3.99,
  74. 74) -> @types.Image raise @types.LoadError {
  75. 75 // 输入验证
  76. 76● if img.width <= 0 || img.height <= 0 {
  77. 77● raise @types.LoadError::DecodeFailed(
  78. 78 "encrypt_image_logistic: 图像尺寸必须大于0",
  79. 79 )
  80. 80 }
  81. 81 if img.channels < 1 || img.channels > 4 {
  82. 82● raise @types.LoadError::DecodeFailed(
  83. 83 "encrypt_image_logistic: 通道数必须在1-4之间",
  84. 84 )
  85. 85 }
  86. 86 let expected_size = img.width * img.height * img.channels
  87. 87● if img.data.length() != expected_size {
  88. 88● raise @types.LoadError::DecodeFailed(
  89. 89 "encrypt_image_logistic: 数据大小不匹配",
  90. 90 )
  91. 91 }
  92. 92 let k = key
  93. 93 let m = mu
  94. 94 let w = img.width
  95. 95 let h = img.height
  96. 96 let channels = img.channels
  97. 97 let total_pixels = w * h * channels
  98. 98 // 生成混沌序列
  99. 99● let chaotic = generate_chaotic_sequence(total_pixels, k, m, warmup=100)
  100. 100 // XOR 加密
  101. 101● let out_data : Array[Byte] = Array::make(total_pixels, b'\x00')
  102. 102 for i in 0..<total_pixels {
  103. 103 // 将混沌值映射到 0-255
  104. 104● let chaotic_byte = (chaotic[i] * 256.0).to_int().min(255).max(0)
  105. 105● let original = img.data[i].to_int()
  106. 106 let encrypted = original ^ chaotic_byte
  107. 107● out_data[i] = encrypted.to_byte()
  108. 108 }
  109. 109 @types.Image::{
  110. 110 width: w,
  111. 111 height: h,
  112. 112 channels,
  113. 113● data: Bytes::from_array(out_data),
  114. 114 }
  115. 115}
  116. 116
  117. 117///|
  118. 118/// 基于 Logistic 混沌映射的图像解密(与加密相同,因为 XOR 是对称的)
  119. 119pub fn decrypt_image_logistic(
  120. 120 img : @types.Image,
  121. 121 key~ : Double = 0.123456789,
  122. 122 mu~ : Double = 3.99,
  123. 123) -> @types.Image raise @types.LoadError {
  124. 124 // 输入验证
  125. 125● if img.width <= 0 || img.height <= 0 {
  126. 126● raise @types.LoadError::DecodeFailed(
  127. 127 "decrypt_image_logistic: 图像尺寸必须大于0",
  128. 128 )
  129. 129 }
  130. 130 if img.channels < 1 || img.channels > 4 {
  131. 131○ raise @types.LoadError::DecodeFailed(
  132. 132 "decrypt_image_logistic: 通道数必须在1-4之间",
  133. 133 )
  134. 134 }
  135. 135 let expected_size = img.width * img.height * img.channels
  136. 136● if img.data.length() != expected_size {
  137. 137○ raise @types.LoadError::DecodeFailed(
  138. 138 "decrypt_image_logistic: 数据大小不匹配",
  139. 139 )
  140. 140 }
  141. 141 // XOR 加密是对称的,解密与加密使用相同的操作
  142. 142● encrypt_image_logistic(img, key~, mu~)
  143. 143}
  144. 144
  145. 145///|
  146. 146/// 简单的 XOR 加密(使用密钥字节序列)
  147. 147pub fn encrypt_image_xor(
  148. 148 img : @types.Image,
  149. 149 key : String,
  150. 150) -> @types.Image raise @types.LoadError {
  151. 151 // 输入验证
  152. 152● if img.width <= 0 || img.height <= 0 {
  153. 153● raise @types.LoadError::DecodeFailed(
  154. 154 "encrypt_image_xor: 图像尺寸必须大于0",
  155. 155 )
  156. 156 }
  157. 157 if img.channels < 1 || img.channels > 4 {
  158. 158○ raise @types.LoadError::DecodeFailed(
  159. 159 "encrypt_image_xor: 通道数必须在1-4之间",
  160. 160 )
  161. 161 }
  162. 162 let expected_size = img.width * img.height * img.channels
  163. 163● if img.data.length() != expected_size {
  164. 164○ raise @types.LoadError::DecodeFailed(
  165. 165 "encrypt_image_xor: 数据大小不匹配",
  166. 166 )
  167. 167 }
  168. 168● if key.length() == 0 {
  169. 169● raise @types.LoadError::DecodeFailed(
  170. 170 "encrypt_image_xor: 密钥不能为空",
  171. 171 )
  172. 172 }
  173. 173 let w = img.width
  174. 174 let h = img.height
  175. 175 let channels = img.channels
  176. 176 let total_pixels = w * h * channels
  177. 177● let key_bytes = @encoding/utf8.encode(key)
  178. 178● let key_len = key_bytes.length()
  179. 179● let out_data : Array[Byte] = Array::make(total_pixels, b'\x00')
  180. 180 for i in 0..<total_pixels {
  181. 181● let key_byte = key_bytes[i % key_len].to_int()
  182. 182● let original = img.data[i].to_int()
  183. 183 let encrypted = original ^ key_byte
  184. 184● out_data[i] = encrypted.to_byte()
  185. 185 }
  186. 186 @types.Image::{
  187. 187 width: w,
  188. 188 height: h,
  189. 189 channels,
  190. 190● data: Bytes::from_array(out_data),
  191. 191 }
  192. 192}
  193. 193
  194. 194///|
  195. 195/// 简单的 XOR 解密
  196. 196pub fn decrypt_image_xor(
  197. 197 img : @types.Image,
  198. 198 key : String,
  199. 199) -> @types.Image raise @types.LoadError {
  200. 200 // 输入验证
  201. 201● if img.width <= 0 || img.height <= 0 {
  202. 202● raise @types.LoadError::DecodeFailed(
  203. 203 "decrypt_image_xor: 图像尺寸必须大于0",
  204. 204 )
  205. 205 }
  206. 206 if img.channels < 1 || img.channels > 4 {
  207. 207○ raise @types.LoadError::DecodeFailed(
  208. 208 "decrypt_image_xor: 通道数必须在1-4之间",
  209. 209 )
  210. 210 }
  211. 211 let expected_size = img.width * img.height * img.channels
  212. 212● if img.data.length() != expected_size {
  213. 213○ raise @types.LoadError::DecodeFailed(
  214. 214 "decrypt_image_xor: 数据大小不匹配",
  215. 215 )
  216. 216 }
  217. 217● if key.length() == 0 {
  218. 218○ raise @types.LoadError::DecodeFailed(
  219. 219 "decrypt_image_xor: 密钥不能为空",
  220. 220 )
  221. 221 }
  222. 222● encrypt_image_xor(img, key)
  223. 223}
  224. 224
  225. 225///|
  226. 226/// 计算图像直方图
  227. 227fn compute_histogram(img : @types.Image) -> Array[Int32] {
  228. 228● let histogram : Array[Int32] = []
  229. 229 for _ in 0..<256 {
  230. 230● histogram.push(0)
  231. 231 }
  232. 232 let w = img.width
  233. 233 let h = img.height
  234. 234 let channels = img.channels
  235. 235 for y in 0..<h {
  236. 236● for x in 0..<w {
  237. 237● let idx = (y * w + x) * channels
  238. 238 for c in 0..<channels {
  239. 239● let val = img.data[idx + c].to_int()
  240. 240 histogram[val] += 1
  241. 241 }
  242. 242 }
  243. 243 }
  244. 244 histogram
  245. 245}
  246. 246
  247. 247///|
  248. 248/// 计算直方图熵(衡量加密质量,熵越高越好)
  249. 249pub fn histogram_entropy(img : @types.Image) -> Double raise @types.LoadError {
  250. 250 // 输入验证
  251. 251● if img.width <= 0 || img.height <= 0 {
  252. 252● raise @types.LoadError::DecodeFailed(
  253. 253 "histogram_entropy: 图像尺寸必须大于0",
  254. 254 )
  255. 255 }
  256. 256 if img.channels < 1 || img.channels > 4 {
  257. 257○ raise @types.LoadError::DecodeFailed(
  258. 258 "histogram_entropy: 通道数必须在1-4之间",
  259. 259 )
  260. 260 }
  261. 261 let expected_size = img.width * img.height * img.channels
  262. 262● if img.data.length() != expected_size {
  263. 263● raise @types.LoadError::DecodeFailed(
  264. 264 "histogram_entropy: 数据大小不匹配",
  265. 265 )
  266. 266 }
  267. 267● let histogram = compute_histogram(img)
  268. 268 let w = img.width
  269. 269 let h = img.height
  270. 270 let channels = img.channels
  271. 271● let total = (w * h * channels).to_double()
  272. 272 let mut entropy = 0.0
  273. 273 for count in histogram {
  274. 274● if count > 0 {
  275. 275● let p = count.to_double() / total
  276. 276● entropy -= p * @math.log2(p)
  277. 277 }
  278. 278 }
  279. 279 entropy
  280. 280}
  281. 281
  282. 282///|
  283. 283/// 计算相邻像素相关性(加密后应接近 0)
  284. 284pub fn adjacent_correlation(
  285. 285 img : @types.Image,
  286. 286 direction~ : String = "horizontal",
  287. 287) -> Double raise @types.LoadError {
  288. 288 // 输入验证
  289. 289● if img.width <= 0 || img.height <= 0 {
  290. 290● raise @types.LoadError::DecodeFailed(
  291. 291 "adjacent_correlation: 图像尺寸必须大于0",
  292. 292 )
  293. 293 }
  294. 294 if img.channels < 1 || img.channels > 4 {
  295. 295○ raise @types.LoadError::DecodeFailed(
  296. 296 "adjacent_correlation: 通道数必须在1-4之间",
  297. 297 )
  298. 298 }
  299. 299 let expected_size = img.width * img.height * img.channels
  300. 300● if img.data.length() != expected_size {
  301. 301● raise @types.LoadError::DecodeFailed(
  302. 302 "adjacent_correlation: 数据大小不匹配",
  303. 303 )
  304. 304 }
  305. 305 let dir = direction
  306. 306 let w = img.width
  307. 307 let h = img.height
  308. 308 let channels = img.channels
  309. 309 // 采样点数量
  310. 310◐ let sample_count = if 1000 < w * h { 1000 } else { w * h }
  311. 311 let mut sum_x = 0.0
  312. 312 let mut sum_y = 0.0
  313. 313 let mut sum_xy = 0.0
  314. 314 let mut sum_x2 = 0.0
  315. 315 let mut sum_y2 = 0.0
  316. 316 let mut count = 0
  317. 317 let mut seed = 12345
  318. 318 for _ in 0..<sample_count {
  319. 319 // 随机选择像素位置
  320. 320● let (next, value) = lcg_next(seed)
  321. 321 seed = next
  322. 322 let x = value % w
  323. 323● let (next2, value2) = lcg_next(seed)
  324. 324 seed = next2
  325. 325 let y = value2 % h
  326. 326 let idx = (y * w + x) * channels
  327. 327● let pixel1 = img.data[idx].to_double()
  328. 328 // 相邻像素
  329. 329● let pixel2 = match dir {
  330. 330 "horizontal" =>
  331. 331● if x + 1 < w {
  332. 332● img.data[(y * w + x + 1) * channels].to_double()
  333. 333 } else {
  334. 334○ img.data[idx].to_double()
  335. 335 }
  336. 336 "vertical" =>
  337. 337● if y + 1 < h {
  338. 338● img.data[((y + 1) * w + x) * channels].to_double()
  339. 339 } else {
  340. 340● img.data[idx].to_double()
  341. 341 }
  342. 342 "diagonal" =>
  343. 343● if x + 1 < w && y + 1 < h {
  344. 344● img.data[((y + 1) * w + x + 1) * channels].to_double()
  345. 345 } else {
  346. 346● img.data[idx].to_double()
  347. 347 }
  348. 348● _ => img.data[idx].to_double()
  349. 349 }
  350. 350 sum_x += pixel1
  351. 351 sum_y += pixel2
  352. 352 sum_xy += pixel1 * pixel2
  353. 353 sum_x2 += pixel1 * pixel1
  354. 354 sum_y2 += pixel2 * pixel2
  355. 355 count += 1
  356. 356 }
  357. 357 if count == 0 {
  358. 358○ return 0.0
  359. 359 }
  360. 360● let n = count.to_double()
  361. 361 let mean_x = sum_x / n
  362. 362 let mean_y = sum_y / n
  363. 363 let cov_xy = sum_xy / n - mean_x * mean_y
  364. 364 let var_x = sum_x2 / n - mean_x * mean_x
  365. 365 let var_y = sum_y2 / n - mean_y * mean_y
  366. 366● let denom = (var_x * var_y).sqrt()
  367. 367 if denom < 0.000001 {
  368. 368● return 0.0
  369. 369 }
  370. 370 cov_xy / denom
  371. 371}
  372. 372
  373. 373///|
  374. 374/// 加密质量评估
  375. 375pub(all) struct EncryptionQuality {
  376. 376 entropy : Double // 直方图熵(理想值 8)
  377. 377 correlation_h : Double // 水平相关性(理想值 0)
  378. 378 correlation_v : Double // 垂直相关性(理想值 0)
  379. 379 correlation_d : Double // 对角相关性(理想值 0)
  380. 380 npcr : Double // 像素变化率(Number of Pixel Change Rate)
  381. 381 uaci : Double // 统一平均变化强度(Unified Average Changing Intensity)
  382. 382}
  383. 383
  384. 384///|
  385. 385/// 计算 NPCR(像素变化率)
  386. 386fn compute_npcr(img1 : @types.Image, img2 : @types.Image) -> Double {
  387. 387● if img1.width != img2.width || img1.height != img2.height {
  388. 388○ return 0.0
  389. 389 }
  390. 390 let w = img1.width
  391. 391 let h = img1.height
  392. 392● let channels = img1.channels.min(img2.channels)
  393. 393 let total = w * h * channels
  394. 394 let mut changed = 0
  395. 395 for i in 0..<total {
  396. 396● if img1.data[i] != img2.data[i] {
  397. 397● changed += 1
  398. 398 }
  399. 399 }
  400. 400● changed.to_double() / total.to_double() * 100.0
  401. 401}
  402. 402
  403. 403///|
  404. 404/// 计算 UACI(统一平均变化强度)
  405. 405fn compute_uaci(img1 : @types.Image, img2 : @types.Image) -> Double {
  406. 406● if img1.width != img2.width || img1.height != img2.height {
  407. 407○ return 0.0
  408. 408 }
  409. 409 let w = img1.width
  410. 410 let h = img1.height
  411. 411● let channels = img1.channels.min(img2.channels)
  412. 412 let total = w * h * channels
  413. 413 let mut sum = 0.0
  414. 414 for i in 0..<total {
  415. 415● let diff = (img1.data[i].to_int() - img2.data[i].to_int()).abs().to_double()
  416. 416 sum += diff / 255.0
  417. 417 }
  418. 418● sum / total.to_double() * 100.0
  419. 419}
  420. 420
  421. 421///|
  422. 422/// 评估加密质量
  423. 423pub fn evaluate_encryption_quality(
  424. 424 original : @types.Image,
  425. 425 encrypted : @types.Image,
  426. 426) -> EncryptionQuality raise @types.LoadError {
  427. 427 // 输入验证
  428. 428● if original.width <= 0 || original.height <= 0 {
  429. 429● raise @types.LoadError::DecodeFailed(
  430. 430 "evaluate_encryption_quality: 图像尺寸必须大于0",
  431. 431 )
  432. 432 }
  433. 433 if original.channels < 1 || original.channels > 4 {
  434. 434○ raise @types.LoadError::DecodeFailed(
  435. 435 "evaluate_encryption_quality: 通道数必须在1-4之间",
  436. 436 )
  437. 437 }
  438. 438 let expected_size = original.width * original.height * original.channels
  439. 439● if original.data.length() != expected_size {
  440. 440● raise @types.LoadError::DecodeFailed(
  441. 441 "evaluate_encryption_quality: 数据大小不匹配",
  442. 442 )
  443. 443 }
  444. 444 if encrypted.width <= 0 || encrypted.height <= 0 {
  445. 445○ raise @types.LoadError::DecodeFailed(
  446. 446 "evaluate_encryption_quality: 图像尺寸必须大于0",
  447. 447 )
  448. 448 }
  449. 449 if encrypted.channels < 1 || encrypted.channels > 4 {
  450. 450○ raise @types.LoadError::DecodeFailed(
  451. 451 "evaluate_encryption_quality: 通道数必须在1-4之间",
  452. 452 )
  453. 453 }
  454. 454 let expected_size2 = encrypted.width * encrypted.height * encrypted.channels
  455. 455● if encrypted.data.length() != expected_size2 {
  456. 456● raise @types.LoadError::DecodeFailed(
  457. 457 "evaluate_encryption_quality: 数据大小不匹配",
  458. 458 )
  459. 459 }
  460. 460● let entropy = histogram_entropy(encrypted)
  461. 461● let corr_h = adjacent_correlation(encrypted, direction="horizontal")
  462. 462● let corr_v = adjacent_correlation(encrypted, direction="vertical")
  463. 463● let corr_d = adjacent_correlation(encrypted, direction="diagonal")
  464. 464● let npcr = compute_npcr(original, encrypted)
  465. 465● let uaci = compute_uaci(original, encrypted)
  466. 466 EncryptionQuality::{
  467. 467 entropy,
  468. 468 correlation_h: corr_h,
  469. 469 correlation_v: corr_v,
  470. 470 correlation_d: corr_d,
  471. 471 npcr,
  472. 472 uaci,
  473. 473 }
  474. 474}
  475. 475
  476. 476///|
  477. 477/// 密钥敏感性测试(微小密钥变化导致完全不同的密文)
  478. 478pub fn key_sensitivity_test(
  479. 479 img : @types.Image,
  480. 480 key : Double,
  481. 481 delta~ : Double = 0.0000001,
  482. 482) -> Double raise @types.LoadError {
  483. 483 // 输入验证
  484. 484● if img.width <= 0 || img.height <= 0 {
  485. 485● raise @types.LoadError::DecodeFailed(
  486. 486 "key_sensitivity_test: 图像尺寸必须大于0",
  487. 487 )
  488. 488 }
  489. 489 if img.channels < 1 || img.channels > 4 {
  490. 490○ raise @types.LoadError::DecodeFailed(
  491. 491 "key_sensitivity_test: 通道数必须在1-4之间",
  492. 492 )
  493. 493 }
  494. 494 let expected_size = img.width * img.height * img.channels
  495. 495● if img.data.length() != expected_size {
  496. 496● raise @types.LoadError::DecodeFailed(
  497. 497 "key_sensitivity_test: 数据大小不匹配",
  498. 498 )
  499. 499 }
  500. 500 let d = delta
  501. 501● let encrypted1 = encrypt_image_logistic(img, key~, mu=3.99)
  502. 502● let encrypted2 = encrypt_image_logistic(img, key=key + d, mu=3.99)
  503. 503● compute_npcr(encrypted1, encrypted2)
  504. 504}
  505. 505
  506. 506///|
  507. 507/// 批量加密
  508. 508pub fn batch_encrypt(
  509. 509 images : Array[@types.Image],
  510. 510 key : Double,
  511. 511) -> Array[@types.Image] raise @types.LoadError {
  512. 512 // 输入验证
  513. 513● for img in images {
  514. 514● if img.width <= 0 || img.height <= 0 {
  515. 515○ raise @types.LoadError::DecodeFailed(
  516. 516 "batch_encrypt: 图像尺寸必须大于0",
  517. 517 )
  518. 518 }
  519. 519 if img.channels < 1 || img.channels > 4 {
  520. 520○ raise @types.LoadError::DecodeFailed(
  521. 521 "batch_encrypt: 通道数必须在1-4之间",
  522. 522 )
  523. 523 }
  524. 524 let expected_size = img.width * img.height * img.channels
  525. 525● if img.data.length() != expected_size {
  526. 526● raise @types.LoadError::DecodeFailed(
  527. 527 "batch_encrypt: 数据大小不匹配",
  528. 528 )
  529. 529 }
  530. 530 }
  531. 531 let result : Array[@types.Image] = []
  532. 532 for img in images {
  533. 533● result.push(encrypt_image_logistic(img, key~, mu=3.99))
  534. 534 }
  535. 535 result
  536. 536}