lib.rs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. use base64::{Engine as _, engine::general_purpose};
  2. use std::error::Error;
  3. fn xor_bytes(buffer: &mut Vec<u8>, xor: u8) {
  4. for b in buffer {
  5. *b = *b ^ xor
  6. }
  7. }
  8. // See: https://stackoverflow.com/questions/41034635/how-do-i-convert-between-string-str-vecu8-and-u8
  9. // for conversion examples (to/from str/String/Vec<u8>).
  10. pub fn encode(text: &str, xor: u8) -> String {
  11. let mut temp = text.as_bytes().to_owned();
  12. xor_bytes(temp.as_mut(), xor);
  13. general_purpose::STANDARD.encode(temp)
  14. }
  15. pub fn decode(text: &str, xor: u8) -> Result<String, Box<dyn Error>> {
  16. let mut chars = general_purpose::STANDARD.decode(text)?;
  17. xor_bytes(chars.as_mut(), xor);
  18. Ok(String::from_utf8(chars)?)
  19. }
  20. #[cfg(test)]
  21. mod tests {
  22. use super::*;
  23. #[test]
  24. fn encode_test() {
  25. let t1 = "hello world";
  26. let t2 = encode(t1, 'U' as u8);
  27. assert_eq!(t2, "PTA5OTp1IjonOTE=");
  28. }
  29. #[test]
  30. fn encode_utf8_test() {
  31. let t1 = "🍺";
  32. let t2 = encode(&t1, 'U' as u8);
  33. assert_eq!(t2, "pcrY7w==");
  34. }
  35. #[test]
  36. fn decode_test() {
  37. let t1= "ICYiPCE2PW9vMTA2OjEw";
  38. let t2 = decode(&t1, 'U' as u8);
  39. match t2 {
  40. Ok(s) => assert_eq!(s, "uswitch::decode"),
  41. Err(err) => panic!("{}", err),
  42. }
  43. }
  44. #[test]
  45. fn decode_utf8_test() {
  46. let t1 = "t9f5";
  47. let t2 = decode(&t1, 'U' as u8);
  48. match t2 {
  49. Ok(s) => assert_eq!(s, "€"),
  50. Err(err) => panic!("{}", err),
  51. }
  52. }
  53. #[test]
  54. fn decode_fail_test() {
  55. let t1 = "yAyL3WlysPBdTEnPDs+JnWlytjv"; // Invalid base64
  56. let t2 = decode(&t1, 'U' as u8);
  57. match t2 {
  58. Ok(s) => panic!("Expected failure! Got '{}'", s),
  59. Err(_) => ()
  60. }
  61. }
  62. #[test]
  63. fn decode_fail_utf8_test() {
  64. let t1 = "woXChQ=="; // Invalid UTF-8
  65. let t2 = decode(&t1, 'U' as u8);
  66. match t2 {
  67. Ok(s) => panic!("Expected failure! Got '{}'", s),
  68. Err(_) => ()
  69. }
  70. }
  71. }