<commit_before>#http://stackoverflow.com/questions/9891708/ruby-file-encryption-decryption-with-private-public-keys
#A ruby example of string interpolation with RSA encrypted secrets
require 'openssl'
require 'base64'
private_key_file="secrets/id_rsa"
#this text tag is the supersecret in ${supersecret:ciphertext}, this makes it configurable
secret_text_tag="supersecret"

def decrypt(ciphertext,private_key_file)
  private_key=OpenSSL::PKey::RSA.new(File.read(private_key_file))
  plaintext=private_key.private_decrypt(Base64.decode64(ciphertext))
  return plaintext
end

somefile=File.read('examples/myconfig.json')
secrets=somefile.scan(/\${#{Regexp.escape(secret_text_tag)}:[^}]*}/)
secrets.each do |secret|
  ciphertext=secret.gsub(/\${#{Regexp.escape(secret_text_tag)}:([^}]*)}/,'\1')
  somefile.gsub!(secret,decrypt(ciphertext,private_key_file))
end
puts somefile<commit_msg>Adding comments to interpolate example<commit_after>#http://stackoverflow.com/questions/9891708/ruby-file-encryption-decryption-with-private-public-keys
#A ruby example of string interpolation with RSA encrypted secrets

require 'openssl'
require 'base64'
#location of private key used for decryption
private_key_file="secrets/id_rsa"
#this text tag is the supersecret in ${supersecret:ciphertext}, this makes it configurable
secret_text_tag="supersecret"

#First decodes base64 ciphertext input and then decrypts; returns plain text
def decrypt(ciphertext,private_key_file)
  private_key=OpenSSL::PKey::RSA.new(File.read(private_key_file))
  plaintext=private_key.private_decrypt(Base64.decode64(ciphertext))
  return plaintext
end

#read some file which needs string interpolation on secrets
somefile=File.read('examples/myconfig.json')
#find all of the secrets
secrets=somefile.scan(/\${#{Regexp.escape(secret_text_tag)}:[^}]*}/)
#loop over each found secret
secrets.each do |secret|
  #exctract just the cipher text from the secret
  ciphertext=secret.gsub(/\${#{Regexp.escape(secret_text_tag)}:([^}]*)}/,'\1')
  #replace the secret with the plain text
  somefile.gsub!(secret,decrypt(ciphertext,private_key_file))
end
#print the file to stdout
puts somefile
{'fraction_non_alphanumeric': 0.12167832167832168, 'fraction_numerical': 0.013986013986013986, 'mean_word_length': 7.618473895582329, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6474129', 'n_tokens_mistral': 740, 'n_tokens_neox': 689, 'n_words': 152}