Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

secure_string

Package Overview
Dependencies
Maintainers
1
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

secure_string

  • 1.3.3
  • Rubygems
  • Socket score

Version published
Maintainers
1
Created
Source

= Overview

SecureString is a special string subclass that provides two pieces of functionality that can be used individually:

  • Byte string support: Although a string can already contain bytes, this makes it easier to view and work with strings holding binary data, including conversion to/from raw hex or Base64 encoded values.
  • Secure string support: Easy methods for RSA encryption, AES encoding, and SHA/MD5 digest hashing, of the data in the strings.

One of the basic philosophies of SecureString is that it does not override--only extends--the feature set of String. However there is one difference that was added: +inspect+ is overridden to return the data as a hex-string, rather than using the specified character encoding. This does not mean it's value has in any way changed, just its presentation. Use +to_s+ to recover the standard String version of the value.

WARNING: it is important to note that the String method +length+ is not a good measure of a byte string's length, as depending on the encoding, it may count multibyte characters as a single element. To ensure that you get the byte length, use the standard string method +bytesize+. See the section on String Encodings for more detail.

= Installation & Configuration

== Installation

SecureString was tested and works successfully in ruby 1.8.7 and 1.9.2.

To install, first install the gem:

gem install secure_string

Then require the gem like so:

require 'secure_string'

By default, this creates the SecureString class, which is completely configured and ready to go like so:

SecureString.new("foo")

== Optional Configuration

Some people like to monkey patch String to translate to a SecureString like so:

This is an optional configuration:

class String def to_ss return SecureString.new(self) end end

Alternatively, if you would like to add the SecureString methods directly onto all Strings, simply add the following code to your program:

This is an optional configuration:

class String include SecurizeString end

Unless you already have code that modifies String in a conflicting way--or code that depends on the value of +inspect+, this should not change the behavior of your existing code.

= Examples

== Basic Usage

Creation of a SecureString from an normal String instance is easy:

ss = SecureString.new("Hello World!") ss.to_s --> "Hello World!" ss.inspect --> "<48656c6c6f20576f726c6421>"

Additionally, you can get at the byte data in various ways:

ss.to_hex --> "48656c6c6f20576f726c6421" ss.to_i --> 22405534230753928650781647905 ss.to_base64 --> "SGVsbG8gV29ybGQh\n"

One can initialize a SecureString from any of these types like so:

ss1 = SecureString.new("Hello World!", :type => :data) ss2 = SecureString.new("48656c6c6f20576f726c6421", :type => :hex) ss3 = SecureString.new(22405534230753928650781647905, :type => :int) ss4 = SecureString.new("SGVsbG8gV29ybGQh", :type => :base64)

ss1 == ss --> true ss2 == ss --> true ss3 == ss --> true ss4 == ss --> true

All of these create equal-valued strings to "HelloWorld!".

== Base64 Methods Overview

The SecureString::Base64Methods module adds +to_base64+, which we've seen:

SecureString.new("Hello World!").to_base64 --> "SGVsbG8gV29ybGQh\n"

It also adds +from_base64+, which can decode a Base64 encoded string. The following example shows the various ways of decoding Bas64 data:

SecureString.new("SGVsbG8gV29ybGQh", :type => :base64) == "Hello World!" --> true SecureString.new("SGVsbG8gV29ybGQh") == "Hello World!" --> false SecureString.new("SGVsbG8gV29ybGQh").from_base64 == "Hello World!" --> true

== Digest Methods Overview

The SecureString::DigestMethods module adds convenience methods for calculating cryptographic hash sums for the data in the string. Note that since SecureString handles binary data well, the string value returns is NOT the hex string; to get the hex digest, simply call to_hex:

ss = SecureString.new("Hello World!") ss.to_md5.to_hex --> "ed076287532e86365e841e92bfc50d8c" ss.to_sha1.to_hex --> "2ef7bde608ce5404e97d5f042f95f89f1c232871" ss.to_sha256.to_hex --> "7f83b1657ff1fc53b92dc18148a1d65dfc2d4b1fa3d677284addd200126d9069" ss.to_digest('SHA-512').to_hex --> "861844d6704e8573fec34d967e20bcfef3d424cf48be04e6dc08f2bd58c729743371015ead891cc3cf1c9d34b49264b510751b1ff9e537937bc46b5d6ff4ecc8"

== RSA Methods Overview

The SecureString::RSAMethods module adds convenience methods for RSA key generation, encryption, and signing, and verification.

The basic features of this module are illustrated on the following worked example:

First, alice and bob much each generate their public and private keys. For the example, we do it like so:

alice_pvt_key, alice_pub_key = SecureString.rsa_keygen bob_pvt_key, bob_pub_key = SecureString.rsa_keygen

Now, Alice creates a message and encrypts it for Bob and signs it.

message = SecureString.new("Hello World") encrypted_message = message.to_rsa(bob_pub_key) signature = encrypted_message.sign(alice_pvt_key)

Alice sends Bob the data in +encrypted_message+ and +signature+. Bob verifies the message's signature, and then decrypts it:

is_verified = encrypted_message.verify?(alice_pub_key, signature) if( is_verified ) decrypted_message = encrypted_message.from_rsa(bob_pvt_key).to_s else raise RuntimeError, "This is not from Alice!" end

The value of Alice's original +message+ variable, and Bob's +decrypted_message+ should be identical.

== Cipher Methods Overview

The SecureString::CipherMethods module adds convenience methods for block cipher encryption, particularly for the AES-256-CBC block cipher.

The following methods illustrate a sample session for the default AES-256-CBC cipher:

Generate a random key and initialization vector.

key, iv = SecureString.aes_keygen

Now encrypt a message:

message = SecureString.new("Hello World!") cipher_text = message.to_aes(key, iv)

Now decrypt the message:

decoded_text = cipher_text.from_aes(key, iv)

= String Encodings

== Overview

Starting in Ruby 1.9.x, String instances manage their own encodings. For example, a string with Unicode characters are usually encoded as UTF-8, while a lot of source is still written in US-ASCII.

Binary data is independent of the encoding that encodes it, however using the binary data when it is assigned a multi-byte character encoding strategy can lead to a few surprises.

For example, for a Unicode string, the +length+ method returns the number of characters in the string, while +bytesize+ returns the number of bytes encoded in the string:

s = "Resum\u00E9" s.encoding --> UTF-8 s.length --> 6 s.bytesize --> 7

== SecureString Encoding

SecureString's basic design philosophy is to--as much as possible--only extend the behavior of String, not replace it. Therefore, SecureString does NOT affect the encoding of the string it is using.

This is normally not a problem--as long as you use +bytesize+ instead of +length+ to get the byte count of the data in the string.

In rare cases, you may want to change a String to the ASCII-8BIT binary encoding without changing its data. To accomplish this, one should call +force_encoding+ like so:

s = "Resum\u00E9" s.force_encoding('BINARY') s.encoding --> ASCII-8BIT s.length --> 7 s.bytesize --> 7

Note that when you do this, equality tests can be broken like so:

s = "Resum\u00E9" b = s.dup.force_encoding('BINARY') s == b --> false s.bytes.to_a == b.bytes.to_a --> true

= Contact

If you have any questions, comments, concerns, patches, or bugs, you can contact me via the github repository at:

http://github.com/paploo/secure_string

or directly via e-mail at:

mailto:jeff@paploo.net

= Version History [1.3.3 - 2011-Jul-19] Added new functionality * (FEATURE) Added PKCS5 v2 keygen from a passphrase support. * (FEATURE) Addition of escaped hex string literal support for pasting into code. * (FIX) Hex conversion is more consistently fast now. [1.3.2 - 2011-Jun-15] Changed minimum requirements from 1.8.6 to 1.8.7. * (CHANGE) Minimum requirements are 1.8.7 due to too many bugs in 1.8.6. * (FIX) Update to the documentation to reflect 1.8.7 support. [1.3.1 - 2011-Jun-15] Added public key extraction from private keys. * (FEATURE) Public keys can be extracted from private keys using either the separate_keys class method or the extract_public_key instance method. [1.3.0 - 2011-Jun-15] Ruby 1.8 compatibility. * (FEATURE) Emulation urlsafe base64 encodings in ruby 1.8. * (CHANGE) SecureString.new arguments changed to work with ruby 1.8. Instead of specifying the argument type hint first, you now do that with an options hash. (You will get a descriptive error if you try to do it the old way.) [1.2.1 - 2011-Jun-15] Bugfixes * (FIX) To/From Base64 methods were returning normal strings, making chaining impossible. [1.2.0 - 2011-May-17] Re-wrote Base64 module to address problems with RFC 2045 vs. RFC 4648 compatibility. * Added testing against source strings that generate incompatible encodings between RFC 2045 and RFC 4648. * (FEATURE) added option to strip newlines from the returned base64 string. * (CHANGE) to_base64 defaults to the standard Base64 instead of websafe Base64. * (FIX) added option to decode as websafe Base64. [1.1.2 - 2010-Nov-08] Minor gemspec file change for compatibility with bundler. [1.1.1 - 2010-Nov-05] Backed down requirements to ruby 1.9.x; Bugfixes and minor changes. * Tested in 1.9.1 and 1.9.2. * Added some documentation and tests on String encodings. * Added more spec tests. * (FEATURE) Digest methods may be supplied via string now. * (FEATURE) RSA encryption works with both public and private keys. * (FEATURE) RSA keys encoded as SecureString can be asked if public or private. * (CHANGE) BinaryStringDataMethods now is non-clobbering and independent. * (CHANGE) An empty string's integer value is now zero. * (FIX) Non-hex characters are ignored when accepting hex data input. [1.1.0 - 2010-Nov-04] Extracted methods into a module that can be easily included on any String class. [1.0.0 - 2010-Nov-04] Added Tests, Examples, and Bugfixes * Added a full suite of spec tests. * (FEATURE) Can get a list of supported ciphers. * (FEATURE) Auto-determine AES key length in +to_aes+ and +from_aes+. * (CHANGE) RSA now defaults to 2048-bit keys instead of just 1024. * (FIX) Init from integer works now. * (FIX) RSA signatures can take digest classes, not just instances. [0.9.0 - 2010-Nov-03] Initial release. * Feature complete, but lacks spec tests and examples.

= TODO List

  • See what happens when including SecurizeString into an object that is not a String. What are the expected root methods? +to_s+, self.new(string) are two that I know of.
  • Add HMAC support.

= License

The files contained in this repository are released under the commercially and GPL compatible "New BSD License", given below:

== License Text

Copyright (c) 2010, Jeffrey C. Reinecke
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the copyright holders nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL JEFFREY REINECKE BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

FAQs

Package last updated on 19 Jul 2011

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc