059 XOR decryption.sf 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. #!/usr/bin/ruby
  2. # Author: Daniel "Trizen" Șuteu
  3. # License: GPLv3
  4. # Website: https://github.com/trizen
  5. # Your task has been made easy, as the encryption key consists of three lower case characters.
  6. # Using cipher.txt (right click and 'Save Link/Target As...'), a file containing the encrypted
  7. # ASCII codes, and the knowledge that the plain text must contain common English words, decrypt
  8. # the message and find the sum of the ASCII values in the original text.
  9. # https://projecteuler.net/problem=59
  10. # Runtime: 0.369s
  11. var enc = eval('[' + %f'p059_cipher.txt'.read + ']')
  12. var p_len = 3 # password length
  13. var pass = [] # decoded password
  14. for p in (^p_len) {
  15. for c in ('a'.ord .. 'z'.ord) {
  16. var dec = []
  17. for i in (p..enc.end `by` p_len) {
  18. dec << chr(enc[i] ^ c)
  19. }
  20. # The number of non-alpha and non-space chars
  21. var count = dec.join.count(/[^a-z ]/i)
  22. # The ratio must be less than 10%
  23. if (count/dec.len < 0.1) {
  24. pass << c
  25. break
  26. }
  27. }
  28. }
  29. var dec = []
  30. for i in (^enc) {
  31. dec << enc[i]^pass[i % p_len]
  32. }
  33. say dec.sum