Advertisement
Guest User

Untitled

a guest
Dec 20th, 2014
190
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1. use core;
  2. use core::prelude::*;
  3. use collections;
  4.  
  5. pub struct ObfuscatedString {
  6. crypted: &'static [u8],
  7. key: &'static [u8]
  8. }
  9.  
  10. impl ObfuscatedString {
  11. pub fn dec_into(&self, dest: &mut [u8]) {
  12. let &ObfuscatedString { crypted, key } = self;
  13.  
  14. for (d, (c, k)) in dest.iter_mut().zip(crypted.iter().zip(key.iter())) {
  15. *d = *c ^ *k;
  16. }
  17. }
  18.  
  19. pub fn dec_vec(&self) -> collections::vec::Vec<u8> {
  20. let len = self.crypted.len();
  21.  
  22. let mut v = collections::vec::Vec::with_capacity(len);
  23. unsafe {
  24. // safe because of with_capacity
  25. v.set_len(len);
  26. }
  27. self.dec_into(v.as_mut_slice());
  28. v
  29. }
  30.  
  31. pub fn dec(&self) -> collections::string::String {
  32. // this is safe, because all constructors of ObfuscatedString
  33. // are unsafe; thus the invariant that decryption produces valid UTF-8
  34. // is maintained in safe code
  35. unsafe {
  36. collections::string::raw::from_utf8(self.dec_vec())
  37. }
  38. }
  39. }
  40.  
  41. impl core::cmp::PartialEq<str> for ObfuscatedString {
  42. fn eq(&self, other: &str) -> bool {
  43. let decrypted = self.crypted.iter().zip(self.key.iter()).map(|(&a, &b)| a ^ b);
  44.  
  45. core::iter::order::eq(decrypted, other.bytes())
  46. }
  47. }
  48.  
  49. impl core::cmp::PartialEq<ObfuscatedString> for str {
  50. fn eq(&self, other: &ObfuscatedString) -> bool {
  51. other == self
  52. }
  53. }
  54.  
  55. impl<'a> core::cmp::PartialEq<ObfuscatedString> for &'a str {
  56. fn eq(&self, other: &ObfuscatedString) -> bool {
  57. other == *self
  58. }
  59. }
  60.  
  61.  
  62. pub unsafe fn construct(crypted: &'static [u8], key: &'static [u8]) -> ObfuscatedString {
  63. ObfuscatedString {
  64. crypted: crypted,
  65. key: key
  66. }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement