crypto.rs 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  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, MAXIMUM_LENGTH_OF_NICK_CHAN_CNT},
  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: &[u8]) -> String {
  62. let nonce = SalsaBox::generate_nonce(&mut OsRng);
  63. let mut ciphertext = salt_box.encrypt(&nonce, plaintext).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. pub fn decrypt_target(
  70. contact: &mut String,
  71. privmsg: &mut PrivMsgEvent,
  72. configured_chans: HashMap<String, ChannelInfo>,
  73. configured_contacts: HashMap<String, ContactInfo>,
  74. ) {
  75. for chan_name in configured_chans.keys() {
  76. let chan_info = configured_chans.get(chan_name).unwrap();
  77. if !chan_info.joined {
  78. continue
  79. }
  80. let salt_box = chan_info.salt_box.clone();
  81. if let Some(salt_box) = salt_box {
  82. let decrypted_target = try_decrypt(&salt_box, &privmsg.target);
  83. if decrypted_target.is_none() {
  84. continue
  85. }
  86. let target =
  87. String::from_utf8_lossy(&unpad(decrypted_target.unwrap().into())).to_string();
  88. if *chan_name == target {
  89. privmsg.target = target;
  90. return
  91. }
  92. }
  93. }
  94. for cnt_name in configured_contacts.keys() {
  95. let cnt_info = configured_contacts.get(cnt_name).unwrap();
  96. let salt_box = cnt_info.salt_box.clone();
  97. if let Some(salt_box) = salt_box {
  98. let decrypted_target = try_decrypt(&salt_box, &privmsg.target);
  99. if decrypted_target.is_none() {
  100. continue
  101. }
  102. let target =
  103. String::from_utf8_lossy(&unpad(decrypted_target.unwrap().into())).to_string();
  104. privmsg.target = target;
  105. *contact = cnt_name.into();
  106. return
  107. }
  108. }
  109. }
  110. /// Decrypt PrivMsg nickname and message
  111. pub fn decrypt_privmsg(salt_box: &SalsaBox, privmsg: &mut PrivMsgEvent) {
  112. let decrypted_nick = try_decrypt(salt_box, &privmsg.nick);
  113. let decrypted_msg = try_decrypt(salt_box, &privmsg.msg);
  114. if decrypted_nick.is_none() && decrypted_msg.is_none() {
  115. return
  116. }
  117. privmsg.nick = String::from_utf8_lossy(&unpad(decrypted_nick.unwrap().into())).to_string();
  118. privmsg.msg = decrypted_msg.unwrap();
  119. }
  120. /// Encrypt PrivMsg
  121. pub fn encrypt_privmsg(salt_box: &SalsaBox, privmsg: &mut PrivMsgEvent) {
  122. privmsg.nick = encrypt(salt_box, &pad(privmsg.nick.clone().into()));
  123. privmsg.target = encrypt(salt_box, &pad(privmsg.target.clone().into()));
  124. privmsg.msg = encrypt(salt_box, privmsg.msg.as_bytes());
  125. }
  126. fn pad(data: Vec<u8>) -> Vec<u8> {
  127. if data.len() == MAXIMUM_LENGTH_OF_NICK_CHAN_CNT {
  128. return data
  129. }
  130. assert!(data.len() < MAXIMUM_LENGTH_OF_NICK_CHAN_CNT);
  131. let padding = vec![0u8; MAXIMUM_LENGTH_OF_NICK_CHAN_CNT - data.len()];
  132. let mut data = data;
  133. data.extend_from_slice(&padding);
  134. data
  135. }
  136. fn unpad(data: Vec<u8>) -> Vec<u8> {
  137. assert!(data.len() == MAXIMUM_LENGTH_OF_NICK_CHAN_CNT);
  138. match data.iter().position(|&x| x == 0u8) {
  139. Some(idx) => data[..idx].to_vec(),
  140. None => data,
  141. }
  142. }
  143. #[cfg(test)]
  144. mod tests {
  145. use super::*;
  146. #[test]
  147. fn test_pad_unpad() {
  148. let nick = String::from("terry-davis");
  149. let padded = pad(nick.clone().into());
  150. assert!(padded.len() == 32);
  151. assert_eq!(nick, String::from_utf8_lossy(&unpad(padded)));
  152. let nick = String::from("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
  153. let padded = pad(nick.clone().into());
  154. assert_eq!(nick, String::from_utf8_lossy(&padded));
  155. assert_eq!(nick, String::from_utf8_lossy(&unpad(padded)));
  156. }
  157. }