crypto.rs 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use std::{collections::HashMap, fmt};
  19. use crypto_box::{
  20. aead::{Aead, AeadCore},
  21. SalsaBox,
  22. };
  23. use rand::rngs::OsRng;
  24. use crate::{
  25. privmsg::PrivMsgEvent,
  26. settings::{ChannelInfo, ContactInfo},
  27. };
  28. #[derive(serde::Serialize)]
  29. pub struct KeyPair {
  30. pub private_key: String,
  31. pub public_key: String,
  32. }
  33. impl fmt::Display for KeyPair {
  34. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  35. write!(f, "Public key: {}\nPrivate key: {}", self.public_key, self.private_key)
  36. }
  37. }
  38. /// The format we're using is nonce+ciphertext, where nonce is 24 bytes.
  39. fn try_decrypt(salt_box: &SalsaBox, ciphertext: &str) -> Option<String> {
  40. let bytes = match bs58::decode(ciphertext).into_vec() {
  41. Ok(v) => v,
  42. Err(_) => return None,
  43. };
  44. if bytes.len() < 25 {
  45. return None
  46. }
  47. // Try extracting the nonce
  48. let nonce = match bytes[0..24].try_into() {
  49. Ok(v) => v,
  50. Err(_) => return None,
  51. };
  52. // Take the remaining ciphertext
  53. let message = &bytes[24..];
  54. // Try decrypting the message
  55. match salt_box.decrypt(nonce, message) {
  56. Ok(v) => Some(String::from_utf8_lossy(&v).to_string()),
  57. Err(_) => None,
  58. }
  59. }
  60. /// The format we're using is nonce+ciphertext, where nonce is 24 bytes.
  61. pub fn encrypt(salt_box: &SalsaBox, plaintext: &str) -> String {
  62. let nonce = SalsaBox::generate_nonce(&mut OsRng);
  63. let mut ciphertext = salt_box.encrypt(&nonce, plaintext.as_bytes()).unwrap();
  64. let mut concat = vec![];
  65. concat.append(&mut nonce.as_slice().to_vec());
  66. concat.append(&mut ciphertext);
  67. bs58::encode(concat).into_string()
  68. }
  69. /// Decrypt PrivMsg target
  70. pub fn decrypt_target(
  71. privmsg: &mut PrivMsgEvent,
  72. configured_chans: &HashMap<String, ChannelInfo>,
  73. configured_contacts: &HashMap<String, ContactInfo>,
  74. private_key: &Option<String>,
  75. ) {
  76. for (name, chan_info) in configured_chans {
  77. if !chan_info.joined {
  78. continue
  79. }
  80. let salt_box = chan_info.salt_box(name).clone();
  81. if let Some(salt_box) = salt_box {
  82. if try_decrypt(&salt_box, &privmsg.target).is_some() {
  83. privmsg.target = name.clone();
  84. return
  85. }
  86. }
  87. }
  88. if private_key.is_none() {
  89. return
  90. }
  91. for (name, contact_info) in configured_contacts {
  92. let salt_box = contact_info.salt_box(private_key.as_ref().unwrap(), name).clone();
  93. if let Some(salt_box) = salt_box {
  94. if try_decrypt(&salt_box, &privmsg.target).is_some() {
  95. privmsg.target = name.clone();
  96. return
  97. }
  98. }
  99. }
  100. }
  101. /// Decrypt PrivMsg nickname and message
  102. pub fn decrypt_privmsg(salt_box: &SalsaBox, privmsg: &mut PrivMsgEvent) {
  103. let decrypted_nick = try_decrypt(salt_box, &privmsg.nick);
  104. let decrypted_msg = try_decrypt(salt_box, &privmsg.msg);
  105. if decrypted_nick.is_none() && decrypted_msg.is_none() {
  106. return
  107. }
  108. privmsg.nick = decrypted_nick.unwrap();
  109. privmsg.msg = decrypted_msg.unwrap();
  110. }
  111. /// Encrypt PrivMsg
  112. pub fn encrypt_privmsg(salt_box: &SalsaBox, privmsg: &mut PrivMsgEvent) {
  113. privmsg.nick = encrypt(salt_box, &privmsg.nick);
  114. privmsg.target = encrypt(salt_box, &privmsg.target);
  115. privmsg.msg = encrypt(salt_box, &privmsg.msg);
  116. }