repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.3/ext/json/ext/parser/extconf.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.3/ext/json/ext/parser/extconf.rb | require 'mkmf'
require 'rbconfig'
unless $CFLAGS.gsub!(/ -O[\dsz]?/, ' -O3')
$CFLAGS << ' -O3'
end
if CONFIG['CC'] =~ /gcc/
$CFLAGS << ' -Wall'
#unless $CFLAGS.gsub!(/ -O[\dsz]?/, ' -O0 -ggdb')
# $CFLAGS << ' -O0 -ggdb'
#end
end
have_header("re.h")
create_makefile 'json/ext/parser'
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.3/lib/json.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.3/lib/json.rb | require 'json/common'
module JSON
require 'json/version'
begin
require 'json/ext'
rescue LoadError
require 'json/pure'
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.3/lib/json/common.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.3/lib/json/common.rb | require 'json/version'
require 'iconv'
module JSON
class << self
# If _object_ is string-like parse the string and return the parsed result
# as a Ruby data structure. Otherwise generate a JSON text from the Ruby
# data structure object and return it.
#
# The _opts_ argument is passed through to generate/parse respectively, see
# generate and parse for their documentation.
def [](object, opts = {})
if object.respond_to? :to_str
JSON.parse(object.to_str, opts => {})
else
JSON.generate(object, opts => {})
end
end
# Returns the JSON parser class, that is used by JSON. This might be either
# JSON::Ext::Parser or JSON::Pure::Parser.
attr_reader :parser
# Set the JSON parser class _parser_ to be used by JSON.
def parser=(parser) # :nodoc:
@parser = parser
remove_const :Parser if const_defined? :Parser
const_set :Parser, parser
end
# Return the constant located at _path_. The format of _path_ has to be
# either ::A::B::C or A::B::C. In any case A has to be located at the top
# level (absolute namespace path?). If there doesn't exist a constant at
# the given path, an ArgumentError is raised.
def deep_const_get(path) # :nodoc:
path.to_s.split(/::/).inject(Object) do |p, c|
case
when c.empty? then p
when p.const_defined?(c) then p.const_get(c)
else
begin
p.const_missing(c)
rescue NameError
raise ArgumentError, "can't find const #{path}"
end
end
end
end
# Set the module _generator_ to be used by JSON.
def generator=(generator) # :nodoc:
@generator = generator
generator_methods = generator::GeneratorMethods
for const in generator_methods.constants
klass = deep_const_get(const)
modul = generator_methods.const_get(const)
klass.class_eval do
instance_methods(false).each do |m|
m.to_s == 'to_json' and remove_method m
end
include modul
end
end
self.state = generator::State
const_set :State, self.state
const_set :SAFE_STATE_PROTOTYPE, State.new.freeze
const_set :FAST_STATE_PROTOTYPE, State.new(
:indent => '',
:space => '',
:object_nl => "",
:array_nl => "",
:max_nesting => false
).freeze
const_set :PRETTY_STATE_PROTOTYPE, State.new(
:indent => ' ',
:space => ' ',
:object_nl => "\n",
:array_nl => "\n"
).freeze
end
# Returns the JSON generator modul, that is used by JSON. This might be
# either JSON::Ext::Generator or JSON::Pure::Generator.
attr_reader :generator
# Returns the JSON generator state class, that is used by JSON. This might
# be either JSON::Ext::Generator::State or JSON::Pure::Generator::State.
attr_accessor :state
# This is create identifier, that is used to decide, if the _json_create_
# hook of a class should be called. It defaults to 'json_class'.
attr_accessor :create_id
end
self.create_id = 'json_class'
NaN = 0.0/0
Infinity = 1.0/0
MinusInfinity = -Infinity
# The base exception for JSON errors.
class JSONError < StandardError; end
# This exception is raised, if a parser error occurs.
class ParserError < JSONError; end
# This exception is raised, if the nesting of parsed datastructures is too
# deep.
class NestingError < ParserError; end
# :stopdoc:
class CircularDatastructure < NestingError; end
# :startdoc:
# This exception is raised, if a generator or unparser error occurs.
class GeneratorError < JSONError; end
# For backwards compatibility
UnparserError = GeneratorError
# This exception is raised, if the required unicode support is missing on the
# system. Usually this means, that the iconv library is not installed.
class MissingUnicodeSupport < JSONError; end
module_function
# Parse the JSON document _source_ into a Ruby data structure and return it.
#
# _opts_ can have the following
# keys:
# * *max_nesting*: The maximum depth of nesting allowed in the parsed data
# structures. Disable depth checking with :max_nesting => false, it defaults
# to 19.
# * *allow_nan*: If set to true, allow NaN, Infinity and -Infinity in
# defiance of RFC 4627 to be parsed by the Parser. This option defaults
# to false.
# * *symbolize_names*: If set to true, returns symbols for the names
# (keys) in a JSON object. Otherwise strings are returned, which is also
# the default.
# * *create_additions*: If set to false, the Parser doesn't create
# additions even if a matchin class and create_id was found. This option
# defaults to true.
# * *object_class*: Defaults to Hash
# * *array_class*: Defaults to Array
def parse(source, opts = {})
Parser.new(source, opts).parse
end
# Parse the JSON document _source_ into a Ruby data structure and return it.
# The bang version of the parse method, defaults to the more dangerous values
# for the _opts_ hash, so be sure only to parse trusted _source_ documents.
#
# _opts_ can have the following keys:
# * *max_nesting*: The maximum depth of nesting allowed in the parsed data
# structures. Enable depth checking with :max_nesting => anInteger. The parse!
# methods defaults to not doing max depth checking: This can be dangerous,
# if someone wants to fill up your stack.
# * *allow_nan*: If set to true, allow NaN, Infinity, and -Infinity in
# defiance of RFC 4627 to be parsed by the Parser. This option defaults
# to true.
# * *create_additions*: If set to false, the Parser doesn't create
# additions even if a matchin class and create_id was found. This option
# defaults to true.
def parse!(source, opts = {})
opts = {
:max_nesting => false,
:allow_nan => true
}.update(opts)
Parser.new(source, opts).parse
end
# Generate a JSON document from the Ruby data structure _obj_ and return
# it. _state_ is * a JSON::State object,
# * or a Hash like object (responding to to_hash),
# * an object convertible into a hash by a to_h method,
# that is used as or to configure a State object.
#
# It defaults to a state object, that creates the shortest possible JSON text
# in one line, checks for circular data structures and doesn't allow NaN,
# Infinity, and -Infinity.
#
# A _state_ hash can have the following keys:
# * *indent*: a string used to indent levels (default: ''),
# * *space*: a string that is put after, a : or , delimiter (default: ''),
# * *space_before*: a string that is put before a : pair delimiter (default: ''),
# * *object_nl*: a string that is put at the end of a JSON object (default: ''),
# * *array_nl*: a string that is put at the end of a JSON array (default: ''),
# * *allow_nan*: true if NaN, Infinity, and -Infinity should be
# generated, otherwise an exception is thrown, if these values are
# encountered. This options defaults to false.
# * *max_nesting*: The maximum depth of nesting allowed in the data
# structures from which JSON is to be generated. Disable depth checking
# with :max_nesting => false, it defaults to 19.
#
# See also the fast_generate for the fastest creation method with the least
# amount of sanity checks, and the pretty_generate method for some
# defaults for a pretty output.
def generate(obj, opts = nil)
if opts
if opts.respond_to? :to_hash
opts = opts.to_hash
elsif opts.respond_to? :to_h
opts = opts.to_h
else
raise TypeError, "can't convert #{opts.class} into Hash"
end
state = SAFE_STATE_PROTOTYPE.dup
state = state.configure(opts)
else
state = SAFE_STATE_PROTOTYPE
end
state.generate(obj)
end
# :stopdoc:
# I want to deprecate these later, so I'll first be silent about them, and
# later delete them.
alias unparse generate
module_function :unparse
# :startdoc:
# Generate a JSON document from the Ruby data structure _obj_ and return it.
# This method disables the checks for circles in Ruby objects.
#
# *WARNING*: Be careful not to pass any Ruby data structures with circles as
# _obj_ argument, because this will cause JSON to go into an infinite loop.
def fast_generate(obj, opts = nil)
if opts
if opts.respond_to? :to_hash
opts = opts.to_hash
elsif opts.respond_to? :to_h
opts = opts.to_h
else
raise TypeError, "can't convert #{opts.class} into Hash"
end
state = FAST_STATE_PROTOTYPE.dup
state.configure(opts)
else
state = FAST_STATE_PROTOTYPE
end
state.generate(obj)
end
# :stopdoc:
# I want to deprecate these later, so I'll first be silent about them, and later delete them.
alias fast_unparse fast_generate
module_function :fast_unparse
# :startdoc:
# Generate a JSON document from the Ruby data structure _obj_ and return it.
# The returned document is a prettier form of the document returned by
# #unparse.
#
# The _opts_ argument can be used to configure the generator, see the
# generate method for a more detailed explanation.
def pretty_generate(obj, opts = nil)
if opts
if opts.respond_to? :to_hash
opts = opts.to_hash
elsif opts.respond_to? :to_h
opts = opts.to_h
else
raise TypeError, "can't convert #{opts.class} into Hash"
end
state = PRETTY_STATE_PROTOTYPE.dup
state.configure(opts)
else
state = PRETTY_STATE_PROTOTYPE
end
state.generate(obj)
end
# :stopdoc:
# I want to deprecate these later, so I'll first be silent about them, and later delete them.
alias pretty_unparse pretty_generate
module_function :pretty_unparse
# :startdoc:
# Load a ruby data structure from a JSON _source_ and return it. A source can
# either be a string-like object, an IO like object, or an object responding
# to the read method. If _proc_ was given, it will be called with any nested
# Ruby object as an argument recursively in depth first order.
#
# This method is part of the implementation of the load/dump interface of
# Marshal and YAML.
def load(source, proc = nil)
if source.respond_to? :to_str
source = source.to_str
elsif source.respond_to? :to_io
source = source.to_io.read
else
source = source.read
end
result = parse(source, :max_nesting => false, :allow_nan => true)
recurse_proc(result, &proc) if proc
result
end
def recurse_proc(result, &proc)
case result
when Array
result.each { |x| recurse_proc x, &proc }
proc.call result
when Hash
result.each { |x, y| recurse_proc x, &proc; recurse_proc y, &proc }
proc.call result
else
proc.call result
end
end
alias restore load
module_function :restore
# Dumps _obj_ as a JSON string, i.e. calls generate on the object and returns
# the result.
#
# If anIO (an IO like object or an object that responds to the write method)
# was given, the resulting JSON is written to it.
#
# If the number of nested arrays or objects exceeds _limit_ an ArgumentError
# exception is raised. This argument is similar (but not exactly the
# same!) to the _limit_ argument in Marshal.dump.
#
# This method is part of the implementation of the load/dump interface of
# Marshal and YAML.
def dump(obj, anIO = nil, limit = nil)
if anIO and limit.nil?
anIO = anIO.to_io if anIO.respond_to?(:to_io)
unless anIO.respond_to?(:write)
limit = anIO
anIO = nil
end
end
limit ||= 0
result = generate(obj, :allow_nan => true, :max_nesting => limit)
if anIO
anIO.write result
anIO
else
result
end
rescue JSON::NestingError
raise ArgumentError, "exceed depth limit"
end
# Shortuct for iconv.
def self.iconv(to, from, string)
Iconv.iconv(to, from, string).first
end
end
module ::Kernel
private
# Outputs _objs_ to STDOUT as JSON strings in the shortest form, that is in
# one line.
def j(*objs)
objs.each do |obj|
puts JSON::generate(obj, :allow_nan => true, :max_nesting => false)
end
nil
end
# Ouputs _objs_ to STDOUT as JSON strings in a pretty format, with
# indentation and over many lines.
def jj(*objs)
objs.each do |obj|
puts JSON::pretty_generate(obj, :allow_nan => true, :max_nesting => false)
end
nil
end
# If _object_ is string-like parse the string and return the parsed result as
# a Ruby data structure. Otherwise generate a JSON text from the Ruby data
# structure object and return it.
#
# The _opts_ argument is passed through to generate/parse respectively, see
# generate and parse for their documentation.
def JSON(object, opts = {})
if object.respond_to? :to_str
JSON.parse(object.to_str, opts)
else
JSON.generate(object, opts)
end
end
end
class ::Class
# Returns true, if this class can be used to create an instance
# from a serialised JSON string. The class has to implement a class
# method _json_create_ that expects a hash as first parameter, which includes
# the required data.
def json_creatable?
respond_to?(:json_create)
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.3/lib/json/version.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.3/lib/json/version.rb | module JSON
# JSON version
VERSION = '1.4.3'
VERSION_ARRAY = VERSION.split(/\./).map { |x| x.to_i } # :nodoc:
VERSION_MAJOR = VERSION_ARRAY[0] # :nodoc:
VERSION_MINOR = VERSION_ARRAY[1] # :nodoc:
VERSION_BUILD = VERSION_ARRAY[2] # :nodoc:
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.3/lib/json/ext.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.3/lib/json/ext.rb | require 'json/common'
module JSON
# This module holds all the modules/classes that implement JSON's
# functionality as C extensions.
module Ext
require 'json/ext/parser'
require 'json/ext/generator'
$DEBUG and warn "Using c extension for JSON."
JSON.parser = Parser
JSON.generator = Generator
end
JSON_LOADED = true
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.3/lib/json/pure.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.3/lib/json/pure.rb | require 'json/common'
require 'json/pure/parser'
require 'json/pure/generator'
module JSON
begin
require 'iconv'
# An iconv instance to convert from UTF8 to UTF16 Big Endian.
UTF16toUTF8 = Iconv.new('utf-8', 'utf-16be') # :nodoc:
# An iconv instance to convert from UTF16 Big Endian to UTF8.
UTF8toUTF16 = Iconv.new('utf-16be', 'utf-8') # :nodoc:
UTF8toUTF16.iconv('no bom')
rescue LoadError
raise MissingUnicodeSupport,
"iconv couldn't be loaded, which is required for UTF-8/UTF-16 conversions"
rescue Errno::EINVAL, Iconv::InvalidEncoding
# Iconv doesn't support big endian utf-16. Let's try to hack this manually
# into the converters.
begin
old_verbose, $VERBSOSE = $VERBOSE, nil
# An iconv instance to convert from UTF8 to UTF16 Big Endian.
UTF16toUTF8 = Iconv.new('utf-8', 'utf-16') # :nodoc:
# An iconv instance to convert from UTF16 Big Endian to UTF8.
UTF8toUTF16 = Iconv.new('utf-16', 'utf-8') # :nodoc:
UTF8toUTF16.iconv('no bom')
if UTF8toUTF16.iconv("\xe2\x82\xac") == "\xac\x20"
swapper = Class.new do
def initialize(iconv) # :nodoc:
@iconv = iconv
end
def iconv(string) # :nodoc:
result = @iconv.iconv(string)
JSON.swap!(result)
end
end
UTF8toUTF16 = swapper.new(UTF8toUTF16) # :nodoc:
end
if UTF16toUTF8.iconv("\xac\x20") == "\xe2\x82\xac"
swapper = Class.new do
def initialize(iconv) # :nodoc:
@iconv = iconv
end
def iconv(string) # :nodoc:
string = JSON.swap!(string.dup)
@iconv.iconv(string)
end
end
UTF16toUTF8 = swapper.new(UTF16toUTF8) # :nodoc:
end
rescue Errno::EINVAL, Iconv::InvalidEncoding
raise MissingUnicodeSupport, "iconv doesn't seem to support UTF-8/UTF-16 conversions"
ensure
$VERBOSE = old_verbose
end
end
# Swap consecutive bytes of _string_ in place.
def self.swap!(string) # :nodoc:
0.upto(string.size / 2) do |i|
break unless string[2 * i + 1]
string[2 * i], string[2 * i + 1] = string[2 * i + 1], string[2 * i]
end
string
end
# This module holds all the modules/classes that implement JSON's
# functionality in pure ruby.
module Pure
$DEBUG and warn "Using pure library for JSON."
JSON.parser = Parser
JSON.generator = Generator
end
JSON_LOADED = true
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.3/lib/json/editor.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.3/lib/json/editor.rb | # To use the GUI JSON editor, start the edit_json.rb executable script. It
# requires ruby-gtk to be installed.
require 'gtk2'
require 'iconv'
require 'json'
require 'rbconfig'
require 'open-uri'
module JSON
module Editor
include Gtk
# Beginning of the editor window title
TITLE = 'JSON Editor'.freeze
# Columns constants
ICON_COL, TYPE_COL, CONTENT_COL = 0, 1, 2
# JSON primitive types (Containers)
CONTAINER_TYPES = %w[Array Hash].sort
# All JSON primitive types
ALL_TYPES = (%w[TrueClass FalseClass Numeric String NilClass] +
CONTAINER_TYPES).sort
# The Nodes necessary for the tree representation of a JSON document
ALL_NODES = (ALL_TYPES + %w[Key]).sort
DEFAULT_DIALOG_KEY_PRESS_HANDLER = lambda do |dialog, event|
case event.keyval
when Gdk::Keyval::GDK_Return
dialog.response Dialog::RESPONSE_ACCEPT
when Gdk::Keyval::GDK_Escape
dialog.response Dialog::RESPONSE_REJECT
end
end
# Returns the Gdk::Pixbuf of the icon named _name_ from the icon cache.
def Editor.fetch_icon(name)
@icon_cache ||= {}
unless @icon_cache.key?(name)
path = File.dirname(__FILE__)
@icon_cache[name] = Gdk::Pixbuf.new(File.join(path, name + '.xpm'))
end
@icon_cache[name]
end
# Opens an error dialog on top of _window_ showing the error message
# _text_.
def Editor.error_dialog(window, text)
dialog = MessageDialog.new(window, Dialog::MODAL,
MessageDialog::ERROR,
MessageDialog::BUTTONS_CLOSE, text)
dialog.show_all
dialog.run
rescue TypeError
dialog = MessageDialog.new(Editor.window, Dialog::MODAL,
MessageDialog::ERROR,
MessageDialog::BUTTONS_CLOSE, text)
dialog.show_all
dialog.run
ensure
dialog.destroy if dialog
end
# Opens a yes/no question dialog on top of _window_ showing the error
# message _text_. If yes was answered _true_ is returned, otherwise
# _false_.
def Editor.question_dialog(window, text)
dialog = MessageDialog.new(window, Dialog::MODAL,
MessageDialog::QUESTION,
MessageDialog::BUTTONS_YES_NO, text)
dialog.show_all
dialog.run do |response|
return Gtk::Dialog::RESPONSE_YES === response
end
ensure
dialog.destroy if dialog
end
# Convert the tree model starting from Gtk::TreeIter _iter_ into a Ruby
# data structure and return it.
def Editor.model2data(iter)
return nil if iter.nil?
case iter.type
when 'Hash'
hash = {}
iter.each { |c| hash[c.content] = Editor.model2data(c.first_child) }
hash
when 'Array'
array = Array.new(iter.n_children)
iter.each_with_index { |c, i| array[i] = Editor.model2data(c) }
array
when 'Key'
iter.content
when 'String'
iter.content
when 'Numeric'
content = iter.content
if /\./.match(content)
content.to_f
else
content.to_i
end
when 'TrueClass'
true
when 'FalseClass'
false
when 'NilClass'
nil
else
fail "Unknown type found in model: #{iter.type}"
end
end
# Convert the Ruby data structure _data_ into tree model data for Gtk and
# returns the whole model. If the parameter _model_ wasn't given a new
# Gtk::TreeStore is created as the model. The _parent_ parameter specifies
# the parent node (iter, Gtk:TreeIter instance) to which the data is
# appended, alternativeley the result of the yielded block is used as iter.
def Editor.data2model(data, model = nil, parent = nil)
model ||= TreeStore.new(Gdk::Pixbuf, String, String)
iter = if block_given?
yield model
else
model.append(parent)
end
case data
when Hash
iter.type = 'Hash'
data.sort.each do |key, value|
pair_iter = model.append(iter)
pair_iter.type = 'Key'
pair_iter.content = key.to_s
Editor.data2model(value, model, pair_iter)
end
when Array
iter.type = 'Array'
data.each do |value|
Editor.data2model(value, model, iter)
end
when Numeric
iter.type = 'Numeric'
iter.content = data.to_s
when String, true, false, nil
iter.type = data.class.name
iter.content = data.nil? ? 'null' : data.to_s
else
iter.type = 'String'
iter.content = data.to_s
end
model
end
# The Gtk::TreeIter class is reopened and some auxiliary methods are added.
class Gtk::TreeIter
include Enumerable
# Traverse each of this Gtk::TreeIter instance's children
# and yield to them.
def each
n_children.times { |i| yield nth_child(i) }
end
# Recursively traverse all nodes of this Gtk::TreeIter's subtree
# (including self) and yield to them.
def recursive_each(&block)
yield self
each do |i|
i.recursive_each(&block)
end
end
# Remove the subtree of this Gtk::TreeIter instance from the
# model _model_.
def remove_subtree(model)
while current = first_child
model.remove(current)
end
end
# Returns the type of this node.
def type
self[TYPE_COL]
end
# Sets the type of this node to _value_. This implies setting
# the respective icon accordingly.
def type=(value)
self[TYPE_COL] = value
self[ICON_COL] = Editor.fetch_icon(value)
end
# Returns the content of this node.
def content
self[CONTENT_COL]
end
# Sets the content of this node to _value_.
def content=(value)
self[CONTENT_COL] = value
end
end
# This module bundles some method, that can be used to create a menu. It
# should be included into the class in question.
module MenuExtension
include Gtk
# Creates a Menu, that includes MenuExtension. _treeview_ is the
# Gtk::TreeView, on which it operates.
def initialize(treeview)
@treeview = treeview
@menu = Menu.new
end
# Returns the Gtk::TreeView of this menu.
attr_reader :treeview
# Returns the menu.
attr_reader :menu
# Adds a Gtk::SeparatorMenuItem to this instance's #menu.
def add_separator
menu.append SeparatorMenuItem.new
end
# Adds a Gtk::MenuItem to this instance's #menu. _label_ is the label
# string, _klass_ is the item type, and _callback_ is the procedure, that
# is called if the _item_ is activated.
def add_item(label, keyval = nil, klass = MenuItem, &callback)
label = "#{label} (C-#{keyval.chr})" if keyval
item = klass.new(label)
item.signal_connect(:activate, &callback)
if keyval
self.signal_connect(:'key-press-event') do |item, event|
if event.state & Gdk::Window::ModifierType::CONTROL_MASK != 0 and
event.keyval == keyval
callback.call item
end
end
end
menu.append item
item
end
# This method should be implemented in subclasses to create the #menu of
# this instance. It has to be called after an instance of this class is
# created, to build the menu.
def create
raise NotImplementedError
end
def method_missing(*a, &b)
treeview.__send__(*a, &b)
end
end
# This class creates the popup menu, that opens when clicking onto the
# treeview.
class PopUpMenu
include MenuExtension
# Change the type or content of the selected node.
def change_node(item)
if current = selection.selected
parent = current.parent
old_type, old_content = current.type, current.content
if ALL_TYPES.include?(old_type)
@clipboard_data = Editor.model2data(current)
type, content = ask_for_element(parent, current.type,
current.content)
if type
current.type, current.content = type, content
current.remove_subtree(model)
toplevel.display_status("Changed a node in tree.")
window.change
end
else
toplevel.display_status(
"Cannot change node of type #{old_type} in tree!")
end
end
end
# Cut the selected node and its subtree, and save it into the
# clipboard.
def cut_node(item)
if current = selection.selected
if current and current.type == 'Key'
@clipboard_data = {
current.content => Editor.model2data(current.first_child)
}
else
@clipboard_data = Editor.model2data(current)
end
model.remove(current)
window.change
toplevel.display_status("Cut a node from tree.")
end
end
# Copy the selected node and its subtree, and save it into the
# clipboard.
def copy_node(item)
if current = selection.selected
if current and current.type == 'Key'
@clipboard_data = {
current.content => Editor.model2data(current.first_child)
}
else
@clipboard_data = Editor.model2data(current)
end
window.change
toplevel.display_status("Copied a node from tree.")
end
end
# Paste the data in the clipboard into the selected Array or Hash by
# appending it.
def paste_node_appending(item)
if current = selection.selected
if @clipboard_data
case current.type
when 'Array'
Editor.data2model(@clipboard_data, model, current)
expand_collapse(current)
when 'Hash'
if @clipboard_data.is_a? Hash
parent = current.parent
hash = Editor.model2data(current)
model.remove(current)
hash.update(@clipboard_data)
Editor.data2model(hash, model, parent)
if parent
expand_collapse(parent)
elsif @expanded
expand_all
end
window.change
else
toplevel.display_status(
"Cannot paste non-#{current.type} data into '#{current.type}'!")
end
else
toplevel.display_status(
"Cannot paste node below '#{current.type}'!")
end
else
toplevel.display_status("Nothing to paste in clipboard!")
end
else
toplevel.display_status("Append a node into the root first!")
end
end
# Paste the data in the clipboard into the selected Array inserting it
# before the selected element.
def paste_node_inserting_before(item)
if current = selection.selected
if @clipboard_data
parent = current.parent or return
parent_type = parent.type
if parent_type == 'Array'
selected_index = parent.each_with_index do |c, i|
break i if c == current
end
Editor.data2model(@clipboard_data, model, parent) do |m|
m.insert_before(parent, current)
end
expand_collapse(current)
toplevel.display_status("Inserted an element to " +
"'#{parent_type}' before index #{selected_index}.")
window.change
else
toplevel.display_status(
"Cannot insert node below '#{parent_type}'!")
end
else
toplevel.display_status("Nothing to paste in clipboard!")
end
else
toplevel.display_status("Append a node into the root first!")
end
end
# Append a new node to the selected Hash or Array.
def append_new_node(item)
if parent = selection.selected
parent_type = parent.type
case parent_type
when 'Hash'
key, type, content = ask_for_hash_pair(parent)
key or return
iter = create_node(parent, 'Key', key)
iter = create_node(iter, type, content)
toplevel.display_status(
"Added a (key, value)-pair to '#{parent_type}'.")
window.change
when 'Array'
type, content = ask_for_element(parent)
type or return
iter = create_node(parent, type, content)
window.change
toplevel.display_status("Appendend an element to '#{parent_type}'.")
else
toplevel.display_status("Cannot append to '#{parent_type}'!")
end
else
type, content = ask_for_element
type or return
iter = create_node(nil, type, content)
window.change
end
end
# Insert a new node into an Array before the selected element.
def insert_new_node(item)
if current = selection.selected
parent = current.parent or return
parent_parent = parent.parent
parent_type = parent.type
if parent_type == 'Array'
selected_index = parent.each_with_index do |c, i|
break i if c == current
end
type, content = ask_for_element(parent)
type or return
iter = model.insert_before(parent, current)
iter.type, iter.content = type, content
toplevel.display_status("Inserted an element to " +
"'#{parent_type}' before index #{selected_index}.")
window.change
else
toplevel.display_status(
"Cannot insert node below '#{parent_type}'!")
end
else
toplevel.display_status("Append a node into the root first!")
end
end
# Recursively collapse/expand a subtree starting from the selected node.
def collapse_expand(item)
if current = selection.selected
if row_expanded?(current.path)
collapse_row(current.path)
else
expand_row(current.path, true)
end
else
toplevel.display_status("Append a node into the root first!")
end
end
# Create the menu.
def create
add_item("Change node", ?n, &method(:change_node))
add_separator
add_item("Cut node", ?X, &method(:cut_node))
add_item("Copy node", ?C, &method(:copy_node))
add_item("Paste node (appending)", ?A, &method(:paste_node_appending))
add_item("Paste node (inserting before)", ?I,
&method(:paste_node_inserting_before))
add_separator
add_item("Append new node", ?a, &method(:append_new_node))
add_item("Insert new node before", ?i, &method(:insert_new_node))
add_separator
add_item("Collapse/Expand node (recursively)", ?e,
&method(:collapse_expand))
menu.show_all
signal_connect(:button_press_event) do |widget, event|
if event.kind_of? Gdk::EventButton and event.button == 3
menu.popup(nil, nil, event.button, event.time)
end
end
signal_connect(:popup_menu) do
menu.popup(nil, nil, 0, Gdk::Event::CURRENT_TIME)
end
end
end
# This class creates the File pulldown menu.
class FileMenu
include MenuExtension
# Clear the model and filename, but ask to save the JSON document, if
# unsaved changes have occured.
def new(item)
window.clear
end
# Open a file and load it into the editor. Ask to save the JSON document
# first, if unsaved changes have occured.
def open(item)
window.file_open
end
def open_location(item)
window.location_open
end
# Revert the current JSON document in the editor to the saved version.
def revert(item)
window.instance_eval do
@filename and file_open(@filename)
end
end
# Save the current JSON document.
def save(item)
window.file_save
end
# Save the current JSON document under the given filename.
def save_as(item)
window.file_save_as
end
# Quit the editor, after asking to save any unsaved changes first.
def quit(item)
window.quit
end
# Create the menu.
def create
title = MenuItem.new('File')
title.submenu = menu
add_item('New', &method(:new))
add_item('Open', ?o, &method(:open))
add_item('Open location', ?l, &method(:open_location))
add_item('Revert', &method(:revert))
add_separator
add_item('Save', ?s, &method(:save))
add_item('Save As', ?S, &method(:save_as))
add_separator
add_item('Quit', ?q, &method(:quit))
title
end
end
# This class creates the Edit pulldown menu.
class EditMenu
include MenuExtension
# Copy data from model into primary clipboard.
def copy(item)
data = Editor.model2data(model.iter_first)
json = JSON.pretty_generate(data, :max_nesting => false)
c = Gtk::Clipboard.get(Gdk::Selection::PRIMARY)
c.text = json
end
# Copy json text from primary clipboard into model.
def paste(item)
c = Gtk::Clipboard.get(Gdk::Selection::PRIMARY)
if json = c.wait_for_text
window.ask_save if @changed
begin
window.edit json
rescue JSON::ParserError
window.clear
end
end
end
# Find a string in all nodes' contents and select the found node in the
# treeview.
def find(item)
@search = ask_for_find_term(@search) or return
iter = model.get_iter('0') or return
iter.recursive_each do |i|
if @iter
if @iter != i
next
else
@iter = nil
next
end
elsif @search.match(i[CONTENT_COL])
set_cursor(i.path, nil, false)
@iter = i
break
end
end
end
# Repeat the last search given by #find.
def find_again(item)
@search or return
iter = model.get_iter('0')
iter.recursive_each do |i|
if @iter
if @iter != i
next
else
@iter = nil
next
end
elsif @search.match(i[CONTENT_COL])
set_cursor(i.path, nil, false)
@iter = i
break
end
end
end
# Sort (Reverse sort) all elements of the selected array by the given
# expression. _x_ is the element in question.
def sort(item)
if current = selection.selected
if current.type == 'Array'
parent = current.parent
ary = Editor.model2data(current)
order, reverse = ask_for_order
order or return
begin
block = eval "lambda { |x| #{order} }"
if reverse
ary.sort! { |a,b| block[b] <=> block[a] }
else
ary.sort! { |a,b| block[a] <=> block[b] }
end
rescue => e
Editor.error_dialog(self, "Failed to sort Array with #{order}: #{e}!")
else
Editor.data2model(ary, model, parent) do |m|
m.insert_before(parent, current)
end
model.remove(current)
expand_collapse(parent)
window.change
toplevel.display_status("Array has been sorted.")
end
else
toplevel.display_status("Only Array nodes can be sorted!")
end
else
toplevel.display_status("Select an Array to sort first!")
end
end
# Create the menu.
def create
title = MenuItem.new('Edit')
title.submenu = menu
add_item('Copy', ?c, &method(:copy))
add_item('Paste', ?v, &method(:paste))
add_separator
add_item('Find', ?f, &method(:find))
add_item('Find Again', ?g, &method(:find_again))
add_separator
add_item('Sort', ?S, &method(:sort))
title
end
end
class OptionsMenu
include MenuExtension
# Collapse/Expand all nodes by default.
def collapsed_nodes(item)
if expanded
self.expanded = false
collapse_all
else
self.expanded = true
expand_all
end
end
# Toggle pretty saving mode on/off.
def pretty_saving(item)
@pretty_item.toggled
window.change
end
attr_reader :pretty_item
# Create the menu.
def create
title = MenuItem.new('Options')
title.submenu = menu
add_item('Collapsed nodes', nil, CheckMenuItem, &method(:collapsed_nodes))
@pretty_item = add_item('Pretty saving', nil, CheckMenuItem,
&method(:pretty_saving))
@pretty_item.active = true
window.unchange
title
end
end
# This class inherits from Gtk::TreeView, to configure it and to add a lot
# of behaviour to it.
class JSONTreeView < Gtk::TreeView
include Gtk
# Creates a JSONTreeView instance, the parameter _window_ is
# a MainWindow instance and used for self delegation.
def initialize(window)
@window = window
super(TreeStore.new(Gdk::Pixbuf, String, String))
self.selection.mode = SELECTION_BROWSE
@expanded = false
self.headers_visible = false
add_columns
add_popup_menu
end
# Returns the MainWindow instance of this JSONTreeView.
attr_reader :window
# Returns true, if nodes are autoexpanding, false otherwise.
attr_accessor :expanded
private
def add_columns
cell = CellRendererPixbuf.new
column = TreeViewColumn.new('Icon', cell,
'pixbuf' => ICON_COL
)
append_column(column)
cell = CellRendererText.new
column = TreeViewColumn.new('Type', cell,
'text' => TYPE_COL
)
append_column(column)
cell = CellRendererText.new
cell.editable = true
column = TreeViewColumn.new('Content', cell,
'text' => CONTENT_COL
)
cell.signal_connect(:edited, &method(:cell_edited))
append_column(column)
end
def unify_key(iter, key)
return unless iter.type == 'Key'
parent = iter.parent
if parent.any? { |c| c != iter and c.content == key }
old_key = key
i = 0
begin
key = sprintf("%s.%d", old_key, i += 1)
end while parent.any? { |c| c != iter and c.content == key }
end
iter.content = key
end
def cell_edited(cell, path, value)
iter = model.get_iter(path)
case iter.type
when 'Key'
unify_key(iter, value)
toplevel.display_status('Key has been changed.')
when 'FalseClass'
value.downcase!
if value == 'true'
iter.type, iter.content = 'TrueClass', 'true'
end
when 'TrueClass'
value.downcase!
if value == 'false'
iter.type, iter.content = 'FalseClass', 'false'
end
when 'Numeric'
iter.content =
if value == 'Infinity'
value
else
(Integer(value) rescue Float(value) rescue 0).to_s
end
when 'String'
iter.content = value
when 'Hash', 'Array'
return
else
fail "Unknown type found in model: #{iter.type}"
end
window.change
end
def configure_value(value, type)
value.editable = false
case type
when 'Array', 'Hash'
value.text = ''
when 'TrueClass'
value.text = 'true'
when 'FalseClass'
value.text = 'false'
when 'NilClass'
value.text = 'null'
when 'Numeric', 'String'
value.text ||= ''
value.editable = true
else
raise ArgumentError, "unknown type '#{type}' encountered"
end
end
def add_popup_menu
menu = PopUpMenu.new(self)
menu.create
end
public
# Create a _type_ node with content _content_, and add it to _parent_
# in the model. If _parent_ is nil, create a new model and put it into
# the editor treeview.
def create_node(parent, type, content)
iter = if parent
model.append(parent)
else
new_model = Editor.data2model(nil)
toplevel.view_new_model(new_model)
new_model.iter_first
end
iter.type, iter.content = type, content
expand_collapse(parent) if parent
iter
end
# Ask for a hash key, value pair to be added to the Hash node _parent_.
def ask_for_hash_pair(parent)
key_input = type_input = value_input = nil
dialog = Dialog.new("New (key, value) pair for Hash", nil, nil,
[ Stock::OK, Dialog::RESPONSE_ACCEPT ],
[ Stock::CANCEL, Dialog::RESPONSE_REJECT ]
)
dialog.width_request = 640
hbox = HBox.new(false, 5)
hbox.pack_start(Label.new("Key:"), false)
hbox.pack_start(key_input = Entry.new)
key_input.text = @key || ''
dialog.vbox.pack_start(hbox, false)
key_input.signal_connect(:activate) do
if parent.any? { |c| c.content == key_input.text }
toplevel.display_status('Key already exists in Hash!')
key_input.text = ''
else
toplevel.display_status('Key has been changed.')
end
end
hbox = HBox.new(false, 5)
hbox.pack_start(Label.new("Type:"), false)
hbox.pack_start(type_input = ComboBox.new(true))
ALL_TYPES.each { |t| type_input.append_text(t) }
type_input.active = @type || 0
dialog.vbox.pack_start(hbox, false)
type_input.signal_connect(:changed) do
value_input.editable = false
case ALL_TYPES[type_input.active]
when 'Array', 'Hash'
value_input.text = ''
when 'TrueClass'
value_input.text = 'true'
when 'FalseClass'
value_input.text = 'false'
when 'NilClass'
value_input.text = 'null'
else
value_input.text = ''
value_input.editable = true
end
end
hbox = HBox.new(false, 5)
hbox.pack_start(Label.new("Value:"), false)
hbox.pack_start(value_input = Entry.new)
value_input.width_chars = 60
value_input.text = @value || ''
dialog.vbox.pack_start(hbox, false)
dialog.signal_connect(:'key-press-event', &DEFAULT_DIALOG_KEY_PRESS_HANDLER)
dialog.show_all
self.focus = dialog
dialog.run do |response|
if response == Dialog::RESPONSE_ACCEPT
@key = key_input.text
type = ALL_TYPES[@type = type_input.active]
content = value_input.text
return @key, type, content
end
end
return
ensure
dialog.destroy
end
# Ask for an element to be appended _parent_.
def ask_for_element(parent = nil, default_type = nil, value_text = @content)
type_input = value_input = nil
dialog = Dialog.new(
"New element into #{parent ? parent.type : 'root'}",
nil, nil,
[ Stock::OK, Dialog::RESPONSE_ACCEPT ],
[ Stock::CANCEL, Dialog::RESPONSE_REJECT ]
)
hbox = HBox.new(false, 5)
hbox.pack_start(Label.new("Type:"), false)
hbox.pack_start(type_input = ComboBox.new(true))
default_active = 0
types = parent ? ALL_TYPES : CONTAINER_TYPES
types.each_with_index do |t, i|
type_input.append_text(t)
if t == default_type
default_active = i
end
end
type_input.active = default_active
dialog.vbox.pack_start(hbox, false)
type_input.signal_connect(:changed) do
configure_value(value_input, types[type_input.active])
end
hbox = HBox.new(false, 5)
hbox.pack_start(Label.new("Value:"), false)
hbox.pack_start(value_input = Entry.new)
value_input.width_chars = 60
value_input.text = value_text if value_text
configure_value(value_input, types[type_input.active])
dialog.vbox.pack_start(hbox, false)
dialog.signal_connect(:'key-press-event', &DEFAULT_DIALOG_KEY_PRESS_HANDLER)
dialog.show_all
self.focus = dialog
dialog.run do |response|
if response == Dialog::RESPONSE_ACCEPT
type = types[type_input.active]
@content = case type
when 'Numeric'
if (t = value_input.text) == 'Infinity'
1 / 0.0
else
Integer(t) rescue Float(t) rescue 0
end
else
value_input.text
end.to_s
return type, @content
end
end
return
ensure
dialog.destroy if dialog
end
# Ask for an order criteria for sorting, using _x_ for the element in
# question. Returns the order criterium, and true/false for reverse
# sorting.
def ask_for_order
dialog = Dialog.new(
"Give an order criterium for 'x'.",
nil, nil,
[ Stock::OK, Dialog::RESPONSE_ACCEPT ],
[ Stock::CANCEL, Dialog::RESPONSE_REJECT ]
)
hbox = HBox.new(false, 5)
hbox.pack_start(Label.new("Order:"), false)
hbox.pack_start(order_input = Entry.new)
order_input.text = @order || 'x'
order_input.width_chars = 60
hbox.pack_start(reverse_checkbox = CheckButton.new('Reverse'), false)
dialog.vbox.pack_start(hbox, false)
dialog.signal_connect(:'key-press-event', &DEFAULT_DIALOG_KEY_PRESS_HANDLER)
dialog.show_all
self.focus = dialog
dialog.run do |response|
if response == Dialog::RESPONSE_ACCEPT
return @order = order_input.text, reverse_checkbox.active?
end
end
return
ensure
dialog.destroy if dialog
end
# Ask for a find term to search for in the tree. Returns the term as a
# string.
def ask_for_find_term(search = nil)
dialog = Dialog.new(
"Find a node matching regex in tree.",
nil, nil,
[ Stock::OK, Dialog::RESPONSE_ACCEPT ],
[ Stock::CANCEL, Dialog::RESPONSE_REJECT ]
)
hbox = HBox.new(false, 5)
hbox.pack_start(Label.new("Regex:"), false)
hbox.pack_start(regex_input = Entry.new)
hbox.pack_start(icase_checkbox = CheckButton.new('Icase'), false)
regex_input.width_chars = 60
if search
regex_input.text = search.source
icase_checkbox.active = search.casefold?
end
dialog.vbox.pack_start(hbox, false)
dialog.signal_connect(:'key-press-event', &DEFAULT_DIALOG_KEY_PRESS_HANDLER)
dialog.show_all
self.focus = dialog
dialog.run do |response|
if response == Dialog::RESPONSE_ACCEPT
begin
return Regexp.new(regex_input.text, icase_checkbox.active? ? Regexp::IGNORECASE : 0)
rescue => e
Editor.error_dialog(self, "Evaluation of regex /#{regex_input.text}/ failed: #{e}!")
return
end
end
end
return
ensure
dialog.destroy if dialog
end
# Expand or collapse row pointed to by _iter_ according
# to the #expanded attribute.
def expand_collapse(iter)
if expanded
expand_row(iter.path, true)
else
collapse_row(iter.path)
end
end
end
# The editor main window
class MainWindow < Gtk::Window
include Gtk
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | true |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.3/lib/json/pure/parser.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.3/lib/json/pure/parser.rb | require 'strscan'
module JSON
module Pure
# This class implements the JSON parser that is used to parse a JSON string
# into a Ruby data structure.
class Parser < StringScanner
STRING = /" ((?:[^\x0-\x1f"\\] |
# escaped special characters:
\\["\\\/bfnrt] |
\\u[0-9a-fA-F]{4} |
# match all but escaped special characters:
\\[\x20-\x21\x23-\x2e\x30-\x5b\x5d-\x61\x63-\x65\x67-\x6d\x6f-\x71\x73\x75-\xff])*)
"/nx
INTEGER = /(-?0|-?[1-9]\d*)/
FLOAT = /(-?
(?:0|[1-9]\d*)
(?:
\.\d+(?i:e[+-]?\d+) |
\.\d+ |
(?i:e[+-]?\d+)
)
)/x
NAN = /NaN/
INFINITY = /Infinity/
MINUS_INFINITY = /-Infinity/
OBJECT_OPEN = /\{/
OBJECT_CLOSE = /\}/
ARRAY_OPEN = /\[/
ARRAY_CLOSE = /\]/
PAIR_DELIMITER = /:/
COLLECTION_DELIMITER = /,/
TRUE = /true/
FALSE = /false/
NULL = /null/
IGNORE = %r(
(?:
//[^\n\r]*[\n\r]| # line comments
/\* # c-style comments
(?:
[^*/]| # normal chars
/[^*]| # slashes that do not start a nested comment
\*[^/]| # asterisks that do not end this comment
/(?=\*/) # single slash before this comment's end
)*
\*/ # the End of this comment
|[ \t\r\n]+ # whitespaces: space, horicontal tab, lf, cr
)+
)mx
UNPARSED = Object.new
# Creates a new JSON::Pure::Parser instance for the string _source_.
#
# It will be configured by the _opts_ hash. _opts_ can have the following
# keys:
# * *max_nesting*: The maximum depth of nesting allowed in the parsed data
# structures. Disable depth checking with :max_nesting => false|nil|0,
# it defaults to 19.
# * *allow_nan*: If set to true, allow NaN, Infinity and -Infinity in
# defiance of RFC 4627 to be parsed by the Parser. This option defaults
# to false.
# * *symbolize_names*: If set to true, returns symbols for the names
# (keys) in a JSON object. Otherwise strings are returned, which is also
# the default.
# * *create_additions*: If set to false, the Parser doesn't create
# additions even if a matchin class and create_id was found. This option
# defaults to true.
# * *object_class*: Defaults to Hash
# * *array_class*: Defaults to Array
def initialize(source, opts = {})
if defined?(::Encoding)
if source.encoding == Encoding::ASCII_8BIT
b = source[0, 4].bytes.to_a
source = case
when b.size >= 4 && b[0] == 0 && b[1] == 0 && b[2] == 0
source.dup.force_encoding(Encoding::UTF_32BE).encode!(Encoding::UTF_8)
when b.size >= 4 && b[0] == 0 && b[2] == 0
source.dup.force_encoding(Encoding::UTF_16BE).encode!(Encoding::UTF_8)
when b.size >= 4 && b[1] == 0 && b[2] == 0 && b[3] == 0
source.dup.force_encoding(Encoding::UTF_32LE).encode!(Encoding::UTF_8)
when b.size >= 4 && b[1] == 0 && b[3] == 0
source.dup.force_encoding(Encoding::UTF_16LE).encode!(Encoding::UTF_8)
else
source.dup
end
else
source = source.encode(Encoding::UTF_8)
end
source.force_encoding(Encoding::ASCII_8BIT)
else
b = source
source = case
when b.size >= 4 && b[0] == 0 && b[1] == 0 && b[2] == 0
JSON.iconv('utf-8', 'utf-32be', b)
when b.size >= 4 && b[0] == 0 && b[2] == 0
JSON.iconv('utf-8', 'utf-16be', b)
when b.size >= 4 && b[1] == 0 && b[2] == 0 && b[3] == 0
JSON.iconv('utf-8', 'utf-32le', b)
when b.size >= 4 && b[1] == 0 && b[3] == 0
JSON.iconv('utf-8', 'utf-16le', b)
else
b
end
end
super source
if !opts.key?(:max_nesting) # defaults to 19
@max_nesting = 19
elsif opts[:max_nesting]
@max_nesting = opts[:max_nesting]
else
@max_nesting = 0
end
@allow_nan = !!opts[:allow_nan]
@symbolize_names = !!opts[:symbolize_names]
ca = true
ca = opts[:create_additions] if opts.key?(:create_additions)
@create_id = ca ? JSON.create_id : nil
@object_class = opts[:object_class] || Hash
@array_class = opts[:array_class] || Array
end
alias source string
# Parses the current JSON string _source_ and returns the complete data
# structure as a result.
def parse
reset
obj = nil
until eos?
case
when scan(OBJECT_OPEN)
obj and raise ParserError, "source '#{peek(20)}' not in JSON!"
@current_nesting = 1
obj = parse_object
when scan(ARRAY_OPEN)
obj and raise ParserError, "source '#{peek(20)}' not in JSON!"
@current_nesting = 1
obj = parse_array
when skip(IGNORE)
;
else
raise ParserError, "source '#{peek(20)}' not in JSON!"
end
end
obj or raise ParserError, "source did not contain any JSON!"
obj
end
private
# Unescape characters in strings.
UNESCAPE_MAP = Hash.new { |h, k| h[k] = k.chr }
UNESCAPE_MAP.update({
?" => '"',
?\\ => '\\',
?/ => '/',
?b => "\b",
?f => "\f",
?n => "\n",
?r => "\r",
?t => "\t",
?u => nil,
})
def parse_string
if scan(STRING)
return '' if self[1].empty?
string = self[1].gsub(%r((?:\\[\\bfnrt"/]|(?:\\u(?:[A-Fa-f\d]{4}))+|\\[\x20-\xff]))n) do |c|
if u = UNESCAPE_MAP[$&[1]]
u
else # \uXXXX
bytes = ''
i = 0
while c[6 * i] == ?\\ && c[6 * i + 1] == ?u
bytes << c[6 * i + 2, 2].to_i(16) << c[6 * i + 4, 2].to_i(16)
i += 1
end
JSON::UTF16toUTF8.iconv(bytes)
end
end
if string.respond_to?(:force_encoding)
string.force_encoding(Encoding::UTF_8)
end
string
else
UNPARSED
end
rescue Iconv::Failure => e
raise GeneratorError, "Caught #{e.class}: #{e}"
end
def parse_value
case
when scan(FLOAT)
Float(self[1])
when scan(INTEGER)
Integer(self[1])
when scan(TRUE)
true
when scan(FALSE)
false
when scan(NULL)
nil
when (string = parse_string) != UNPARSED
string
when scan(ARRAY_OPEN)
@current_nesting += 1
ary = parse_array
@current_nesting -= 1
ary
when scan(OBJECT_OPEN)
@current_nesting += 1
obj = parse_object
@current_nesting -= 1
obj
when @allow_nan && scan(NAN)
NaN
when @allow_nan && scan(INFINITY)
Infinity
when @allow_nan && scan(MINUS_INFINITY)
MinusInfinity
else
UNPARSED
end
end
def parse_array
raise NestingError, "nesting of #@current_nesting is too deep" if
@max_nesting.nonzero? && @current_nesting > @max_nesting
result = @array_class.new
delim = false
until eos?
case
when (value = parse_value) != UNPARSED
delim = false
result << value
skip(IGNORE)
if scan(COLLECTION_DELIMITER)
delim = true
elsif match?(ARRAY_CLOSE)
;
else
raise ParserError, "expected ',' or ']' in array at '#{peek(20)}'!"
end
when scan(ARRAY_CLOSE)
if delim
raise ParserError, "expected next element in array at '#{peek(20)}'!"
end
break
when skip(IGNORE)
;
else
raise ParserError, "unexpected token in array at '#{peek(20)}'!"
end
end
result
end
def parse_object
raise NestingError, "nesting of #@current_nesting is too deep" if
@max_nesting.nonzero? && @current_nesting > @max_nesting
result = @object_class.new
delim = false
until eos?
case
when (string = parse_string) != UNPARSED
skip(IGNORE)
unless scan(PAIR_DELIMITER)
raise ParserError, "expected ':' in object at '#{peek(20)}'!"
end
skip(IGNORE)
unless (value = parse_value).equal? UNPARSED
result[@symbolize_names ? string.to_sym : string] = value
delim = false
skip(IGNORE)
if scan(COLLECTION_DELIMITER)
delim = true
elsif match?(OBJECT_CLOSE)
;
else
raise ParserError, "expected ',' or '}' in object at '#{peek(20)}'!"
end
else
raise ParserError, "expected value in object at '#{peek(20)}'!"
end
when scan(OBJECT_CLOSE)
if delim
raise ParserError, "expected next name, value pair in object at '#{peek(20)}'!"
end
if @create_id and klassname = result[@create_id]
klass = JSON.deep_const_get klassname
break unless klass and klass.json_creatable?
result = klass.json_create(result)
end
break
when skip(IGNORE)
;
else
raise ParserError, "unexpected token in object at '#{peek(20)}'!"
end
end
result
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.3/lib/json/pure/generator.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.3/lib/json/pure/generator.rb | module JSON
MAP = {
"\x0" => '\u0000',
"\x1" => '\u0001',
"\x2" => '\u0002',
"\x3" => '\u0003',
"\x4" => '\u0004',
"\x5" => '\u0005',
"\x6" => '\u0006',
"\x7" => '\u0007',
"\b" => '\b',
"\t" => '\t',
"\n" => '\n',
"\xb" => '\u000b',
"\f" => '\f',
"\r" => '\r',
"\xe" => '\u000e',
"\xf" => '\u000f',
"\x10" => '\u0010',
"\x11" => '\u0011',
"\x12" => '\u0012',
"\x13" => '\u0013',
"\x14" => '\u0014',
"\x15" => '\u0015',
"\x16" => '\u0016',
"\x17" => '\u0017',
"\x18" => '\u0018',
"\x19" => '\u0019',
"\x1a" => '\u001a',
"\x1b" => '\u001b',
"\x1c" => '\u001c',
"\x1d" => '\u001d',
"\x1e" => '\u001e',
"\x1f" => '\u001f',
'"' => '\"',
'\\' => '\\\\',
} # :nodoc:
# Convert a UTF8 encoded Ruby string _string_ to a JSON string, encoded with
# UTF16 big endian characters as \u????, and return it.
if defined?(::Encoding)
def utf8_to_json(string) # :nodoc:
string = string.dup
string << '' # XXX workaround: avoid buffer sharing
string.force_encoding(::Encoding::ASCII_8BIT)
string.gsub!(/["\\\x0-\x1f]/) { MAP[$&] }
string.force_encoding(::Encoding::UTF_8)
string
end
def utf8_to_json_ascii(string) # :nodoc:
string = string.dup
string << '' # XXX workaround: avoid buffer sharing
string.force_encoding(::Encoding::ASCII_8BIT)
string.gsub!(/["\\\x0-\x1f]/) { MAP[$&] }
string.gsub!(/(
(?:
[\xc2-\xdf][\x80-\xbf] |
[\xe0-\xef][\x80-\xbf]{2} |
[\xf0-\xf4][\x80-\xbf]{3}
)+ |
[\x80-\xc1\xf5-\xff] # invalid
)/nx) { |c|
c.size == 1 and raise GeneratorError, "invalid utf8 byte: '#{c}'"
s = JSON::UTF8toUTF16.iconv(c).unpack('H*')[0]
s.gsub!(/.{4}/n, '\\\\u\&')
}
string.force_encoding(::Encoding::UTF_8)
string
rescue Iconv::Failure => e
raise GeneratorError, "Caught #{e.class}: #{e}"
end
else
def utf8_to_json(string) # :nodoc:
string.gsub(/["\\\x0-\x1f]/) { MAP[$&] }
end
def utf8_to_json_ascii(string) # :nodoc:
string = string.gsub(/["\\\x0-\x1f]/) { MAP[$&] }
string.gsub!(/(
(?:
[\xc2-\xdf][\x80-\xbf] |
[\xe0-\xef][\x80-\xbf]{2} |
[\xf0-\xf4][\x80-\xbf]{3}
)+ |
[\x80-\xc1\xf5-\xff] # invalid
)/nx) { |c|
c.size == 1 and raise GeneratorError, "invalid utf8 byte: '#{c}'"
s = JSON::UTF8toUTF16.iconv(c).unpack('H*')[0]
s.gsub!(/.{4}/n, '\\\\u\&')
}
string
rescue Iconv::Failure => e
raise GeneratorError, "Caught #{e.class}: #{e}"
end
end
module_function :utf8_to_json, :utf8_to_json_ascii
module Pure
module Generator
# This class is used to create State instances, that are use to hold data
# while generating a JSON text from a a Ruby data structure.
class State
# Creates a State object from _opts_, which ought to be Hash to create
# a new State instance configured by _opts_, something else to create
# an unconfigured instance. If _opts_ is a State object, it is just
# returned.
def self.from_state(opts)
case opts
when self
opts
when Hash
new(opts)
else
SAFE_STATE_PROTOTYPE
end
end
# Instantiates a new State object, configured by _opts_.
#
# _opts_ can have the following keys:
#
# * *indent*: a string used to indent levels (default: ''),
# * *space*: a string that is put after, a : or , delimiter (default: ''),
# * *space_before*: a string that is put before a : pair delimiter (default: ''),
# * *object_nl*: a string that is put at the end of a JSON object (default: ''),
# * *array_nl*: a string that is put at the end of a JSON array (default: ''),
# * *check_circular*: is deprecated now, use the :max_nesting option instead,
# * *max_nesting*: sets the maximum level of data structure nesting in
# the generated JSON, max_nesting = 0 if no maximum should be checked.
# * *allow_nan*: true if NaN, Infinity, and -Infinity should be
# generated, otherwise an exception is thrown, if these values are
# encountered. This options defaults to false.
def initialize(opts = {})
@indent = ''
@space = ''
@space_before = ''
@object_nl = ''
@array_nl = ''
@allow_nan = false
@ascii_only = false
configure opts
end
# This string is used to indent levels in the JSON text.
attr_accessor :indent
# This string is used to insert a space between the tokens in a JSON
# string.
attr_accessor :space
# This string is used to insert a space before the ':' in JSON objects.
attr_accessor :space_before
# This string is put at the end of a line that holds a JSON object (or
# Hash).
attr_accessor :object_nl
# This string is put at the end of a line that holds a JSON array.
attr_accessor :array_nl
# This integer returns the maximum level of data structure nesting in
# the generated JSON, max_nesting = 0 if no maximum is checked.
attr_accessor :max_nesting
def check_max_nesting(depth) # :nodoc:
return if @max_nesting.zero?
current_nesting = depth + 1
current_nesting > @max_nesting and
raise NestingError, "nesting of #{current_nesting} is too deep"
end
# Returns true, if circular data structures are checked,
# otherwise returns false.
def check_circular?
!@max_nesting.zero?
end
# Returns true if NaN, Infinity, and -Infinity should be considered as
# valid JSON and output.
def allow_nan?
@allow_nan
end
def ascii_only?
@ascii_only
end
# Configure this State instance with the Hash _opts_, and return
# itself.
def configure(opts)
@indent = opts[:indent] if opts.key?(:indent)
@space = opts[:space] if opts.key?(:space)
@space_before = opts[:space_before] if opts.key?(:space_before)
@object_nl = opts[:object_nl] if opts.key?(:object_nl)
@array_nl = opts[:array_nl] if opts.key?(:array_nl)
@allow_nan = !!opts[:allow_nan] if opts.key?(:allow_nan)
@ascii_only = opts[:ascii_only] if opts.key?(:ascii_only)
if !opts.key?(:max_nesting) # defaults to 19
@max_nesting = 19
elsif opts[:max_nesting]
@max_nesting = opts[:max_nesting]
else
@max_nesting = 0
end
self
end
# Returns the configuration instance variables as a hash, that can be
# passed to the configure method.
def to_h
result = {}
for iv in %w[indent space space_before object_nl array_nl allow_nan max_nesting]
result[iv.intern] = instance_variable_get("@#{iv}")
end
result
end
# Generates a valid JSON document from object +obj+ and returns the
# result. If no valid JSON document can be created this method raises a
# GeneratorError exception.
def generate(obj)
result = obj.to_json(self)
if result !~ /\A\s*(?:\[.*\]|\{.*\})\s*\Z/m
raise GeneratorError, "only generation of JSON objects or arrays allowed"
end
result
end
# Return the value returned by method +name+.
def [](name)
__send__ name
end
end
module GeneratorMethods
module Object
# Converts this object to a string (calling #to_s), converts
# it to a JSON string, and returns the result. This is a fallback, if no
# special method #to_json was defined for some object.
def to_json(*) to_s.to_json end
end
module Hash
# Returns a JSON string containing a JSON object, that is unparsed from
# this Hash instance.
# _state_ is a JSON::State object, that can also be used to configure the
# produced JSON string output further.
# _depth_ is used to find out nesting depth, to indent accordingly.
def to_json(state = nil, depth = 0, *)
if state
state = State.from_state(state)
state.check_max_nesting(depth)
end
json_transform(state, depth)
end
private
def json_shift(state, depth)
state and not state.object_nl.empty? or return ''
state.indent * depth
end
def json_transform(state, depth)
delim = ','
if state
delim << state.object_nl
result = '{'
result << state.object_nl
depth += 1
first = true
indent = state && !state.object_nl.empty?
each { |key,value|
result << delim unless first
result << state.indent * depth if indent
result << key.to_s.to_json(state, depth)
result << state.space_before
result << ':'
result << state.space
result << value.to_json(state, depth)
first = false
}
depth -= 1
result << state.object_nl
result << state.indent * depth if indent if indent
result << '}'
else
result = '{'
result << map { |key,value|
key.to_s.to_json << ':' << value.to_json
}.join(delim)
result << '}'
end
result
end
end
module Array
# Returns a JSON string containing a JSON array, that is unparsed from
# this Array instance.
# _state_ is a JSON::State object, that can also be used to configure the
# produced JSON string output further.
# _depth_ is used to find out nesting depth, to indent accordingly.
def to_json(state = nil, depth = 0, *)
if state
state = State.from_state(state)
state.check_max_nesting(depth)
end
json_transform(state, depth)
end
private
def json_transform(state, depth)
delim = ','
if state
delim << state.array_nl
result = '['
result << state.array_nl
depth += 1
first = true
indent = state && !state.array_nl.empty?
each { |value|
result << delim unless first
result << state.indent * depth if indent
result << value.to_json(state, depth)
first = false
}
depth -= 1
result << state.array_nl
result << state.indent * depth if indent
result << ']'
else
'[' << map { |value| value.to_json }.join(delim) << ']'
end
end
end
module Integer
# Returns a JSON string representation for this Integer number.
def to_json(*) to_s end
end
module Float
# Returns a JSON string representation for this Float number.
def to_json(state = nil, *)
case
when infinite?
if state && state.allow_nan?
to_s
else
raise GeneratorError, "#{self} not allowed in JSON"
end
when nan?
if state && state.allow_nan?
to_s
else
raise GeneratorError, "#{self} not allowed in JSON"
end
else
to_s
end
end
end
module String
if defined?(::Encoding)
# This string should be encoded with UTF-8 A call to this method
# returns a JSON string encoded with UTF16 big endian characters as
# \u????.
def to_json(*args)
state, = *args
state ||= State.from_state(state)
if encoding == ::Encoding::UTF_8
string = self
else
string = encode(::Encoding::UTF_8)
end
if state.ascii_only?
'"' << JSON.utf8_to_json_ascii(string) << '"'
else
'"' << JSON.utf8_to_json(string) << '"'
end
end
else
# This string should be encoded with UTF-8 A call to this method
# returns a JSON string encoded with UTF16 big endian characters as
# \u????.
def to_json(*args)
state, = *args
state ||= State.from_state(state)
if state.ascii_only?
'"' << JSON.utf8_to_json_ascii(self) << '"'
else
'"' << JSON.utf8_to_json(self) << '"'
end
end
end
# Module that holds the extinding methods if, the String module is
# included.
module Extend
# Raw Strings are JSON Objects (the raw bytes are stored in an
# array for the key "raw"). The Ruby String can be created by this
# module method.
def json_create(o)
o['raw'].pack('C*')
end
end
# Extends _modul_ with the String::Extend module.
def self.included(modul)
modul.extend Extend
end
# This method creates a raw object hash, that can be nested into
# other data structures and will be unparsed as a raw string. This
# method should be used, if you want to convert raw strings to JSON
# instead of UTF-8 strings, e. g. binary data.
def to_json_raw_object
{
JSON.create_id => self.class.name,
'raw' => self.unpack('C*'),
}
end
# This method creates a JSON text from the result of
# a call to to_json_raw_object of this String.
def to_json_raw(*args)
to_json_raw_object.to_json(*args)
end
end
module TrueClass
# Returns a JSON string for true: 'true'.
def to_json(*) 'true' end
end
module FalseClass
# Returns a JSON string for false: 'false'.
def to_json(*) 'false' end
end
module NilClass
# Returns a JSON string for nil: 'null'.
def to_json(*) 'null' end
end
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.3/lib/json/add/core.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.3/lib/json/add/core.rb | # This file contains implementations of ruby core's custom objects for
# serialisation/deserialisation.
unless Object.const_defined?(:JSON) and ::JSON.const_defined?(:JSON_LOADED) and
::JSON::JSON_LOADED
require 'json'
end
require 'date'
class Symbol
def to_json(*a)
{
JSON.create_id => self.class.name,
's' => to_s,
}.to_json(*a)
end
def self.json_create(o)
o['s'].to_sym
end
end
class Time
def self.json_create(object)
if usec = object.delete('u') # used to be tv_usec -> tv_nsec
object['n'] = usec * 1000
end
if respond_to?(:tv_nsec)
at(*object.values_at('s', 'n'))
else
at(object['s'], object['n'] / 1000)
end
end
def to_json(*args)
{
JSON.create_id => self.class.name,
's' => tv_sec,
'n' => respond_to?(:tv_nsec) ? tv_nsec : tv_usec * 1000
}.to_json(*args)
end
end
class Date
def self.json_create(object)
civil(*object.values_at('y', 'm', 'd', 'sg'))
end
alias start sg unless method_defined?(:start)
def to_json(*args)
{
JSON.create_id => self.class.name,
'y' => year,
'm' => month,
'd' => day,
'sg' => start,
}.to_json(*args)
end
end
class DateTime
def self.json_create(object)
args = object.values_at('y', 'm', 'd', 'H', 'M', 'S')
of_a, of_b = object['of'].split('/')
if of_b and of_b != '0'
args << Rational(of_a.to_i, of_b.to_i)
else
args << of_a
end
args << object['sg']
civil(*args)
end
alias start sg unless method_defined?(:start)
def to_json(*args)
{
JSON.create_id => self.class.name,
'y' => year,
'm' => month,
'd' => day,
'H' => hour,
'M' => min,
'S' => sec,
'of' => offset.to_s,
'sg' => start,
}.to_json(*args)
end
end
class Range
def self.json_create(object)
new(*object['a'])
end
def to_json(*args)
{
JSON.create_id => self.class.name,
'a' => [ first, last, exclude_end? ]
}.to_json(*args)
end
end
class Struct
def self.json_create(object)
new(*object['v'])
end
def to_json(*args)
klass = self.class.name
klass.to_s.empty? and raise JSON::JSONError, "Only named structs are supported!"
{
JSON.create_id => klass,
'v' => values,
}.to_json(*args)
end
end
class Exception
def self.json_create(object)
result = new(object['m'])
result.set_backtrace object['b']
result
end
def to_json(*args)
{
JSON.create_id => self.class.name,
'm' => message,
'b' => backtrace,
}.to_json(*args)
end
end
class Regexp
def self.json_create(object)
new(object['s'], object['o'])
end
def to_json(*)
{
JSON.create_id => self.class.name,
'o' => options,
's' => source,
}.to_json
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.3/lib/json/add/rails.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.3/lib/json/add/rails.rb | # This file contains implementations of rails custom objects for
# serialisation/deserialisation.
unless Object.const_defined?(:JSON) and ::JSON.const_defined?(:JSON_LOADED) and
::JSON::JSON_LOADED
require 'json'
end
class Object
def self.json_create(object)
obj = new
for key, value in object
next if key == JSON.create_id
instance_variable_set "@#{key}", value
end
obj
end
def to_json(*a)
result = {
JSON.create_id => self.class.name
}
instance_variables.inject(result) do |r, name|
r[name[1..-1]] = instance_variable_get name
r
end
result.to_json(*a)
end
end
class Symbol
def to_json(*a)
to_s.to_json(*a)
end
end
module Enumerable
def to_json(*a)
to_a.to_json(*a)
end
end
# class Regexp
# def to_json(*)
# inspect
# end
# end
#
# The above rails definition has some problems:
#
# 1. { 'foo' => /bar/ }.to_json # => "{foo: /bar/}"
# This isn't valid JSON, because the regular expression syntax is not
# defined in RFC 4627. (And unquoted strings are disallowed there, too.)
# Though it is valid Javascript.
#
# 2. { 'foo' => /bar/mix }.to_json # => "{foo: /bar/mix}"
# This isn't even valid Javascript.
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbcsqlite3-adapter-0.9.7-java/lib/active_record/connection_adapters/jdbcsqlite3_adapter.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbcsqlite3-adapter-0.9.7-java/lib/active_record/connection_adapters/jdbcsqlite3_adapter.rb | tried_gem = false
begin
require "jdbc_adapter"
rescue LoadError
raise if tried_gem
require 'rubygems'
gem "activerecord-jdbc-adapter"
tried_gem = true
retry
end
tried_gem = false
begin
require "jdbc/sqlite3"
rescue LoadError
raise if tried_gem
require 'rubygems'
gem "jdbc-sqlite3"
tried_gem = true
retry
end
require 'active_record/connection_adapters/jdbc_adapter'
module ActiveRecord
class Base
class << self
alias_method :jdbcsqlite3_connection, :sqlite3_connection
end
end
end | ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jdbc-sqlite3-3.6.3.054/lib/jdbc/sqlite3.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jdbc-sqlite3-3.6.3.054/lib/jdbc/sqlite3.rb | module Jdbc
module SQLite3
VERSION = "3.6.3.054" # Based on SQLite 3.6.3
end
end
if RUBY_PLATFORM =~ /java/
require "sqlitejdbc-#{Jdbc::SQLite3::VERSION}.jar"
else
warn "jdbc-SQLite3 is only for use with JRuby"
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/test_all.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/test_all.rb | Dir.glob("test/test_*.rb").sort.reject{|t| t =~ /test_all/}.each {|t| require t }
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/test_x509store.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/test_x509store.rb | begin
require "openssl"
rescue LoadError
end
require "test/unit"
require "tempfile"
class TestX509Store < Test::Unit::TestCase
def setup
@store = OpenSSL::X509::Store.new
end
def teardown
end
def test_ns_cert_type
f = Tempfile.new("globalsign-root.pem")
f << GLOBALSIGN_ROOT_CA
f.close
@store.add_file(f.path)
f.unlink
# CAUTION !
#
# sgc is an issuing CA certificate so we should not verify it for the
# purpose 'PURPOSE_SSL_SERVER'. It's not a SSL server certificate.
# We're just checking the code for 'PURPOSE_SSL_SERVER'.
# jruby-openssl/0.5.2 raises the following exception around ASN.1
# nsCertType handling.
# Purpose.java:344:in `call': java.lang.ClassCastException: org.bouncycastle.asn1.DEROctetString cannot be cast to org.bouncycastle.asn1.DERBitString
sgc = OpenSSL::X509::Certificate.new(GLOBALSIGN_ORGANIZATION_VALIDATION_CA)
@store.purpose = OpenSSL::X509::PURPOSE_SSL_SERVER
assert_nothing_raised do
@store.verify(sgc) # => should be false
end
end
def test_purpose_ssl_client
@store.add_file("test/fixture/purpose/cacert.pem")
cert = OpenSSL::X509::Certificate.new(File.read("test/fixture/purpose/sslclient.pem"))
@store.purpose = OpenSSL::X509::PURPOSE_SSL_CLIENT
assert_equal(true, @store.verify(cert))
@store.purpose = OpenSSL::X509::PURPOSE_SSL_SERVER
assert_equal(false, @store.verify(cert))
@store.purpose = OpenSSL::X509::PURPOSE_SSL_CLIENT
assert_equal(true, @store.verify(cert))
end
def test_purpose_ssl_server
@store.add_file("test/fixture/purpose/cacert.pem")
cert = OpenSSL::X509::Certificate.new(File.read("test/fixture/purpose/sslserver.pem"))
@store.purpose = OpenSSL::X509::PURPOSE_SSL_SERVER
assert_equal(true, @store.verify(cert))
@store.purpose = OpenSSL::X509::PURPOSE_SSL_CLIENT
assert_equal(false, @store.verify(cert))
@store.purpose = OpenSSL::X509::PURPOSE_SSL_SERVER
assert_equal(true, @store.verify(cert))
end
def test_add_file_multiple
f = Tempfile.new("globalsign-root.pem")
f << GLOBALSIGN_ROOT_CA
f << "junk junk\n"
f << "junk junk\n"
f << "junk junk\n"
f << File.read("test/fixture/purpose/cacert.pem")
f.close
@store.add_file(f.path)
f.unlink
cert = OpenSSL::X509::Certificate.new(File.read("test/fixture/purpose/sslserver.pem"))
@store.purpose = OpenSSL::X509::PURPOSE_SSL_SERVER
assert_equal(true, @store.verify(cert))
@store.purpose = OpenSSL::X509::PURPOSE_SSL_CLIENT
assert_equal(false, @store.verify(cert))
@store.purpose = OpenSSL::X509::PURPOSE_SSL_SERVER
assert_equal(true, @store.verify(cert))
end
# jruby-openssl/0.6 raises "can't store certificate" because of duplicated
# subject. ruby-openssl just ignores the second certificate.
def test_add_file_JRUBY_4409
assert_nothing_raised do
@store.add_file("test/fixture/ca-bundle.crt")
end
end
def test_set_default_paths
@store.purpose = OpenSSL::X509::PURPOSE_SSL_SERVER
cert = OpenSSL::X509::Certificate.new(File.read("test/fixture/purpose/sslserver.pem"))
assert_equal(false, @store.verify(cert))
begin
backup = ENV['SSL_CERT_DIR']
ENV['SSL_CERT_DIR'] = 'test/fixture/purpose/'
@store.set_default_paths
assert_equal(true, @store.verify(cert))
ensure
ENV['SSL_CERT_DIR'] = backup if backup
end
end
GLOBALSIGN_ROOT_CA = <<__EOS__
-----BEGIN CERTIFICATE-----
MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkG
A1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jv
b3QgQ0ExGzAZBgNVBAMTEkdsb2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAw
MDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9i
YWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYDVQQDExJHbG9iYWxT
aWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDaDuaZ
jc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavp
xy0Sy6scTHAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp
1Wrjsok6Vjk4bwY8iGlbKk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdG
snUOhugZitVtbNV4FpWi6cgKOOvyJBNPc1STE4U6G7weNLWLBYy5d4ux2x8gkasJ
U26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrXgzT/LCrBbBlDSgeF59N8
9iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8E
BTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0B
AQUFAAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOz
yj1hTdNGCbM+w6DjY1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE
38NflNUVyRRBnMRddWQVDf9VMOyGj/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymP
AbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhHhm4qxFYxldBniYUr+WymXUad
DKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveCX4XSQRjbgbME
HMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==
-----END CERTIFICATE-----
__EOS__
GLOBALSIGN_ORGANIZATION_VALIDATION_CA = <<__EOS__
-----BEGIN CERTIFICATE-----
MIIEZzCCA0+gAwIBAgILBAAAAAABHkSl9SowDQYJKoZIhvcNAQEFBQAwVzELMAkG
A1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jv
b3QgQ0ExGzAZBgNVBAMTEkdsb2JhbFNpZ24gUm9vdCBDQTAeFw0wNzA0MTExMjAw
MDBaFw0xNzA0MTExMjAwMDBaMGoxIzAhBgNVBAsTGk9yZ2FuaXphdGlvbiBWYWxp
ZGF0aW9uIENBMRMwEQYDVQQKEwpHbG9iYWxTaWduMS4wLAYDVQQDEyVHbG9iYWxT
aWduIE9yZ2FuaXphdGlvbiBWYWxpZGF0aW9uIENBMIIBIjANBgkqhkiG9w0BAQEF
AAOCAQ8AMIIBCgKCAQEAoS/EvM6HA+lnwYnI5ZP8fbStnvZjTmronCxziaIB9I8h
+P0lnVgWbYb27klXdX516iIRfj37x0JB3PzFDJFVgHvrZDMdm/nKOOmrxiVDUSVA
9OR+GFVqqY8QOkAe1leD738vNC8t0vZTwhkNt+3JgfVGLLQjQl6dEwN17Opq/Fd8
yTaXO5jcExPs7EH6XTTquZPnEBZlzJyS/fXFnT5KuQn85F8eaV9N9FZyRLEdIwPI
NvZliMi/ORZFjh4mbFEWxSoAOMWkE2mVfasBO6jEFLSA2qwaRCDV/qkGexQnr+Aw
Id2Q9KnVIxkuHgPmwd+VKeTBlEPdPpCqy0vJvorTOQIDAQABo4IBHzCCARswDgYD
VR0PAQH/BAQDAgEGMBIGA1UdEwEB/wQIMAYBAf8CAQAwHQYDVR0OBBYEFH1tKuxm
q6dRNqsCafFwj8RZC5ofMEsGA1UdIAREMEIwQAYJKwYBBAGgMgEUMDMwMQYIKwYB
BQUHAgEWJWh0dHA6Ly93d3cuZ2xvYmFsc2lnbi5uZXQvcmVwb3NpdG9yeS8wMwYD
VR0fBCwwKjAooCagJIYiaHR0cDovL2NybC5nbG9iYWxzaWduLm5ldC9yb290LmNy
bDARBglghkgBhvhCAQEEBAMCAgQwIAYDVR0lBBkwFwYKKwYBBAGCNwoDAwYJYIZI
AYb4QgQBMB8GA1UdIwQYMBaAFGB7ZhpFDZfKiVAvfQTNNKj//P1LMA0GCSqGSIb3
DQEBBQUAA4IBAQB5R/wV10x53w96ns7UfEtjyYm1ez+ZEuicjJpJL+BOlUrtx7y+
8aLbjpMdunFUqkvZiSIkh8UEqKyCUqBS+LjhT6EnZmMhSjnnx8VOX7LWHRNtMOnO
16IcvCkKczxbI0n+1v/KsE/18meYwEcR+LdIppAJ1kK+6rG5U0LDnCDJ+6FbtVZt
h4HIYKzEuXInCo4eqLEuzTKieFewnPiVu0OOjDGGblMNxhIFukFuqDUwCRgdAmH/
/e413mrDO9BNS05QslY2DERd2hplKuaYVqljMy4E567o9I63stp9wMjirqYoL+PJ
c738B0E0t6pu7qfb0ZM87ZDsMpKI2cgjbHQh
-----END CERTIFICATE-----
__EOS__
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/test_pkcs7.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/test_pkcs7.rb | require 'openssl'
require "test/unit"
class TestPkcs7 < Test::Unit::TestCase
CERT_PEM = <<END
-----BEGIN CERTIFICATE-----
MIIC8zCCAdugAwIBAgIBATANBgkqhkiG9w0BAQQFADA9MRMwEQYKCZImiZPyLGQB
GRYDb3JnMRkwFwYKCZImiZPyLGQBGRYJcnVieS1sYW5nMQswCQYDVQQDDAJDQTAe
Fw0wOTA1MjMxNTAzNDNaFw0wOTA1MjMxNjAzNDNaMD0xEzARBgoJkiaJk/IsZAEZ
FgNvcmcxGTAXBgoJkiaJk/IsZAEZFglydWJ5LWxhbmcxCzAJBgNVBAMMAkNBMIIB
IjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuV9ht9J7k4NBs38jOXvvTKY9
gW8nLICSno5EETR1cuF7i4pNs9I1QJGAFAX0BEO4KbzXmuOvfCpD3CU+Slp1enen
fzq/t/e/1IRW0wkJUJUFQign4CtrkJL+P07yx18UjyPlBXb81ApEmAB5mrJVSrWm
qbjs07JbuS4QQGGXLc+Su96DkYKmSNVjBiLxVVSpyZfAY3hD37d60uG+X8xdW5v6
8JkRFIhdGlb6JL8fllf/A/blNwdJOhVr9mESHhwGjwfSeTDPfd8ZLE027E5lyAVX
9KZYcU00mOX+fdxOSnGqS/8JDRh0EPHDL15RcJjV2J6vZjPb0rOYGDoMcH+94wID
AQABMA0GCSqGSIb3DQEBBAUAA4IBAQB8UTw1agA9wdXxHMUACduYu6oNL7pdF0dr
w7a4QPJyj62h4+Umxvp13q0PBw0E+mSjhXMcqUhDLjrmMcvvNGhuh5Sdjbe3GI/M
3lCC9OwYYIzzul7omvGC3JEIGfzzdNnPPCPKEWp5X9f0MKLMR79qOf+sjHTjN2BY
SY3YGsEFxyTXDdqrlaYaOtTAdi/C+g1WxR8fkPLefymVwIFwvyc9/bnp7iBn7Hcw
mbxtLPbtQ9mURT0GHewZRTGJ1aiTq9Ag3xXME2FPF04eFRd3mclOQZNXKQ+LDxYf
k0X5FeZvsWf4srFxoVxlcDdJtHh91ZRpDDJYGQlsUm9CPTnO+e4E
-----END CERTIFICATE-----
END
def test_pkcs7_des3_key_generation_for_encrypt
# SunJCE requires DES/DES3 keybits = 21/168 for key generation.
# BC allows 24/192 keybits and treats it as 21/168.
msg = "Hello World"
password = "password"
cert = OpenSSL::X509::Certificate.new(CERT_PEM)
certs = [cert]
cipher = OpenSSL::Cipher.new("des-ede3-cbc")
cipher.encrypt
cipher.pkcs5_keyivgen(password)
p7 = OpenSSL::PKCS7.encrypt(certs, msg, cipher, OpenSSL::PKCS7::BINARY)
assert_equal(msg, p7.data)
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/test_cipher.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/test_cipher.rb | begin
require "openssl"
rescue LoadError
end
require "test/unit"
class TestCipher < Test::Unit::TestCase
def test_keylen
cipher = OpenSSL::Cipher::Cipher.new('DES-EDE3-CBC')
# must be 24 but it returns 16 on JRE6 without unlimited jurisdiction
# policy. it returns 24 on JRE6 with the unlimited policy.
assert_equal(24, cipher.key_len)
end
def test_encrypt_takes_parameter
enc = OpenSSL::Cipher::Cipher.new('DES-EDE3-CBC')
enc.encrypt("123")
data = enc.update("password")
data << enc.final
end
IV_TEMPLATE = "aaaabbbbccccddddeeeeffffgggghhhhiiiijjjjj"
KEY_TEMPLATE = "aaaabbbbccccddddeeeeffffgggghhhhiiiijjjjj"
# JRUBY-1692
def test_repeated_des
do_repeated_test(
"des-ede3-cbc",
"foobarbazboofarf",
":\022Q\211ex\370\332\374\274\214\356\301\260V\025",
"B\242\3531\003\362\3759\363s\203\374\240\030|\230"
)
end
# JRUBY-1692
def test_repeated_aes
do_repeated_test(
"aes-128-cbc",
"foobarbazboofarf",
"\342\260Y\344\306\227\004^\272|/\323<\016,\226",
"jqO\305/\211\216\b\373\300\274\bw\213]\310"
)
end
def test_rc2
do_repeated_test(
"RC2",
"foobarbazboofarf",
"\x18imZ\x9Ed\x15\xF3\xD6\xE6M\xCDf\xAA\xD3\xFE",
"\xEF\xF7\x16\x06\x93)-##\xB2~\xAD,\xAD\x82\xF5"
)
end
def test_rc4
do_repeated_test(
"RC4",
"foobarbazboofarf",
"/i|\257\336U\354\331\212\304E\021\246\351\235\303",
"\020\367\370\316\212\262\266e\242\333\263\305z\340\204\200"
)
end
def test_cast
do_repeated_test(
"cast-cbc",
"foobarbazboofarf",
"`m^\225\277\307\247m`{\f\020fl\ry",
"(\354\265\251,D\016\037\251\250V\207\367\214\276B"
)
end
# JRUBY-4326 (1)
def test_cipher_unsupported_algorithm
assert_raise(OpenSSL::Cipher::CipherError) do
cipher = OpenSSL::Cipher::Cipher.new('aes-xxxxxxx')
end
end
# JRUBY-4326 (2)
def test_cipher_unsupported_keylen
bits_128 = java.lang.String.new("0123456789ABCDEF").getBytes()
bits_256 = java.lang.String.new("0123456789ABCDEF0123456789ABCDEF").getBytes()
# AES128 is allowed
cipher = OpenSSL::Cipher::Cipher.new('aes-128-cbc')
cipher = OpenSSL::Cipher::Cipher.new('AES-128-CBC')
cipher = javax.crypto.Cipher.getInstance("AES/CBC/PKCS5Padding")
key_spec = javax.crypto.spec.SecretKeySpec.new(bits_128, "AES")
iv_spec = javax.crypto.spec.IvParameterSpec.new(bits_128)
assert_nothing_raised do
cipher.init(javax.crypto.Cipher::ENCRYPT_MODE, key_spec, iv_spec)
end
# check if AES256 is allowed or not in env policy
cipher = javax.crypto.Cipher.getInstance("AES/CBC/PKCS5Padding")
key_spec = javax.crypto.spec.SecretKeySpec.new(bits_256, "AES")
allowed = false
begin
cipher.init(javax.crypto.Cipher::ENCRYPT_MODE, key_spec, iv_spec)
allowed = true
rescue
end
# jruby-openssl should raise as well?
# CRuby's openssl raises exception at initialization time.
# At this time, jruby-openssl raises later. TODO
cipher = OpenSSL::Cipher::Cipher.new('aes-256-cbc')
cipher.encrypt
cipher.padding = 0
if allowed
assert_nothing_raised(OpenSSL::Cipher::CipherError) do
cipher.pkcs5_keyivgen("password")
end
else
assert_raise(OpenSSL::Cipher::CipherError) do
cipher.pkcs5_keyivgen("password")
end
end
end
def test_iv_length_auto_trim_JRUBY_4012
e1 = e2 = nil
plain = 'data'
des = OpenSSL::Cipher::Cipher.new("des-ede3-cbc")
des.encrypt
des.key = '0123456789abcdef01234567890'
des.iv = "0" * (128/8) # too long for DES which is a 64 bit block
assert_nothing_raised do
e1 = des.update(plain) + des.final
end
des = OpenSSL::Cipher::Cipher.new("des-ede3-cbc")
des.encrypt
des.key = '0123456789abcdef01234567890'
des.iv = "0" * (64/8) # DES is a 64 bit block
e2 = des.update(plain) + des.final
assert_equal(e2, e1, "JRUBY-4012")
end
private
def do_repeated_test(algo, string, enc1, enc2)
do_repeated_encrypt_test(algo, string, enc1, enc2)
do_repeated_decrypt_test(algo, string, enc1, enc2)
end
def do_repeated_encrypt_test(algo, string, result1, result2)
cipher = OpenSSL::Cipher::Cipher.new(algo)
cipher.encrypt
cipher.padding = 0
cipher.iv = IV_TEMPLATE[0, cipher.iv_len]
cipher.key = KEY_TEMPLATE[0, cipher.key_len]
assert_equal result1, cipher.update(string)
assert_equal "", cipher.final
assert_equal result2, cipher.update(string) + cipher.final
end
def do_repeated_decrypt_test(algo, result, string1, string2)
cipher = OpenSSL::Cipher::Cipher.new(algo)
cipher.decrypt
cipher.padding = 0
cipher.iv = IV_TEMPLATE[0, cipher.iv_len]
cipher.key = KEY_TEMPLATE[0, cipher.key_len]
assert_equal result, cipher.update(string1)
assert_equal "", cipher.final
assert_equal result, cipher.update(string2) + cipher.final
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/test_integration.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/test_integration.rb | begin
require "openssl"
rescue LoadError
end
require "test/unit"
require 'net/https'
class TestIntegration < Test::Unit::TestCase
# JRUBY-2471
def _test_drb
config = {
:SSLVerifyMode => OpenSSL::SSL::VERIFY_PEER,
:SSLCACertificateFile => File.join(File.dirname(__FILE__), "fixture", "cacert.pem"),
:SSLPrivateKey => OpenSSL::PKey::RSA.new(File.read(File.join(File.dirname(__FILE__), "fixture", "localhost_keypair.pem"))),
:SSLCertificate => OpenSSL::X509::Certificate.new(File.read(File.join(File.dirname(__FILE__), "fixture", "cert_localhost.pem"))),
}
p config
DRb.start_service(nil, nil, config)
end
# JRUBY-2913
# Warning - this test actually uses the internet connection.
# If there is no connection, it will fail.
def test_ca_path_name
uri = URI.parse('https://www.amazon.com')
http = Net::HTTP.new(uri.host, uri.port)
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
http.ca_path = "test/fixture/ca_path/"
http.use_ssl = true
response = http.start do |s|
assert s.get(uri.request_uri).length > 0
end
end
# Warning - this test actually uses the internet connection.
# If there is no connection, it will fail.
def test_ssl_verify
uri = URI.parse('https://www.amazon.com/')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
# right trust anchor for www.amazon.com
http.ca_file = 'test/fixture/verisign.pem'
response = http.start do |s|
assert s.get(uri.request_uri).length > 0
end
# wrong trust anchor for www.amazon.com
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
http.ca_file = 'test/fixture/verisign_c3.pem'
assert_raise(OpenSSL::SSL::SSLError) do
# it must cause SSLError for verification failure.
response = http.start do |s|
s.get(uri.request_uri)
end
end
# round trip
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
http.ca_file = 'test/fixture/verisign.pem'
response = http.start do |s|
assert s.get(uri.request_uri).length > 0
end
end
# Warning - this test actually uses the internet connection.
# If there is no connection, it will fail.
def test_pathlen_does_not_appear
uri = URI.parse('https://www.paypal.com/')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
# right trust anchor for www.amazon.com
http.ca_file = 'test/fixture/verisign_c3.pem'
response = http.start do |s|
assert s.get(uri.request_uri).length > 0
end
end
# JRUBY-2178 and JRUBY-1307
# Warning - this test actually uses the internet connection.
# If there is no connection, it will fail.
# This test generally throws an exception
# about illegal_parameter when
# it can't use the cipher string correctly
def test_cipher_strings
socket = TCPSocket.new('rubyforge.org', 443)
ctx = OpenSSL::SSL::SSLContext.new
ctx.cert_store = OpenSSL::X509::Store.new
ctx.verify_mode = 0
ctx.cert = nil
ctx.key = nil
ctx.client_ca = nil
ctx.ciphers = "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"
ssl_socket = OpenSSL::SSL::SSLSocket.new(socket, ctx)
ssl_socket.connect
ssl_socket.close
end
# JRUBY-1194
def test_des_encryption
iv = "IVIVIVIV"
key = "KEYKEYKE"
alg = "des"
str = "string abc foo bar baxz"
cipher = OpenSSL::Cipher::Cipher.new(alg)
cipher.encrypt(key, iv)
cipher.padding = 32
cipher.key = key
cipher.iv = iv
encrypted = cipher.update(str)
encrypted << cipher.final
assert_equal "\253\305\306\372;\374\235\302\357/\006\360\355XO\232\312S\356* #\227\217", encrypted
end
def _test_perf_of_nil
# require 'net/https'
# require 'benchmark'
# def request(data)
# connection = Net::HTTP.new("www.google.com", 443)
# connection.use_ssl = true
# connection.verify_mode = OpenSSL::SSL::VERIFY_NONE
# connection.start do |connection|
# connection.request_post("/tbproxy/spell?lang=en", data, { 'User-Agent' => "Test", 'Accept' => 'text/xml' })
# end
# end
# puts "is not: #{Benchmark.measure { request("") }.to_s.chomp}"
# puts "is nil: #{Benchmark.measure { request(nil) }.to_s.chomp}"
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/test_pkey.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/test_pkey.rb | begin
require "openssl"
rescue LoadError
end
require "test/unit"
class TestPKey < Test::Unit::TestCase
def test_has_correct_methods
pkey_methods = OpenSSL::PKey::PKey.instance_methods(false).sort - ["initialize"]
assert_equal ["sign", "verify"], pkey_methods
rsa_methods = OpenSSL::PKey::RSA.instance_methods(false).sort - ["initialize"]
assert_equal ["d", "d=", "dmp1", "dmp1=", "dmq1", "dmq1=", "e", "e=", "export", "iqmp", "iqmp=", "n", "n=", "p", "p=", "params", "private?", "private_decrypt", "private_encrypt", "public?", "public_decrypt", "public_encrypt", "public_key", "q", "q=", "to_der", "to_pem", "to_s", "to_text"], rsa_methods
assert_equal ["generate"], OpenSSL::PKey::RSA.methods(false)
# dsa_methods = OpenSSL::PKey::DSA.instance_methods(false).sort - ["initialize"]
# assert_equal ["export", "g", "g=", "p", "p=", "params", "priv_key", "priv_key=", "private?", "pub_key", "pub_key=", "public?", "public_key", "q", "q=", "syssign", "sysverify", "to_der", "to_pem", "to_s", "to_text"], dsa_methods
# assert_equal ["generate"], OpenSSL::PKey::DSA.methods(false)
end
#iqmp == coefficient
#e == public exponent
#n == modulus
#d == private exponent
#p == prime1
#q == prime2
#dmq1 == exponent2
#dmp1 == exponent1
def test_can_generate_rsa_key
OpenSSL::PKey::RSA.generate(512)
end
def test_can_generate_dsa_key
OpenSSL::PKey::DSA.generate(512)
end
def test_malformed_rsa_handling
pem = <<__EOP__
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtiU1/UMzIQ1On9OlZGoV
S0yySFYWoXLH12nmP69fg9jwdRbQlb0rxLn7zATbwfqcvGpCcW+8SmdwW74elNrc
wRtbKjJKfbJCsVfDssbbj6BF+Bcq3ihi8+CGNXFdJOYhZZ+5Adg2Qc9Qp3Ubw9wu
/3Ai87+1aQxoZPMFwdX2BRiZvxch9dwHVyL8EuFGUOYId/8JQepHyZMbTqp/8wlA
UAbMcPW+IKp3N0WMgred3CjXKHAqqM0Ira9RLSXdlO2uFV4OrM0ak8rnTN5w1DsI
McjvVvOck0aIxfHEEmeadt3YMn4PCW33/j8geulZLvt0ci60/OWMSCcIqByITlvY
DwIDAQAB
-----END PUBLIC KEY-----
__EOP__
pkey = OpenSSL::PKey::RSA.new(pem)
# jruby-openssl/0.6 raises NativeException
assert_raise(OpenSSL::PKey::RSAError, 'JRUBY-4492') do
pkey.public_decrypt("rah")
end
end
# http://github.com/jruby/jruby-openssl/issues#issue/1
def test_load_pkey_rsa
pem = <<__EOP__
-----BEGIN PRIVATE KEY-----
MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALRiMLAh9iimur8V
A7qVvdqxevEuUkW4K+2KdMXmnQbG9Aa7k7eBjK1S+0LYmVjPKlJGNXHDGuy5Fw/d
7rjVJ0BLB+ubPK8iA/Tw3hLQgXMRRGRXXCn8ikfuQfjUS1uZSatdLB81mydBETlJ
hI6GH4twrbDJCR2Bwy/XWXgqgGRzAgMBAAECgYBYWVtleUzavkbrPjy0T5FMou8H
X9u2AC2ry8vD/l7cqedtwMPp9k7TubgNFo+NGvKsl2ynyprOZR1xjQ7WgrgVB+mm
uScOM/5HVceFuGRDhYTCObE+y1kxRloNYXnx3ei1zbeYLPCHdhxRYW7T0qcynNmw
rn05/KO2RLjgQNalsQJBANeA3Q4Nugqy4QBUCEC09SqylT2K9FrrItqL2QKc9v0Z
zO2uwllCbg0dwpVuYPYXYvikNHHg+aCWF+VXsb9rpPsCQQDWR9TT4ORdzoj+Nccn
qkMsDmzt0EfNaAOwHOmVJ2RVBspPcxt5iN4HI7HNeG6U5YsFBb+/GZbgfBT3kpNG
WPTpAkBI+gFhjfJvRw38n3g/+UeAkwMI2TJQS4n8+hid0uus3/zOjDySH3XHCUno
cn1xOJAyZODBo47E+67R4jV1/gzbAkEAklJaspRPXP877NssM5nAZMU0/O/NGCZ+
3jPgDUno6WbJn5cqm8MqWhW1xGkImgRk+fkDBquiq4gPiT898jusgQJAd5Zrr6Q8
AO/0isr/3aa6O6NLQxISLKcPDk2NOccAfS/xOtfOz4sJYM3+Bs4Io9+dZGSDCA54
Lw03eHTNQghS0A==
-----END PRIVATE KEY-----
__EOP__
assert_nothing_raised do
pkey = OpenSSL::PKey::RSA.new(pem)
pkey2 = OpenSSL::PKey::RSA.new(pkey.to_pem)
assert_equal(pkey.n, pkey2.n)
assert_equal(pkey.e, pkey2.e)
assert_equal(pkey.d, pkey2.d)
end
end
def test_load_pkey_rsa_enc
# password is '1234'
pem = <<__EOP__
-----BEGIN ENCRYPTED PRIVATE KEY-----
MIICoTAbBgkqhkiG9w0BBQMwDgQIfvehP6JEg2wCAggABIICgD7kzSr+xWgdAuzG
cYNkCEWyKF6V0cJ58AKSoL4FQ59OQvQP/hMnSZEMiUpeGNRE6efC7O02RUjNarIk
ciCYIBqd5EFG3OSypK5l777AbCChIkzZHbyE/pIbadr8ZX9C4pkwzPqS0Avzavxi
5s1WDX2GggJkBcQUijqG9QuOZcOvoYbojHPT4tdJq+J6s+0LFas9Jp3a6dYkxtgv
u8Z6EFDZoLGOSVy/jCSMuZAnhoOxUCYqd9FFo2jryV7tQ/CaYAUApAQFTLgBA9qk
4WmyKRpwzIx6EG1pkqulvPXJCcTat9YwllEDVuQ2rKVwDepSl9O7X170Kx1sBecz
mGcfqviU9xwP5mkXO/TLoTZExkHF08Y3d/PTMdxGEDZH37/yRqCIb3Uyqv/jLibM
/s9fm52aWsfO1ndHEhciovlMJvGXq3+e+9gmq1w2TyNQahRc5fwfhwWKhPKfYDBk
7AtjPGfELDX61WZ5m+4Kb70BcGSAEgXCaBydVsMROy0B8jkYgtAnVBb4EMrGOsCG
jmNeW9MRIhrhDcifdyq1DMNg7IONMF+5mDdQ3FhK6WzlFU+8cTN517qA8L3A3+ZX
asiS+rx5/50InINknjuvVkmTGMzjl89nMNrZCjhx9sIDfXQ3ZKFmh1mvnXq/fLan
CgXn/UtLoykrSlobgqIxZslhj3p01kMCgGe62S3kokYrDTQEc57rlKWWR3Xyjy/T
LsecXAKEROj95IHSMMnT4jl+TJnbvGKQ2U9tOOB3W+OOOlDEFE59pQlcmQPAwdzr
mzI4kupi3QRTFjOgvX29leII9sPtpr4dKMKVIRxKnvMZhUAkS/n3+Szfa6zKexLa
4CHVgDo=
-----END ENCRYPTED PRIVATE KEY-----
__EOP__
assert_nothing_raised do
pkey = OpenSSL::PKey::RSA.new(pem, '1234')
pkey2 = OpenSSL::PKey::RSA.new(pkey.to_pem)
assert_equal(pkey.n, pkey2.n)
assert_equal(pkey.e, pkey2.e)
assert_equal(pkey.d, pkey2.d)
end
end
# jruby-openssl/0.6 causes NPE
def test_generate_pkey_rsa_empty
assert_nothing_raised do
OpenSSL::PKey::RSA.new.to_pem
end
end
def test_generate_pkey_rsa_length
assert_nothing_raised do
OpenSSL::PKey::RSA.new(512).to_pem
end
end
def test_generate_pkey_rsa_to_text
assert_match(
/Private-Key: \(512 bit\)/,
OpenSSL::PKey::RSA.new(512).to_text
)
end
def test_load_pkey_rsa
pkey = OpenSSL::PKey::RSA.new(512)
assert_equal(pkey.to_pem, OpenSSL::PKey::RSA.new(pkey.to_pem).to_pem)
end
def test_load_pkey_rsa_public
pkey = OpenSSL::PKey::RSA.new(512).public_key
assert_equal(pkey.to_pem, OpenSSL::PKey::RSA.new(pkey.to_pem).to_pem)
end
def test_load_pkey_rsa_der
pkey = OpenSSL::PKey::RSA.new(512)
assert_equal(pkey.to_der, OpenSSL::PKey::RSA.new(pkey.to_der).to_der)
end
def test_load_pkey_rsa_public_der
pkey = OpenSSL::PKey::RSA.new(512).public_key
assert_equal(pkey.to_der, OpenSSL::PKey::RSA.new(pkey.to_der).to_der)
end
# jruby-openssl/0.6 causes NPE
def test_generate_pkey_dsa_empty
assert_nothing_raised do
OpenSSL::PKey::DSA.new.to_pem
end
end
# jruby-openssl/0.6 ignores fixnum arg => to_pem returned 65 bytes with 'MAA='
def test_generate_pkey_dsa_length
assert(OpenSSL::PKey::DSA.new(512).to_pem.size > 100)
end
# jruby-openssl/0.6 returns nil for DSA#to_text
def test_generate_pkey_dsa_to_text
assert_match(
/Private-Key: \(512 bit\)/,
OpenSSL::PKey::DSA.new(512).to_text
)
end
def test_load_pkey_dsa
pkey = OpenSSL::PKey::DSA.new(512)
assert_equal(pkey.to_pem, OpenSSL::PKey::DSA.new(pkey.to_pem).to_pem)
end
def test_load_pkey_dsa_public
pkey = OpenSSL::PKey::DSA.new(512).public_key
assert_equal(pkey.to_pem, OpenSSL::PKey::DSA.new(pkey.to_pem).to_pem)
end
def test_load_pkey_dsa_der
pkey = OpenSSL::PKey::DSA.new(512)
assert_equal(pkey.to_der, OpenSSL::PKey::DSA.new(pkey.to_der).to_der)
end
def test_load_pkey_dsa_public_der
pkey = OpenSSL::PKey::DSA.new(512).public_key
assert_equal(pkey.to_der, OpenSSL::PKey::DSA.new(pkey.to_der).to_der)
end
def test_load_pkey_dsa_net_ssh
blob = "0\201\367\002\001\000\002A\000\203\316/\037u\272&J\265\003l3\315d\324h\372{\t8\252#\331_\026\006\035\270\266\255\343\353Z\302\276\335\336\306\220\375\202L\244\244J\206>\346\b\315\211\302L\246x\247u\a\376\366\345\302\016#\002\025\000\244\274\302\221Og\275/\302+\356\346\360\024\373wI\2573\361\002@\027\215\270r*\f\213\350C\245\021:\350 \006\\\376\345\022`\210b\262\3643\023XLKS\320\370\002\276\347A\nU\204\276\324\256`=\026\240\330\306J\316V\213\024\e\030\215\355\006\037q\337\356ln\002@\017\257\034\f\260\333'S\271#\237\230E\321\312\027\021\226\331\251Vj\220\305\316\036\v\266+\000\230\270\177B\003?t\a\305]e\344\261\334\023\253\323\251\223M\2175)a(\004\"lI8\312\303\307\a\002\024_\aznW\345\343\203V\326\246ua\203\376\201o\350\302\002"
pkey = OpenSSL::PKey::DSA.new(blob)
assert_equal(blob, pkey.to_der)
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/test_parse_certificate.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/test_parse_certificate.rb | require 'openssl'
require "test/unit"
class TestParseCertificate < Test::Unit::TestCase
CERT = File.dirname(__FILE__) + '/cert_with_ec_pk.cer'
def test_certificate_parse_works_with_ec_pk_cert
cer = OpenSSL::X509::Certificate.new(File.read(CERT))
assert cer.to_s != nil
assert cer.issuer.to_s != nil
assert cer.subject.to_s != nil
assert cer.extensions.to_s != nil
end
def test_certificate_with_ec_pk_cert_fails_requesting_pk
cer = OpenSSL::X509::Certificate.new(File.read(CERT))
assert_raise(OpenSSL::X509::CertificateError) { cer.public_key }
end
def test_loading_key_raise_certificate_error
key_file = File.expand_path('fixture/keypair.pem', File.dirname(__FILE__))
assert_raises(OpenSSL::X509::CertificateError) do
OpenSSL::X509::Certificate.new(File.read(key_file))
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/test_certificate.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/test_certificate.rb | require 'openssl'
require "test/unit"
class TestCertificate < Test::Unit::TestCase
def setup
cert_file = File.expand_path('fixture/selfcert.pem', File.dirname(__FILE__))
key_file = File.expand_path('fixture/keypair.pem', File.dirname(__FILE__))
@cert = OpenSSL::X509::Certificate.new(File.read(cert_file))
@key = OpenSSL::PKey::RSA.new(File.read(key_file))
end
def test_sign_for_pem_initialized_certificate
pem = @cert.to_pem
exts = @cert.extensions
assert_nothing_raised do
@cert.sign(@key, OpenSSL::Digest::SHA1.new)
end
# TODO: for now, jruby-openssl cannot keep order of extensions after sign.
# assert_equal(pem, @cert.to_pem)
assert_equal(exts.size, @cert.extensions.size)
exts.each do |ext|
found = @cert.extensions.find { |e| e.oid == ext.oid }
assert_not_nil(found)
assert_equal(ext.value, found.value)
end
end
def test_set_public_key
pkey = @cert.public_key
newkey = OpenSSL::PKey::RSA.new(1024)
@cert.public_key = newkey
assert_equal(newkey.public_key.to_pem, @cert.public_key.to_pem)
end
# JRUBY-3468
def test_jruby3468
pem_cert = <<END
-----BEGIN CERTIFICATE-----
MIIC/jCCAmegAwIBAgIBATANBgkqhkiG9w0BAQUFADBNMQswCQYDVQQGEwJKUDER
MA8GA1UECgwIY3Rvci5vcmcxFDASBgNVBAsMC0RldmVsb3BtZW50MRUwEwYDVQQD
DAxodHRwLWFjY2VzczIwHhcNMDcwOTExMTM1ODMxWhcNMDkwOTEwMTM1ODMxWjBN
MQswCQYDVQQGEwJKUDERMA8GA1UECgwIY3Rvci5vcmcxFDASBgNVBAsMC0RldmVs
b3BtZW50MRUwEwYDVQQDDAxodHRwLWFjY2VzczIwgZ8wDQYJKoZIhvcNAQEBBQAD
gY0AMIGJAoGBALi66ujWtUCQm5HpMSyr/AAIFYVXC/dmn7C8TR/HMiUuW3waY4uX
LFqCDAGOX4gf177pX+b99t3mpaiAjJuqc858D9xEECzhDWgXdLbhRqWhUOble4RY
c1yWYC990IgXJDMKx7VAuZ3cBhdBxtlE9sb1ZCzmHQsvTy/OoRzcJCrTAgMBAAGj
ge0wgeowDwYDVR0TAQH/BAUwAwEB/zAxBglghkgBhvhCAQ0EJBYiUnVieS9PcGVu
U1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4EFgQUJNE0GGaRKmN2qhnO
FyBWVl4Qj6owDgYDVR0PAQH/BAQDAgEGMHUGA1UdIwRuMGyAFCTRNBhmkSpjdqoZ
zhcgVlZeEI+qoVGkTzBNMQswCQYDVQQGEwJKUDERMA8GA1UECgwIY3Rvci5vcmcx
FDASBgNVBAsMC0RldmVsb3BtZW50MRUwEwYDVQQDDAxodHRwLWFjY2VzczKCAQEw
DQYJKoZIhvcNAQEFBQADgYEAH11tstSUuqFpMqoh/vM5l3Nqb8ygblbqEYQs/iG/
UeQkOZk/P1TxB6Ozn2htJ1srqDpUsncFVZ/ecP19GkeOZ6BmIhppcHhE5WyLBcPX
It5q1BW0PiAzT9LlEGoaiW0nw39so0Pr1whJDfc1t4fjdk+kSiMIzRHbTDvHWfpV
nTA=
-----END CERTIFICATE-----
END
cert = OpenSSL::X509::Certificate.new(pem_cert)
key_id = cert.extensions[2]
assert_equal "24:D1:34:18:66:91:2A:63:76:AA:19:CE:17:20:56:56:5E:10:8F:AA", key_id.value
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/ut_eof.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/ut_eof.rb | require 'test/unit'
module TestEOF
def test_eof_0
open_file("") {|f|
assert_equal("", f.read(0))
assert_equal("", f.read(0))
assert_equal("", f.read)
assert_nil(f.read(0))
assert_nil(f.read(0))
}
open_file("") {|f|
assert_nil(f.read(1))
assert_equal("", f.read)
assert_nil(f.read(1))
}
open_file("") {|f|
s = "x"
assert_equal("", f.read(nil, s))
assert_equal("", s)
}
open_file("") {|f|
s = "x"
assert_nil(f.read(10, s))
assert_equal("", s)
}
end
def test_eof_0_rw
return unless respond_to? :open_file_rw
open_file_rw("") {|f|
assert_equal("", f.read)
assert_equal("", f.read)
assert_equal(0, f.syswrite(""))
assert_equal("", f.read)
}
end
def test_eof_1
open_file("a") {|f|
assert_equal("", f.read(0))
assert_equal("a", f.read(1))
assert_equal("" , f.read(0))
assert_equal("" , f.read(0))
assert_equal("", f.read)
assert_nil(f.read(0))
assert_nil(f.read(0))
}
open_file("a") {|f|
assert_equal("a", f.read(1))
assert_nil(f.read(1))
}
open_file("a") {|f|
assert_equal("a", f.read(2))
assert_nil(f.read(1))
assert_equal("", f.read)
assert_nil(f.read(1))
}
open_file("a") {|f|
assert_equal("a", f.read)
assert_nil(f.read(1))
assert_equal("", f.read)
assert_nil(f.read(1))
}
open_file("a") {|f|
assert_equal("a", f.read(2))
assert_equal("", f.read)
assert_equal("", f.read)
}
open_file("a") {|f|
assert_equal("a", f.read)
assert_nil(f.read(0))
}
open_file("a") {|f|
s = "x"
assert_equal("a", f.read(nil, s))
assert_equal("a", s)
}
open_file("a") {|f|
s = "x"
assert_equal("a", f.read(10, s))
assert_equal("a", s)
}
end
def test_eof_2
open_file("") {|f|
assert_equal("", f.read)
assert(f.eof?)
}
end
def test_eof_3
open_file("") {|f|
assert(f.eof?)
}
end
module Seek
def open_file_seek(content, pos)
open_file(content) do |f|
f.seek(pos)
yield f
end
end
def test_eof_0_seek
open_file_seek("", 10) {|f|
assert_equal(10, f.pos)
assert_equal("", f.read(0))
assert_equal("", f.read)
assert_nil(f.read(0))
assert_equal("", f.read)
}
end
def test_eof_1_seek
open_file_seek("a", 10) {|f|
assert_equal("", f.read)
assert_equal("", f.read)
}
open_file_seek("a", 1) {|f|
assert_equal("", f.read)
assert_equal("", f.read)
}
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/test_openssl.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/test_openssl.rb | files = File.join(File.dirname(__FILE__), 'openssl', 'test_*.rb')
Dir.glob(files).sort.each do |tc|
require tc
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/test_java.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/test_java.rb | $:.unshift File.join(File.dirname(__FILE__), '..', 'mocha', 'lib')
require "test/unit"
require 'mocha'
if defined?(JRUBY_VERSION)
require "java"
$CLASSPATH << 'pkg/classes'
$CLASSPATH << 'lib/bcprov-jdk15-144.jar'
module PKCS7Test
module ASN1
OctetString = org.bouncycastle.asn1.DEROctetString
end
PKCS7 = org.jruby.ext.openssl.impl.PKCS7 unless defined?(PKCS7)
Attribute = org.jruby.ext.openssl.impl.Attribute unless defined?(Attribute)
CipherSpec = org.jruby.ext.openssl.impl.CipherSpec unless defined?(CipherSpec)
Digest = org.jruby.ext.openssl.impl.Digest unless defined?(Digest)
EncContent = org.jruby.ext.openssl.impl.EncContent unless defined?(EncContent)
Encrypt = org.jruby.ext.openssl.impl.Encrypt unless defined?(Encrypt)
Envelope = org.jruby.ext.openssl.impl.Envelope unless defined?(Envelope)
IssuerAndSerial = org.jruby.ext.openssl.impl.IssuerAndSerial unless defined?(IssuerAndSerial)
RecipInfo = org.jruby.ext.openssl.impl.RecipInfo unless defined?(RecipInfo)
SignEnvelope = org.jruby.ext.openssl.impl.SignEnvelope unless defined?(SignEnvelope)
Signed = org.jruby.ext.openssl.impl.Signed unless defined?(Signed)
SMIME = org.jruby.ext.openssl.impl.SMIME unless defined?(SMIME)
Mime = org.jruby.ext.openssl.impl.Mime unless defined?(Mime)
MimeHeader = org.jruby.ext.openssl.impl.MimeHeader unless defined?(MimeHeader)
MimeParam = org.jruby.ext.openssl.impl.MimeParam unless defined?(MimeParam)
BIO = org.jruby.ext.openssl.impl.BIO unless defined?(BIO)
PKCS7Exception = org.jruby.ext.openssl.impl.PKCS7Exception unless defined?(PKCS7Exception)
ASN1Registry = org.jruby.ext.openssl.impl.ASN1Registry unless defined?(ASN1Registry)
AlgorithmIdentifier = org.bouncycastle.asn1.x509.AlgorithmIdentifier unless defined?(AlgorithmIdentifier)
SignerInfoWithPkey = org.jruby.ext.openssl.impl.SignerInfoWithPkey unless defined?(SignerInfoWithPkey)
IssuerAndSerialNumber = org.bouncycastle.asn1.pkcs.IssuerAndSerialNumber unless defined?(IssuerAndSerialNumber)
ASN1InputStream = org.bouncycastle.asn1.ASN1InputStream unless defined?(ASN1InputStream)
X509AuxCertificate = org.jruby.ext.openssl.x509store.X509AuxCertificate unless defined?(X509AuxCertificate)
ArrayList = java.util.ArrayList unless defined?(ArrayList)
CertificateFactory = java.security.cert.CertificateFactory unless defined?(CertificateFactory)
BCP = org.bouncycastle.jce.provider.BouncyCastleProvider unless defined?(BCP)
ByteArrayInputStream = java.io.ByteArrayInputStream unless defined?(ByteArrayInputStream)
BigInteger = java.math.BigInteger unless defined?(BigInteger)
Cipher = javax.crypto.Cipher unless defined?(Cipher)
DERInteger = org.bouncycastle.asn1.DERInteger
DERSet = org.bouncycastle.asn1.DERSet
DEROctetString = org.bouncycastle.asn1.DEROctetString
X509Name = org.bouncycastle.asn1.x509.X509Name
MimeEnvelopedString = File::read(File.join(File.dirname(__FILE__), 'java', 'pkcs7_mime_enveloped.message'))
MimeSignedString = File::read(File.join(File.dirname(__FILE__), 'java', 'pkcs7_mime_signed.message'))
MultipartSignedString = File::read(File.join(File.dirname(__FILE__), 'java', 'pkcs7_multipart_signed.message'))
X509CertString = <<CERT
-----BEGIN CERTIFICATE-----
MIICijCCAXKgAwIBAgIBAjANBgkqhkiG9w0BAQUFADA9MRMwEQYKCZImiZPyLGQB
GRYDb3JnMRkwFwYKCZImiZPyLGQBGRYJcnVieS1sYW5nMQswCQYDVQQDDAJDQTAe
Fw0wODA3MDgxOTE1NDZaFw0wODA3MDgxOTQ1NDZaMEQxEzARBgoJkiaJk/IsZAEZ
FgNvcmcxGTAXBgoJkiaJk/IsZAEZFglydWJ5LWxhbmcxEjAQBgNVBAMMCWxvY2Fs
aG9zdDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAy8LEsNRApz7U/j5DoB4X
BgO9Z8Atv5y/OVQRp0ag8Tqo1YewsWijxEWB7JOATwpBN267U4T1nPZIxxEEO7n/
WNa2ws9JWsjah8ssEBFSxZqdXKSLf0N4Hi7/GQ/aYoaMCiQ8jA4jegK2FJmXM71u
Pe+jFN/peeBOpRfyXxRFOYcCAwEAAaMSMBAwDgYDVR0PAQH/BAQDAgWgMA0GCSqG
SIb3DQEBBQUAA4IBAQCU879BALJIM9avHiuZ3WTjDy0UYP3ZG5wtuSqBSnD1k8pr
hXfRaga7mDj6EQaGUovImb+KrRi6mZc+zsx4rTxwBNJT9U8yiW2eYxmgcT9/qKrD
/1nz+e8NeUCCDY5UTUHGszZw5zLEDgDX2n3E/CDIZsoRSyq5vXq1jpfih/tSWanj
Y9uP/o8Dc7ZcRJOAX7NPu1bbZcbxEbZ8sMe5wZ5HNiAR6gnOrjz2Yyazb//PSskE
4flt/2h4pzGA0/ZHcnDjcoLdiLtInsqPOlVDLgqd/XqRYWtj84N4gw1iS9cHyrIZ
dqbS54IKvzElD+R0QVS2z6TIGJSpuSBnZ4yfuNuq
-----END CERTIFICATE-----
CERT
X509CRLString = <<CRL
----BEGIN X509 CRL-----
MIIBlTB/AgEBMA0GCSqGSIb3DQEBBQUAMD0xEzARBgoJkiaJk/IsZAEZFgNvcmcx
GTAXBgoJkiaJk/IsZAEZFglydWJ5LWxhbmcxCzAJBgNVBAMMAkNBFw0wODA3MTgx
NzQxMjhaFw0wODA3MTgxODA4MDhaoA4wDDAKBgNVHRQEAwIBATANBgkqhkiG9w0B
AQUFAAOCAQEASJaj1keN+tMmsF3QmjH2RhbW/9rZAl4gjv+uQQqrcS2ByfkXLU1d
l/8rCHeT/XMoeU6xhQNHPP3uZBwfuuETcp65BMBcZFOUhUR0U5AaGhvSDS/+6EsP
zFdQgAagmThFdN5ei9guTLqWwN0ZyqiaHyevFJuk+L9qbKavaSeKqfJbU7Sj/Z3J
WLKoixvyj3N6W7evygH80lTvjZugmxJ1/AjICVSYr1hpHHd6EWq0b0YFrGFmg27R
WmsAXd0QV5UChfAJ2+Cz5U1bPszvIJGrzfAIoLxHv5rI5rseQzqZdPaFSe4Oehln
9qEYmsK3PS6bYoQol0cgj97Ep4olS8CulA==
-----END X509 CRL-----
CRL
X509Cert = X509AuxCertificate.new(CertificateFactory.getInstance("X.509",BCP.new).generateCertificate(ByteArrayInputStream.new(X509CertString.to_java_bytes)))
X509CRL = CertificateFactory.getInstance("X.509",BCP.new).generateCRL(ByteArrayInputStream.new(X509CRLString.to_java_bytes))
end
files = File.join(File.dirname(__FILE__), 'java', 'test_*.rb')
Dir.glob(files).sort.each do |tc|
require tc
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/openssl/ssl_server.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/openssl/ssl_server.rb | require "socket"
require "thread"
require "openssl"
require File.join(File.dirname(__FILE__), "utils.rb")
def get_pem(io=$stdin)
buf = ""
while line = io.gets
if /^-----BEGIN / =~ line
buf << line
break
end
end
while line = io.gets
buf << line
if /^-----END / =~ line
break
end
end
return buf
end
def make_key(pem)
begin
return OpenSSL::PKey::RSA.new(pem)
rescue
return OpenSSL::PKey::DSA.new(pem)
end
end
if $DEBUG
def log(s); File.open("ssl-server-debug", "a") {|f| f.puts s}; end
File.open("ssl-server-debug", "w") {|f| f << ""}
log "server starting"
else
def log(s) end
end
begin
ca_cert = OpenSSL::X509::Certificate.new(get_pem)
log "got ca cert #{ca_cert.inspect}"
ssl_cert = OpenSSL::X509::Certificate.new(get_pem)
log "got ssl cert #{ssl_cert.inspect}"
ssl_key = make_key(get_pem)
port = Integer(ARGV.shift)
verify_mode = Integer(ARGV.shift)
start_immediately = (/yes/ =~ ARGV.shift)
store = OpenSSL::X509::Store.new
store.add_cert(ca_cert)
store.purpose = OpenSSL::X509::PURPOSE_SSL_CLIENT
ctx = OpenSSL::SSL::SSLContext.new
ctx.cert_store = store
#ctx.extra_chain_cert = [ ca_cert ]
ctx.cert = ssl_cert
ctx.key = ssl_key
ctx.verify_mode = verify_mode
Socket.do_not_reverse_lookup = true
tcps = nil
100.times{|i|
begin
log "starting server on #{port+i}"
tcps = TCPServer.new("0.0.0.0", port+i)
port = port + i
break
rescue Errno::EADDRINUSE
next
end
}
log "starting ssl server"
ssls = OpenSSL::SSL::SSLServer.new(tcps, ctx)
ssls.start_immediately = start_immediately
log("sending pid #{Process.pid}")
$stdout.sync = true
$stdout.puts Process.pid
$stdout.puts port
loop do
ssl = ssls.accept rescue next
Thread.start{
q = Queue.new
th = Thread.start{ ssl.write(q.shift) while true }
while line = ssl.gets
if line =~ /^STARTTLS$/
ssl.accept
next
end
q.push(line)
end
th.kill if q.empty?
ssl.close
}
end
rescue
log $!
log $!.backtrace.join("\n")
end | ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/openssl/test_pkey_rsa.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/openssl/test_pkey_rsa.rb | begin
require "openssl"
require File.join(File.dirname(__FILE__), "utils.rb")
rescue LoadError
end
require 'test/unit'
if defined?(OpenSSL)
class OpenSSL::TestPKeyRSA < Test::Unit::TestCase
def test_padding
key = OpenSSL::PKey::RSA.new(512, 3)
# Need right size for raw mode
plain0 = "x" * (512/8)
cipher = key.private_encrypt(plain0, OpenSSL::PKey::RSA::NO_PADDING)
plain1 = key.public_decrypt(cipher, OpenSSL::PKey::RSA::NO_PADDING)
assert_equal(plain0, plain1)
# Need smaller size for pkcs1 mode
plain0 = "x" * (512/8 - 11)
cipher1 = key.private_encrypt(plain0, OpenSSL::PKey::RSA::PKCS1_PADDING)
plain1 = key.public_decrypt(cipher1, OpenSSL::PKey::RSA::PKCS1_PADDING)
assert_equal(plain0, plain1)
cipherdef = key.private_encrypt(plain0) # PKCS1_PADDING is default
plain1 = key.public_decrypt(cipherdef)
assert_equal(plain0, plain1)
assert_equal(cipher1, cipherdef)
# Failure cases
assert_raise(ArgumentError){ key.private_encrypt() }
assert_raise(ArgumentError){ key.private_encrypt("hi", 1, nil) }
assert_raise(OpenSSL::PKey::RSAError){ key.private_encrypt(plain0, 666) }
end
def test_private
key = OpenSSL::PKey::RSA.new(512, 3)
assert(key.private?)
key2 = OpenSSL::PKey::RSA.new(key.to_der)
assert(key2.private?)
key3 = key.public_key
assert(!key3.private?)
key4 = OpenSSL::PKey::RSA.new(key3.to_der)
assert(!key4.private?)
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/openssl/test_ssl.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/openssl/test_ssl.rb | begin
require "openssl"
require File.join(File.dirname(__FILE__), "utils.rb")
rescue LoadError
end
require "rbconfig"
require "socket"
require "test/unit"
require 'tempfile'
if defined?(OpenSSL)
class OpenSSL::TestSSL < Test::Unit::TestCase
RUBY = ENV["RUBY"] || File.join(
::Config::CONFIG["bindir"],
::Config::CONFIG["ruby_install_name"] + ::Config::CONFIG["EXEEXT"]
)
SSL_SERVER = File.join(File.dirname(__FILE__), "ssl_server.rb")
PORT = 20443
ITERATIONS = ($0 == __FILE__) ? 100 : 10
# NOT USED: Disable in-proc process launching and either run jruby with
# specified args or yield args to a given block
def jruby_oop(*args)
prev_in_process = JRuby.runtime.instance_config.run_ruby_in_process
JRuby.runtime.instance_config.run_ruby_in_process = false
if block_given?
yield args
else
`#{RUBY} #{args.join(' ')}`
end
ensure
JRuby.runtime.instance_config.run_ruby_in_process = prev_in_process
end
def setup
@ca_key = OpenSSL::TestUtils::TEST_KEY_RSA2048
@svr_key = OpenSSL::TestUtils::TEST_KEY_RSA1024
@cli_key = OpenSSL::TestUtils::TEST_KEY_DSA256
@ca = OpenSSL::X509::Name.parse("/DC=org/DC=ruby-lang/CN=CA")
@svr = OpenSSL::X509::Name.parse("/DC=org/DC=ruby-lang/CN=localhost")
@cli = OpenSSL::X509::Name.parse("/DC=org/DC=ruby-lang/CN=localhost")
now = Time.at(Time.now.to_i)
ca_exts = [
["basicConstraints","CA:TRUE",true],
["keyUsage","cRLSign,keyCertSign",true],
]
ee_exts = [
["keyUsage","keyEncipherment,digitalSignature",true],
]
@ca_cert = issue_cert(@ca, @ca_key, 1, now, now+3600, ca_exts,
nil, nil, OpenSSL::Digest::SHA1.new)
@svr_cert = issue_cert(@svr, @svr_key, 2, now, now+1800, ee_exts,
@ca_cert, @ca_key, OpenSSL::Digest::SHA1.new)
@cli_cert = issue_cert(@cli, @cli_key, 3, now, now+1800, ee_exts,
@ca_cert, @ca_key, OpenSSL::Digest::SHA1.new)
@server = nil
end
def teardown
end
def issue_cert(*arg)
OpenSSL::TestUtils.issue_cert(*arg)
end
def issue_crl(*arg)
OpenSSL::TestUtils.issue_crl(*arg)
end
def choose_port(port)
tcps = nil
100.times{ |i|
begin
tcps = TCPServer.new("127.0.0.1", port+i)
port = port + i
break
rescue Errno::EADDRINUSE
next
end
}
return tcps, port
end
def readwrite_loop(ctx, ssl)
while line = ssl.gets
if line =~ /^STARTTLS$/
ssl.accept
next
end
ssl.write(line)
end
rescue OpenSSL::SSL::SSLError
rescue IOError
ensure
ssl.close rescue nil
end
def server_loop(ctx, ssls, server_proc)
loop do
ssl = nil
begin
ssl = ssls.accept
rescue OpenSSL::SSL::SSLError
retry
end
Thread.start do
Thread.current.abort_on_exception = true
server_proc.call(ctx, ssl)
end
end
rescue Errno::EBADF, IOError
end
def start_server(port0, verify_mode, start_immediately, args = {}, &block)
ctx_proc = args[:ctx_proc]
server_proc = args[:server_proc]
server_proc ||= method(:readwrite_loop)
store = OpenSSL::X509::Store.new
store.add_cert(@ca_cert)
store.purpose = OpenSSL::X509::PURPOSE_SSL_CLIENT
ctx = OpenSSL::SSL::SSLContext.new
ctx.cert_store = store
#ctx.extra_chain_cert = [ ca_cert ]
ctx.cert = @svr_cert
ctx.key = @svr_key
ctx.verify_mode = verify_mode
ctx_proc.call(ctx) if ctx_proc
Socket.do_not_reverse_lookup = true
tcps, port = choose_port(port0)
begin
tcps = TCPServer.new("127.0.0.1", port)
rescue Errno::EADDRINUSE
port += 1
retry
end
ssls = OpenSSL::SSL::SSLServer.new(tcps, ctx)
ssls.start_immediately = start_immediately
begin
server = Thread.new do
Thread.current.abort_on_exception = true
server_loop(ctx, ssls, server_proc)
end
$stderr.printf("%s started: pid=%d port=%d\n", SSL_SERVER, $$, port) if $DEBUG
block.call(server, port.to_i)
ensure
tcps.close if (tcps)
if (server)
server.join(5)
if server.alive?
server.kill
server.join
flunk("TCPServer was closed and SSLServer is still alive") unless $!
end
end
end
end
def starttls(ssl)
ssl.puts("STARTTLS")
sleep 1 # When this line is eliminated, process on Cygwin blocks
# forever at ssl.connect. But I don't know why it does.
ssl.connect
end
def test_ctx_setup
ctx = OpenSSL::SSL::SSLContext.new
assert_equal(ctx.setup, true)
assert_equal(ctx.setup, nil)
end
def test_connect_and_close
start_server(PORT, OpenSSL::SSL::VERIFY_NONE, true){|server, port|
sock = TCPSocket.new("127.0.0.1", port)
ssl = OpenSSL::SSL::SSLSocket.new(sock)
assert(ssl.connect)
ssl.close
assert(!sock.closed?)
sock.close
sock = TCPSocket.new("127.0.0.1", port)
ssl = OpenSSL::SSL::SSLSocket.new(sock)
ssl.sync_close = true # !!
assert(ssl.connect)
ssl.close
assert(sock.closed?)
}
end
def test_read_and_write
start_server(PORT, OpenSSL::SSL::VERIFY_NONE, true){|server, port|
sock = TCPSocket.new("127.0.0.1", port)
ssl = OpenSSL::SSL::SSLSocket.new(sock)
ssl.sync_close = true
ssl.connect
assert_raise(ArgumentError) { ssl.sysread(-1) }
# syswrite and sysread
ITERATIONS.times{|i|
str = "x" * 100 + "\n"
ssl.syswrite(str)
assert_equal(str, ssl.sysread(str.size))
str = "x" * i * 100 + "\n"
buf = ""
ssl.syswrite(str)
assert_equal(buf.object_id, ssl.sysread(str.size, buf).object_id)
assert_equal(str, buf)
}
# puts and gets
ITERATIONS.times{
str = "x" * 100 + "\n"
ssl.puts(str)
assert_equal(str, ssl.gets)
}
# read and write
ITERATIONS.times{|i|
str = "x" * 100 + "\n"
ssl.write(str)
assert_equal(str, ssl.read(str.size))
str = "x" * i * 100 + "\n"
buf = ""
ssl.write(str)
assert_equal(buf.object_id, ssl.read(str.size, buf).object_id)
assert_equal(str, buf)
}
ssl.close
}
end
def test_sysread_chunks
args = {}
args[:server_proc] = proc { |ctx, ssl|
while line = ssl.gets
if line =~ /^STARTTLS$/
ssl.accept
next
end
ssl.write("0" * 800)
ssl.write("1" * 200)
ssl.close
break
end
}
start_server(PORT, OpenSSL::SSL::VERIFY_NONE, true, args){|server, port|
sock = TCPSocket.new("127.0.0.1", port)
ssl = OpenSSL::SSL::SSLSocket.new(sock)
ssl.sync_close = true
ssl.connect
ssl.syswrite("hello\n")
assert_equal("0" * 200, ssl.sysread(200))
assert_equal("0" * 200, ssl.sysread(200))
assert_equal("0" * 200, ssl.sysread(200))
assert_equal("0" * 200, ssl.sysread(200))
assert_equal("1" * 200, ssl.sysread(200))
ssl.close
}
end
def test_sysread_buffer
start_server(PORT, OpenSSL::SSL::VERIFY_NONE, true){|server, port|
sock = TCPSocket.new("127.0.0.1", port)
ssl = OpenSSL::SSL::SSLSocket.new(sock)
ssl.sync_close = true
ssl.connect
ITERATIONS.times{|i|
# the given buffer is cleared before concatenating.
# NB: SSLSocket#readpartial depends sysread.
str = "x" * i * 100 + "\n"
ssl.syswrite(str)
buf = "asdf"
assert_equal(buf.object_id, ssl.sysread(0, buf).object_id)
assert_equal("", buf)
buf = "asdf"
read = ssl.sysread(str.size, buf)
assert(!read.empty?)
assert_equal(buf.object_id, read.object_id)
assert_equal(str, buf)
ssl.syswrite(str)
read = ssl.sysread(str.size, nil)
assert(!read.empty?)
assert_equal(str, read)
}
ssl.close
}
end
def test_client_auth
vflag = OpenSSL::SSL::VERIFY_PEER|OpenSSL::SSL::VERIFY_FAIL_IF_NO_PEER_CERT
start_server(PORT, vflag, true){|server, port|
assert_raise(OpenSSL::SSL::SSLError){
sock = TCPSocket.new("127.0.0.1", port)
ssl = OpenSSL::SSL::SSLSocket.new(sock)
ssl.connect
}
ctx = OpenSSL::SSL::SSLContext.new
ctx.key = @cli_key
ctx.cert = @cli_cert
sock = TCPSocket.new("127.0.0.1", port)
ssl = OpenSSL::SSL::SSLSocket.new(sock, ctx)
ssl.sync_close = true
ssl.connect
ssl.puts("foo")
assert_equal("foo\n", ssl.gets)
ssl.close
called = nil
ctx = OpenSSL::SSL::SSLContext.new
ctx.client_cert_cb = Proc.new{ |sslconn|
called = true
[@cli_cert, @cli_key]
}
sock = TCPSocket.new("127.0.0.1", port)
ssl = OpenSSL::SSL::SSLSocket.new(sock, ctx)
ssl.sync_close = true
ssl.connect
assert(called)
ssl.puts("foo")
assert_equal("foo\n", ssl.gets)
ssl.close
}
end
def test_client_auth_with_server_store
vflag = OpenSSL::SSL::VERIFY_PEER
localcacert_file = Tempfile.open("cafile")
localcacert_file << @ca_cert.to_pem
localcacert_file.close
localcacert_path = localcacert_file.path
ssl_store = OpenSSL::X509::Store.new
ssl_store.purpose = OpenSSL::X509::PURPOSE_ANY
ssl_store.add_file(localcacert_path)
args = {}
args[:ctx_proc] = proc { |server_ctx|
server_ctx.cert = @svr_cert
server_ctx.key = @svr_key
server_ctx.verify_mode = vflag
server_ctx.cert_store = ssl_store
}
start_server(PORT, vflag, true, args){|server, port|
ctx = OpenSSL::SSL::SSLContext.new
ctx.cert = @cli_cert
ctx.key = @cli_key
sock = TCPSocket.new("127.0.0.1", port)
ssl = OpenSSL::SSL::SSLSocket.new(sock, ctx)
ssl.sync_close = true
ssl.connect
ssl.puts("foo")
assert_equal("foo\n", ssl.gets)
ssl.close
localcacert_file.unlink
}
end
def test_client_crl_with_server_store
vflag = OpenSSL::SSL::VERIFY_PEER
localcacert_file = Tempfile.open("cafile")
localcacert_file << @ca_cert.to_pem
localcacert_file.close
localcacert_path = localcacert_file.path
ssl_store = OpenSSL::X509::Store.new
ssl_store.purpose = OpenSSL::X509::PURPOSE_ANY
ssl_store.add_file(localcacert_path)
ssl_store.flags = OpenSSL::X509::V_FLAG_CRL_CHECK_ALL|OpenSSL::X509::V_FLAG_CRL_CHECK
crl = issue_crl([], 1, Time.now, Time.now+1600, [],
@cli_cert, @ca_key, OpenSSL::Digest::SHA1.new)
ssl_store.add_crl(OpenSSL::X509::CRL.new(crl.to_pem))
args = {}
args[:ctx_proc] = proc { |server_ctx|
server_ctx.cert = @svr_cert
server_ctx.key = @svr_key
server_ctx.verify_mode = vflag
server_ctx.cert_store = ssl_store
}
start_server(PORT, vflag, true, args){|s, p|
ctx = OpenSSL::SSL::SSLContext.new
ctx.cert = @cli_cert
ctx.key = @cli_key
assert_raise(OpenSSL::SSL::SSLError){
sock = TCPSocket.new("127.0.0.1", p)
ssl = OpenSSL::SSL::SSLSocket.new(sock, ctx)
ssl.sync_close = true
ssl.connect
ssl.close
}
localcacert_file.unlink
}
end
def test_starttls
start_server(PORT, OpenSSL::SSL::VERIFY_NONE, false){|server, port|
sock = TCPSocket.new("127.0.0.1", port)
ssl = OpenSSL::SSL::SSLSocket.new(sock)
ssl.sync_close = true
str = "x" * 1000 + "\n"
ITERATIONS.times{
ssl.puts(str)
assert_equal(str, ssl.gets)
}
starttls(ssl)
ITERATIONS.times{
ssl.puts(str)
assert_equal(str, ssl.gets)
}
ssl.close
}
end
def test_parallel
GC.start
start_server(PORT, OpenSSL::SSL::VERIFY_NONE, true){|server, port|
ssls = []
10.times{
sock = TCPSocket.new("127.0.0.1", port)
ssl = OpenSSL::SSL::SSLSocket.new(sock)
ssl.connect
ssl.sync_close = true
ssls << ssl
}
str = "x" * 1000 + "\n"
ITERATIONS.times{
ssls.each{|ssl|
ssl.puts(str)
assert_equal(str, ssl.gets)
}
}
ssls.each{|ssl| ssl.close }
}
end
def test_verify_result
start_server(PORT, OpenSSL::SSL::VERIFY_NONE, true){|server, port|
sock = TCPSocket.new("127.0.0.1", port)
ctx = OpenSSL::SSL::SSLContext.new
ctx.set_params
ssl = OpenSSL::SSL::SSLSocket.new(sock, ctx)
assert_raise(OpenSSL::SSL::SSLError){ ssl.connect }
assert_equal(OpenSSL::X509::V_ERR_SELF_SIGNED_CERT_IN_CHAIN, ssl.verify_result)
sock = TCPSocket.new("127.0.0.1", port)
ctx = OpenSSL::SSL::SSLContext.new
ctx.set_params(
:verify_callback => Proc.new do |preverify_ok, store_ctx|
store_ctx.error = OpenSSL::X509::V_OK
true
end
)
ssl = OpenSSL::SSL::SSLSocket.new(sock, ctx)
ssl.connect
assert_equal(OpenSSL::X509::V_OK, ssl.verify_result)
sock = TCPSocket.new("127.0.0.1", port)
ctx = OpenSSL::SSL::SSLContext.new
ctx.set_params(
:verify_callback => Proc.new do |preverify_ok, store_ctx|
store_ctx.error = OpenSSL::X509::V_ERR_APPLICATION_VERIFICATION
false
end
)
ssl = OpenSSL::SSL::SSLSocket.new(sock, ctx)
assert_raise(OpenSSL::SSL::SSLError){ ssl.connect }
assert_equal(OpenSSL::X509::V_ERR_APPLICATION_VERIFICATION, ssl.verify_result)
}
end
def test_extra_chain_cert
start_server(PORT, OpenSSL::SSL::VERIFY_PEER, true){|server, port|
sock = TCPSocket.new("127.0.0.1", port)
ctx = OpenSSL::SSL::SSLContext.new
ctx.set_params
ssl = OpenSSL::SSL::SSLSocket.new(sock, ctx)
assert_raise(OpenSSL::SSL::SSLError){ ssl.connect }
assert_equal(OpenSSL::X509::V_ERR_SELF_SIGNED_CERT_IN_CHAIN, ssl.verify_result)
}
# server returns a chain w/o root cert so the client verification fails
# with UNABLE_TO_GET_ISSUER_CERT_LOCALLY not SELF_SIGNED_CERT_IN_CHAIN.
args = {}
args[:ctx_proc] = proc { |server_ctx|
server_ctx.cert = @svr_cert
server_ctx.key = @svr_key
server_ctx.extra_chain_cert = [@svr_cert]
}
start_server(PORT, OpenSSL::SSL::VERIFY_PEER, true, args){|server, port|
sock = TCPSocket.new("127.0.0.1", port)
ctx = OpenSSL::SSL::SSLContext.new
ctx.set_params
ssl = OpenSSL::SSL::SSLSocket.new(sock, ctx)
assert_raise(OpenSSL::SSL::SSLError){ ssl.connect }
assert_equal(OpenSSL::X509::V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY, ssl.verify_result)
}
end
def test_client_ca
args = {}
vflag = OpenSSL::SSL::VERIFY_PEER|OpenSSL::SSL::VERIFY_FAIL_IF_NO_PEER_CERT
# client_ca as a cert
args[:ctx_proc] = proc { |server_ctx|
server_ctx.cert = @svr_cert
server_ctx.key = @svr_key
server_ctx.client_ca = @ca_cert
}
start_server(PORT, vflag, true, args){|server, port|
ctx = OpenSSL::SSL::SSLContext.new
ctx.key = @cli_key
ctx.cert = @cli_cert
sock = TCPSocket.new("127.0.0.1", port)
ssl = OpenSSL::SSL::SSLSocket.new(sock, ctx)
ssl.sync_close = true
ssl.connect
ssl.puts("foo")
assert_equal("foo\n", ssl.gets)
}
# client_ca as an array
args[:ctx_proc] = proc { |server_ctx|
server_ctx.cert = @svr_cert
server_ctx.key = @svr_key
server_ctx.client_ca = [@ca_cert, @svr_cert]
}
start_server(PORT, vflag, true, args){|server, port|
ctx = OpenSSL::SSL::SSLContext.new
ctx.key = @cli_key
ctx.cert = @cli_cert
sock = TCPSocket.new("127.0.0.1", port)
ssl = OpenSSL::SSL::SSLSocket.new(sock, ctx)
ssl.sync_close = true
ssl.connect
ssl.puts("foo")
assert_equal("foo\n", ssl.gets)
}
end
def test_sslctx_ssl_version_client
start_server(PORT, OpenSSL::SSL::VERIFY_NONE, true){|server, port|
sock = TCPSocket.new("127.0.0.1", port)
ctx = OpenSSL::SSL::SSLContext.new
ctx.set_params
ctx.verify_mode = OpenSSL::SSL::VERIFY_NONE
ctx.ssl_version = "TLSv1"
ssl = OpenSSL::SSL::SSLSocket.new(sock, ctx)
assert_nothing_raised do
ssl.connect
end
ssl.puts("hello TLSv1")
ssl.close
sock.close
#
sock = TCPSocket.new("127.0.0.1", port)
ctx.ssl_version = "SSLv3"
ssl = OpenSSL::SSL::SSLSocket.new(sock, ctx)
assert_nothing_raised do
ssl.connect
end
ssl.puts("hello SSLv3")
ssl.close
sock.close
#
sock = TCPSocket.new("127.0.0.1", port)
ctx.ssl_version = "SSLv3_server"
ssl = OpenSSL::SSL::SSLSocket.new(sock, ctx)
assert_raise(OpenSSL::SSL::SSLError) do
ssl.connect
end
sock.close
#
sock = TCPSocket.new("127.0.0.1", port)
ctx.ssl_version = "TLSv1_client"
ssl = OpenSSL::SSL::SSLSocket.new(sock, ctx)
assert_nothing_raised do
ssl.connect
end
ssl.puts("hello TLSv1_client")
ssl.close
sock.close
}
end
def test_sslctx_ssl_version
args = {}
args[:ctx_proc] = proc { |server_ctx|
server_ctx.ssl_version = "TLSv1"
}
start_server(PORT, OpenSSL::SSL::VERIFY_NONE, true, args){|server, port|
sock = TCPSocket.new("127.0.0.1", port)
ctx = OpenSSL::SSL::SSLContext.new
ctx.verify_mode = OpenSSL::SSL::VERIFY_NONE
ctx.ssl_version = "TLSv1"
ssl = OpenSSL::SSL::SSLSocket.new(sock, ctx)
assert_nothing_raised do
ssl.connect
end
ssl.puts("hello TLSv1")
ssl.close
sock.close
#
sock = TCPSocket.new("127.0.0.1", port)
ctx.ssl_version = "SSLv3"
ssl = OpenSSL::SSL::SSLSocket.new(sock, ctx)
assert_raise(OpenSSL::SSL::SSLError) do
ssl.connect
end
}
end
def test_verify_depth
vflag = OpenSSL::SSL::VERIFY_PEER|OpenSSL::SSL::VERIFY_FAIL_IF_NO_PEER_CERT
args = {}
# depth == 1 => OK
args[:ctx_proc] = proc { |server_ctx|
server_ctx.cert = @svr_cert
server_ctx.key = @svr_key
server_ctx.verify_mode = vflag
server_ctx.verify_depth = 1
}
start_server(PORT, vflag, true, args){|server, port|
ctx = OpenSSL::SSL::SSLContext.new
ctx.key = @cli_key
ctx.cert = @cli_cert
sock = TCPSocket.new("127.0.0.1", port)
ssl = OpenSSL::SSL::SSLSocket.new(sock, ctx)
assert_nothing_raised do
ssl.connect
end
ssl.close
}
# depth == 0 => error
error = nil
args[:ctx_proc] = proc { |server_ctx|
server_ctx.cert = @svr_cert
server_ctx.key = @svr_key
server_ctx.verify_mode = vflag
server_ctx.verify_depth = 0
server_ctx.verify_callback = proc { |preverify_ok, store_ctx|
error = store_ctx.error
preverify_ok
}
}
start_server(PORT, vflag, true, args){|server, port|
ctx = OpenSSL::SSL::SSLContext.new
ctx.key = @cli_key
ctx.cert = @cli_cert
sock = TCPSocket.new("127.0.0.1", port)
ssl = OpenSSL::SSL::SSLSocket.new(sock, ctx)
assert_raises(OpenSSL::SSL::SSLError) do
ssl.connect
end
ssl.close
}
assert_equal OpenSSL::X509::V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY, error
end
def test_sslctx_set_params
start_server(PORT, OpenSSL::SSL::VERIFY_NONE, true){|server, port|
sock = TCPSocket.new("127.0.0.1", port)
ctx = OpenSSL::SSL::SSLContext.new
ctx.set_params
assert_equal(OpenSSL::SSL::VERIFY_PEER, ctx.verify_mode)
assert_equal(OpenSSL::SSL::OP_ALL, ctx.options)
ciphers = ctx.ciphers
ciphers_versions = ciphers.collect{|_, v, _, _| v }
ciphers_names = ciphers.collect{|v, _, _, _| v }
assert(ciphers_names.all?{|v| /ADH/ !~ v })
assert(ciphers_versions.all?{|v| /SSLv2/ !~ v })
ssl = OpenSSL::SSL::SSLSocket.new(sock, ctx)
assert_raise(OpenSSL::SSL::SSLError){ ssl.connect }
assert_equal(OpenSSL::X509::V_ERR_SELF_SIGNED_CERT_IN_CHAIN, ssl.verify_result)
}
end
def test_sslctx_ciphers
c = OpenSSL::SSL::SSLContext.new
c.ciphers = 'DEFAULT'
default = c.ciphers
assert(default.size > 0)
c.ciphers = 'ALL'
all = c.ciphers
assert(all.size > 0)
c.ciphers = 'LOW'
low = c.ciphers
assert(low.size > 0)
c.ciphers = 'MEDIUM'
medium = c.ciphers
assert(medium.size > 0)
c.ciphers = 'HIGH'
high = c.ciphers
assert(high.size > 0)
c.ciphers = 'EXP'
exp = c.ciphers
assert(exp.size > 0)
# -
c.ciphers = 'ALL:-LOW'
assert_equal(all - low, c.ciphers)
c.ciphers = 'ALL:-MEDIUM'
assert_equal(all - medium, c.ciphers)
c.ciphers = 'ALL:-HIGH'
assert_equal(all - high, c.ciphers)
c.ciphers = 'ALL:-EXP'
assert_equal(all - exp, c.ciphers)
c.ciphers = 'ALL:-LOW:-MEDIUM'
assert_equal(all - low - medium, c.ciphers)
c.ciphers = 'ALL:-LOW:-MEDIUM:-HIGH'
assert_equal(all - low - medium - high, c.ciphers)
assert_raise(OpenSSL::SSL::SSLError) do
# should be empty for OpenSSL/0.9.8l. check OpenSSL changes if this test fail.
c.ciphers = 'ALL:-LOW:-MEDIUM:-HIGH:-EXP'
end
# !
c.ciphers = 'ALL:-LOW:LOW'
assert_equal(all.sort, c.ciphers.sort)
c.ciphers = 'ALL:!LOW:LOW'
assert_equal(all - low, c.ciphers)
c.ciphers = 'ALL:!LOW:+LOW'
assert_equal(all - low, c.ciphers)
# +
c.ciphers = 'HIGH:LOW:+LOW'
assert_equal(high + low, c.ciphers)
c.ciphers = 'HIGH:LOW:+HIGH'
assert_equal(low + high, c.ciphers)
# name+name
c.ciphers = 'RC4'
rc4 = c.ciphers
c.ciphers = 'RSA'
rsa = c.ciphers
c.ciphers = 'RC4+RSA'
assert_equal(rc4&rsa, c.ciphers)
c.ciphers = 'RSA+RC4'
assert_equal(rc4&rsa, c.ciphers)
c.ciphers = 'ALL:RSA+RC4'
assert_equal(all + ((rc4&rsa) - all), c.ciphers)
end
def test_sslctx_options
args = {}
args[:ctx_proc] = proc { |server_ctx|
# TLSv1 only
server_ctx.options = OpenSSL::SSL::OP_NO_SSLv2|OpenSSL::SSL::OP_NO_SSLv3
}
start_server(PORT, OpenSSL::SSL::VERIFY_NONE, true, args){|server, port|
sock = TCPSocket.new("127.0.0.1", port)
ctx = OpenSSL::SSL::SSLContext.new
ctx.set_params
ctx.verify_mode = OpenSSL::SSL::VERIFY_NONE
ctx.options = OpenSSL::SSL::OP_NO_TLSv1
ssl = OpenSSL::SSL::SSLSocket.new(sock, ctx)
assert_raise(OpenSSL::SSL::SSLError, Errno::ECONNRESET) do
ssl.connect
end
ssl.close
sock.close
#
sock = TCPSocket.new("127.0.0.1", port)
ctx = OpenSSL::SSL::SSLContext.new
ctx.set_params
ctx.verify_mode = OpenSSL::SSL::VERIFY_NONE
ctx.options = OpenSSL::SSL::OP_NO_SSLv3
ssl = OpenSSL::SSL::SSLSocket.new(sock, ctx)
assert_nothing_raised do
ssl.connect
end
ssl.close
sock.close
}
end
def test_post_connection_check
sslerr = OpenSSL::SSL::SSLError
start_server(PORT, OpenSSL::SSL::VERIFY_NONE, true){|server, port|
sock = TCPSocket.new("127.0.0.1", port)
ssl = OpenSSL::SSL::SSLSocket.new(sock)
ssl.connect
assert_raise(sslerr){ssl.post_connection_check("localhost.localdomain")}
assert_raise(sslerr){ssl.post_connection_check("127.0.0.1")}
assert(ssl.post_connection_check("localhost"))
assert_raise(sslerr){ssl.post_connection_check("foo.example.com")}
cert = ssl.peer_cert
assert(!OpenSSL::SSL.verify_certificate_identity(cert, "localhost.localdomain"))
assert(!OpenSSL::SSL.verify_certificate_identity(cert, "127.0.0.1"))
assert(OpenSSL::SSL.verify_certificate_identity(cert, "localhost"))
assert(!OpenSSL::SSL.verify_certificate_identity(cert, "foo.example.com"))
}
now = Time.now
exts = [
["keyUsage","keyEncipherment,digitalSignature",true],
["subjectAltName","DNS:localhost.localdomain",false],
["subjectAltName","IP:127.0.0.1",false],
]
@svr_cert = issue_cert(@svr, @svr_key, 4, now, now+1800, exts,
@ca_cert, @ca_key, OpenSSL::Digest::SHA1.new)
start_server(PORT, OpenSSL::SSL::VERIFY_NONE, true){|server, port|
sock = TCPSocket.new("127.0.0.1", port)
ssl = OpenSSL::SSL::SSLSocket.new(sock)
ssl.connect
assert(ssl.post_connection_check("localhost.localdomain"))
assert(ssl.post_connection_check("127.0.0.1"))
assert_raise(sslerr){ssl.post_connection_check("localhost")}
assert_raise(sslerr){ssl.post_connection_check("foo.example.com")}
cert = ssl.peer_cert
assert(OpenSSL::SSL.verify_certificate_identity(cert, "localhost.localdomain"))
assert(OpenSSL::SSL.verify_certificate_identity(cert, "127.0.0.1"))
assert(!OpenSSL::SSL.verify_certificate_identity(cert, "localhost"))
assert(!OpenSSL::SSL.verify_certificate_identity(cert, "foo.example.com"))
}
now = Time.now
exts = [
["keyUsage","keyEncipherment,digitalSignature",true],
["subjectAltName","DNS:*.localdomain",false],
]
@svr_cert = issue_cert(@svr, @svr_key, 5, now, now+1800, exts,
@ca_cert, @ca_key, OpenSSL::Digest::SHA1.new)
start_server(PORT, OpenSSL::SSL::VERIFY_NONE, true){|server, port|
sock = TCPSocket.new("127.0.0.1", port)
ssl = OpenSSL::SSL::SSLSocket.new(sock)
ssl.connect
assert(ssl.post_connection_check("localhost.localdomain"))
assert_raise(sslerr){ssl.post_connection_check("127.0.0.1")}
assert_raise(sslerr){ssl.post_connection_check("localhost")}
assert_raise(sslerr){ssl.post_connection_check("foo.example.com")}
cert = ssl.peer_cert
assert(OpenSSL::SSL.verify_certificate_identity(cert, "localhost.localdomain"))
assert(!OpenSSL::SSL.verify_certificate_identity(cert, "127.0.0.1"))
assert(!OpenSSL::SSL.verify_certificate_identity(cert, "localhost"))
assert(!OpenSSL::SSL.verify_certificate_identity(cert, "foo.example.com"))
}
end
def TODO_implement_SSLSession_test_client_session
last_session = nil
start_server(PORT, OpenSSL::SSL::VERIFY_NONE, true) do |server, port|
2.times do
sock = TCPSocket.new("127.0.0.1", port)
# Debian's openssl 0.9.8g-13 failed at assert(ssl.session_reused?),
# when use default SSLContext. [ruby-dev:36167]
ctx = OpenSSL::SSL::SSLContext.new("TLSv1")
ssl = OpenSSL::SSL::SSLSocket.new(sock, ctx)
ssl.sync_close = true
ssl.session = last_session if last_session
ssl.connect
session = ssl.session
if last_session
assert(ssl.session_reused?)
if session.respond_to?(:id)
assert_equal(session.id, last_session.id)
end
assert_equal(session.to_pem, last_session.to_pem)
assert_equal(session.to_der, last_session.to_der)
# Older version of OpenSSL may not be consistent. Look up which versions later.
assert_equal(session.to_text, last_session.to_text)
else
assert(!ssl.session_reused?)
end
last_session = session
str = "x" * 100 + "\n"
ssl.puts(str)
assert_equal(str, ssl.gets)
ssl.close
end
end
end
def TODO_implement_SSLSession_test_server_session
connections = 0
saved_session = nil
ctx_proc = Proc.new do |ctx, ssl|
# add test for session callbacks here
end
server_proc = Proc.new do |ctx, ssl|
session = ssl.session
stats = ctx.session_cache_stats
case connections
when 0
assert_equal(stats[:cache_num], 1)
assert_equal(stats[:cache_hits], 0)
assert_equal(stats[:cache_misses], 0)
assert(!ssl.session_reused?)
when 1
assert_equal(stats[:cache_num], 1)
assert_equal(stats[:cache_hits], 1)
assert_equal(stats[:cache_misses], 0)
assert(ssl.session_reused?)
ctx.session_remove(session)
saved_session = session
when 2
assert_equal(stats[:cache_num], 1)
assert_equal(stats[:cache_hits], 1)
assert_equal(stats[:cache_misses], 1)
assert(!ssl.session_reused?)
ctx.session_add(saved_session)
when 3
assert_equal(stats[:cache_num], 2)
assert_equal(stats[:cache_hits], 2)
assert_equal(stats[:cache_misses], 1)
assert(ssl.session_reused?)
ctx.flush_sessions(Time.now + 5000)
when 4
assert_equal(stats[:cache_num], 1)
assert_equal(stats[:cache_hits], 2)
assert_equal(stats[:cache_misses], 2)
assert(!ssl.session_reused?)
ctx.session_add(saved_session)
end
connections += 1
readwrite_loop(ctx, ssl)
end
first_session = nil
start_server(PORT, OpenSSL::SSL::VERIFY_NONE, true, :ctx_proc => ctx_proc, :server_proc => server_proc) do |server, port|
10.times do |i|
sock = TCPSocket.new("127.0.0.1", port)
ctx = OpenSSL::SSL::SSLContext.new
if defined?(OpenSSL::SSL::OP_NO_TICKET)
# disable RFC4507 support
ctx.options = OpenSSL::SSL::OP_NO_TICKET
end
ssl = OpenSSL::SSL::SSLSocket.new(sock, ctx)
ssl.sync_close = true
ssl.session = first_session if first_session
ssl.connect
session = ssl.session
if first_session
case i
when 1; assert(ssl.session_reused?)
when 2; assert(!ssl.session_reused?)
when 3; assert(ssl.session_reused?)
when 4; assert(!ssl.session_reused?)
when 5..10; assert(ssl.session_reused?)
end
end
first_session ||= session
str = "x" * 100 + "\n"
ssl.puts(str)
assert_equal(str, ssl.gets)
ssl.close
end
end
end
def test_tlsext_hostname
return unless OpenSSL::SSL::SSLSocket.instance_methods.include?("hostname")
ctx_proc = Proc.new do |ctx, ssl|
foo_ctx = ctx.dup
ctx.servername_cb = Proc.new do |ssl, hostname|
case hostname
when 'foo.example.com'
foo_ctx
when 'bar.example.com'
nil
else
raise "unknown hostname #{hostname.inspect}"
end
end
end
server_proc = Proc.new do |ctx, ssl|
readwrite_loop(ctx, ssl)
end
start_server(PORT, OpenSSL::SSL::VERIFY_NONE, true, :ctx_proc => ctx_proc, :server_proc => server_proc) do |server, port|
2.times do |i|
sock = TCPSocket.new("127.0.0.1", port)
ctx = OpenSSL::SSL::SSLContext.new
if defined?(OpenSSL::SSL::OP_NO_TICKET)
# disable RFC4507 support
ctx.options = OpenSSL::SSL::OP_NO_TICKET
end
ssl = OpenSSL::SSL::SSLSocket.new(sock, ctx)
ssl.sync_close = true
ssl.hostname = (i & 1 == 0) ? 'foo.example.com' : 'bar.example.com'
ssl.connect
str = "x" * 100 + "\n"
ssl.puts(str)
assert_equal(str, ssl.gets)
ssl.close
end
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/openssl/test_x509store.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/openssl/test_x509store.rb | begin
require "openssl"
require File.join(File.dirname(__FILE__), "utils.rb")
rescue LoadError
end
require "test/unit"
require "tempfile"
if defined?(OpenSSL)
class OpenSSL::TestX509Store < Test::Unit::TestCase
def setup
@rsa1024 = OpenSSL::TestUtils::TEST_KEY_RSA1024
@rsa2048 = OpenSSL::TestUtils::TEST_KEY_RSA2048
@dsa256 = OpenSSL::TestUtils::TEST_KEY_DSA256
@dsa512 = OpenSSL::TestUtils::TEST_KEY_DSA512
@ca1 = OpenSSL::X509::Name.parse("/DC=org/DC=ruby-lang/CN=CA1")
@ca2 = OpenSSL::X509::Name.parse("/DC=org/DC=ruby-lang/CN=CA2")
@ee1 = OpenSSL::X509::Name.parse("/DC=org/DC=ruby-lang/CN=EE1")
@ee2 = OpenSSL::X509::Name.parse("/DC=org/DC=ruby-lang/CN=EE2")
end
def teardown
end
def issue_cert(*args)
OpenSSL::TestUtils.issue_cert(*args)
end
def issue_crl(*args)
OpenSSL::TestUtils.issue_crl(*args)
end
def test_verify
now = Time.at(Time.now.to_i)
ca_exts = [
["basicConstraints","CA:TRUE",true],
["keyUsage","cRLSign,keyCertSign",true],
]
ee_exts = [
["keyUsage","keyEncipherment,digitalSignature",true],
]
ca1_cert = issue_cert(@ca1, @rsa2048, 1, now, now+3600, ca_exts,
nil, nil, OpenSSL::Digest::SHA1.new)
ca2_cert = issue_cert(@ca2, @rsa1024, 2, now, now+1800, ca_exts,
ca1_cert, @rsa2048, OpenSSL::Digest::SHA1.new)
ee1_cert = issue_cert(@ee1, @dsa256, 10, now, now+1800, ee_exts,
ca2_cert, @rsa1024, OpenSSL::Digest::SHA1.new)
ee2_cert = issue_cert(@ee2, @dsa512, 20, now, now+1800, ee_exts,
ca2_cert, @rsa1024, OpenSSL::Digest::SHA1.new)
ee3_cert = issue_cert(@ee2, @dsa512, 30, now-100, now-1, ee_exts,
ca2_cert, @rsa1024, OpenSSL::Digest::SHA1.new)
ee4_cert = issue_cert(@ee2, @dsa512, 40, now+1000, now+2000, ee_exts,
ca2_cert, @rsa1024, OpenSSL::Digest::SHA1.new)
revoke_info = []
crl1 = issue_crl(revoke_info, 1, now, now+1800, [],
ca1_cert, @rsa2048, OpenSSL::Digest::SHA1.new)
revoke_info = [ [2, now, 1], ]
crl1_2 = issue_crl(revoke_info, 2, now, now+1800, [],
ca1_cert, @rsa2048, OpenSSL::Digest::SHA1.new)
revoke_info = [ [20, now, 1], ]
crl2 = issue_crl(revoke_info, 1, now, now+1800, [],
ca2_cert, @rsa1024, OpenSSL::Digest::SHA1.new)
revoke_info = []
crl2_2 = issue_crl(revoke_info, 2, now-100, now-1, [],
ca2_cert, @rsa1024, OpenSSL::Digest::SHA1.new)
assert(true, ca1_cert.verify(ca1_cert.public_key)) # self signed
assert(true, ca2_cert.verify(ca1_cert.public_key)) # issued by ca1
assert(true, ee1_cert.verify(ca2_cert.public_key)) # issued by ca2
assert(true, ee2_cert.verify(ca2_cert.public_key)) # issued by ca2
assert(true, ee3_cert.verify(ca2_cert.public_key)) # issued by ca2
assert(true, crl1.verify(ca1_cert.public_key)) # issued by ca1
assert(true, crl1_2.verify(ca1_cert.public_key)) # issued by ca1
assert(true, crl2.verify(ca2_cert.public_key)) # issued by ca2
assert(true, crl2_2.verify(ca2_cert.public_key)) # issued by ca2
store = OpenSSL::X509::Store.new
assert_equal(false, store.verify(ca1_cert))
assert_not_equal(OpenSSL::X509::V_OK, store.error)
assert_equal(false, store.verify(ca2_cert))
assert_not_equal(OpenSSL::X509::V_OK, store.error)
store.add_cert(ca1_cert)
assert_equal(true, store.verify(ca2_cert))
assert_equal(OpenSSL::X509::V_OK, store.error)
assert_equal("ok", store.error_string)
chain = store.chain
assert_equal(2, chain.size)
assert_equal(@ca2.to_der, chain[0].subject.to_der)
assert_equal(@ca1.to_der, chain[1].subject.to_der)
store.purpose = OpenSSL::X509::PURPOSE_SSL_CLIENT
assert_equal(false, store.verify(ca2_cert))
assert_not_equal(OpenSSL::X509::V_OK, store.error)
store.purpose = OpenSSL::X509::PURPOSE_CRL_SIGN
assert_equal(true, store.verify(ca2_cert))
assert_equal(OpenSSL::X509::V_OK, store.error)
store.add_cert(ca2_cert)
store.purpose = OpenSSL::X509::PURPOSE_SSL_CLIENT
assert_equal(true, store.verify(ee1_cert))
assert_equal(true, store.verify(ee2_cert))
assert_equal(OpenSSL::X509::V_OK, store.error)
assert_equal("ok", store.error_string)
chain = store.chain
assert_equal(3, chain.size)
assert_equal(@ee2.to_der, chain[0].subject.to_der)
assert_equal(@ca2.to_der, chain[1].subject.to_der)
assert_equal(@ca1.to_der, chain[2].subject.to_der)
assert_equal(false, store.verify(ee3_cert))
assert_equal(OpenSSL::X509::V_ERR_CERT_HAS_EXPIRED, store.error)
assert_match(/expire/i, store.error_string)
assert_equal(false, store.verify(ee4_cert))
assert_equal(OpenSSL::X509::V_ERR_CERT_NOT_YET_VALID, store.error)
assert_match(/not yet valid/i, store.error_string)
store = OpenSSL::X509::Store.new
store.add_cert(ca1_cert)
store.add_cert(ca2_cert)
store.time = now + 1500
assert_equal(true, store.verify(ca1_cert))
assert_equal(true, store.verify(ca2_cert))
assert_equal(true, store.verify(ee4_cert))
store.time = now + 1900
assert_equal(true, store.verify(ca1_cert))
assert_equal(false, store.verify(ca2_cert))
assert_equal(OpenSSL::X509::V_ERR_CERT_HAS_EXPIRED, store.error)
assert_equal(false, store.verify(ee4_cert))
assert_equal(OpenSSL::X509::V_ERR_CERT_HAS_EXPIRED, store.error)
store.time = now + 4000
assert_equal(false, store.verify(ee1_cert))
assert_equal(OpenSSL::X509::V_ERR_CERT_HAS_EXPIRED, store.error)
assert_equal(false, store.verify(ee4_cert))
assert_equal(OpenSSL::X509::V_ERR_CERT_HAS_EXPIRED, store.error)
# the underlying X509 struct caches the result of the last
# verification for signature and not-before. so the following code
# rebuilds new objects to avoid site effect.
store.time = Time.now - 4000
assert_equal(false, store.verify(OpenSSL::X509::Certificate.new(ca2_cert)))
assert_equal(OpenSSL::X509::V_ERR_CERT_NOT_YET_VALID, store.error)
assert_equal(false, store.verify(OpenSSL::X509::Certificate.new(ee1_cert)))
assert_equal(OpenSSL::X509::V_ERR_CERT_NOT_YET_VALID, store.error)
return unless defined?(OpenSSL::X509::V_FLAG_CRL_CHECK)
store = OpenSSL::X509::Store.new
store.purpose = OpenSSL::X509::PURPOSE_ANY
store.flags = OpenSSL::X509::V_FLAG_CRL_CHECK
store.add_cert(ca1_cert)
store.add_crl(crl1) # revoke no cert
store.add_crl(crl2) # revoke ee2_cert
assert_equal(true, store.verify(ca1_cert))
assert_equal(true, store.verify(ca2_cert))
assert_equal(true, store.verify(ee1_cert, [ca2_cert]))
assert_equal(false, store.verify(ee2_cert, [ca2_cert]))
store = OpenSSL::X509::Store.new
store.purpose = OpenSSL::X509::PURPOSE_ANY
store.flags = OpenSSL::X509::V_FLAG_CRL_CHECK
store.add_cert(ca1_cert)
store.add_crl(crl1_2) # revoke ca2_cert
store.add_crl(crl2) # revoke ee2_cert
assert_equal(true, store.verify(ca1_cert))
assert_equal(false, store.verify(ca2_cert))
assert_equal(true, store.verify(ee1_cert, [ca2_cert]),
"This test is expected to be success with OpenSSL 0.9.7c or later.")
assert_equal(false, store.verify(ee2_cert, [ca2_cert]))
store.flags =
OpenSSL::X509::V_FLAG_CRL_CHECK|OpenSSL::X509::V_FLAG_CRL_CHECK_ALL
assert_equal(true, store.verify(ca1_cert))
assert_equal(false, store.verify(ca2_cert))
assert_equal(false, store.verify(ee1_cert, [ca2_cert]))
assert_equal(false, store.verify(ee2_cert, [ca2_cert]))
store = OpenSSL::X509::Store.new
store.purpose = OpenSSL::X509::PURPOSE_ANY
store.flags =
OpenSSL::X509::V_FLAG_CRL_CHECK|OpenSSL::X509::V_FLAG_CRL_CHECK_ALL
store.add_cert(ca1_cert)
store.add_cert(ca2_cert)
store.add_crl(crl1)
store.add_crl(crl2_2) # issued by ca2 but expired.
assert_equal(true, store.verify(ca1_cert))
assert_equal(true, store.verify(ca2_cert))
assert_equal(false, store.verify(ee1_cert))
assert_equal(OpenSSL::X509::V_ERR_CRL_HAS_EXPIRED, store.error)
assert_equal(false, store.verify(ee2_cert))
end
def test_set_errors
now = Time.now
ca1_cert = issue_cert(@ca1, @rsa2048, 1, now, now+3600, [],
nil, nil, OpenSSL::Digest::SHA1.new)
store = OpenSSL::X509::Store.new
store.add_cert(ca1_cert)
assert_raise(OpenSSL::X509::StoreError){
store.add_cert(ca1_cert) # add same certificate twice
}
revoke_info = []
crl1 = issue_crl(revoke_info, 1, now, now+1800, [],
ca1_cert, @rsa2048, OpenSSL::Digest::SHA1.new)
revoke_info = [ [2, now, 1], ]
crl2 = issue_crl(revoke_info, 2, now+1800, now+3600, [],
ca1_cert, @rsa2048, OpenSSL::Digest::SHA1.new)
store.add_crl(crl1)
assert_raise(OpenSSL::X509::StoreError){
store.add_crl(crl2) # add CRL issued by same CA twice.
}
end
def test_add_file
ca1_cert = <<END
-----BEGIN CERTIFICATE-----
MIIBzzCCATigAwIBAgIBATANBgkqhkiG9w0BAQUFADANMQswCQYDVQQDDAJjYTAe
Fw0wOTA1MjIxMDE5MjNaFw0xNDA1MjExMDE5MjNaMA0xCzAJBgNVBAMMAmNhMIGf
MA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDcTL520vsbXHXPfkHKrcgWbk2zVf0y
oK7bPg06kjCghs8KYsi9b/tT9KpkpejD0KucDBSmDILD3PvIWrNFcBRWf6ZC5vA5
YuF6ueATuFhsXjUFuNLqyPcIX+XrOQmXgjiyO9nc5vzQwWRRhdyyT8DgCRUD/yHW
pjD2ZEGIAVLY/wIDAQABoz8wPTAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBQf
923P/SgiCcbiN20bbmuFM6SLxzALBgNVHQ8EBAMCAQYwDQYJKoZIhvcNAQEFBQAD
gYEAE0CpCo8MxhfUNWMHF5GsGEG2+1LdE+aUX7gSb6d4vn1WjusrM2FoOFTomt32
YPqJwMEbcqILq2v9Kkao4QNJRlK+z1xpRDnt1iBrHdXrYJFvYnfMqv3z7XAFPfQZ
yMP+P2sR0jPzy4UNZfDIMmMUqQdhkz7onKWOGjXwLEtkCMs=
-----END CERTIFICATE-----
END
f = Tempfile.new("ca1_cert")
f << ca1_cert
f.close
store = OpenSSL::X509::Store.new
store.add_file(f.path)
assert_equal(true, store.verify(OpenSSL::X509::Certificate.new(ca1_cert)))
f.unlink
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/openssl/test_x509req.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/openssl/test_x509req.rb | begin
require "openssl"
require File.join(File.dirname(__FILE__), "utils.rb")
rescue LoadError
end
require "test/unit"
if defined?(OpenSSL)
class OpenSSL::TestX509Request < Test::Unit::TestCase
def setup
@rsa1024 = OpenSSL::TestUtils::TEST_KEY_RSA1024
@rsa2048 = OpenSSL::TestUtils::TEST_KEY_RSA2048
@dsa256 = OpenSSL::TestUtils::TEST_KEY_DSA256
@dsa512 = OpenSSL::TestUtils::TEST_KEY_DSA512
@dn = OpenSSL::X509::Name.parse("/DC=org/DC=ruby-lang/CN=GOTOU Yuuzou")
end
def issue_csr(ver, dn, key, digest)
req = OpenSSL::X509::Request.new
req.version = ver
req.subject = dn
req.public_key = key.public_key
req.sign(key, digest)
req
end
def test_public_key
req = issue_csr(0, @dn, @rsa1024, OpenSSL::Digest::SHA1.new)
assert_equal(@rsa1024.public_key.to_der, req.public_key.to_der)
req = OpenSSL::X509::Request.new(req.to_der)
assert_equal(@rsa1024.public_key.to_der, req.public_key.to_der)
req = issue_csr(0, @dn, @dsa512, OpenSSL::Digest::DSS1.new)
assert_equal(@dsa512.public_key.to_der, req.public_key.to_der)
req = OpenSSL::X509::Request.new(req.to_der)
assert_equal(@dsa512.public_key.to_der, req.public_key.to_der)
end
def test_version
req = issue_csr(0, @dn, @rsa1024, OpenSSL::Digest::SHA1.new)
assert_equal(0, req.version)
req = OpenSSL::X509::Request.new(req.to_der)
assert_equal(0, req.version)
req = issue_csr(1, @dn, @rsa1024, OpenSSL::Digest::SHA1.new)
assert_equal(1, req.version)
req = OpenSSL::X509::Request.new(req.to_der)
assert_equal(1, req.version)
end
def test_subject
req = issue_csr(0, @dn, @rsa1024, OpenSSL::Digest::SHA1.new)
assert_equal(@dn.to_der, req.subject.to_der)
req = OpenSSL::X509::Request.new(req.to_der)
assert_equal(@dn.to_der, req.subject.to_der)
end
def create_ext_req(exts)
ef = OpenSSL::X509::ExtensionFactory.new
exts = exts.collect{|e| ef.create_extension(*e) }
return OpenSSL::ASN1::Set([OpenSSL::ASN1::Sequence(exts)])
end
def get_ext_req(ext_req_value)
set = OpenSSL::ASN1.decode(ext_req_value)
seq = set.value[0]
seq.value.collect{|asn1ext|
OpenSSL::X509::Extension.new(asn1ext).to_a
}
end
def test_attr
exts = [
["keyUsage", "Digital Signature, Key Encipherment", true],
["subjectAltName", "email:gotoyuzo@ruby-lang.org", false],
]
attrval = create_ext_req(exts)
attrs = [
OpenSSL::X509::Attribute.new("extReq", attrval),
OpenSSL::X509::Attribute.new("msExtReq", attrval),
]
req0 = issue_csr(0, @dn, @rsa1024, OpenSSL::Digest::SHA1.new)
attrs.each{|attr| req0.add_attribute(attr) }
req1 = issue_csr(0, @dn, @rsa1024, OpenSSL::Digest::SHA1.new)
req1.attributes = attrs
assert_equal(req0.to_der, req1.to_der)
attrs = req0.attributes
assert_equal(2, attrs.size)
assert_equal("extReq", attrs[0].oid)
assert_equal("msExtReq", attrs[1].oid)
assert_equal(exts, get_ext_req(attrs[0].value))
assert_equal(exts, get_ext_req(attrs[1].value))
req = OpenSSL::X509::Request.new(req0.to_der)
attrs = req.attributes
assert_equal(2, attrs.size)
assert_equal("extReq", attrs[0].oid)
assert_equal("msExtReq", attrs[1].oid)
assert_equal(exts, get_ext_req(attrs[0].value))
assert_equal(exts, get_ext_req(attrs[1].value))
end
def test_sign_and_verify
req = issue_csr(0, @dn, @rsa1024, OpenSSL::Digest::SHA1.new)
assert_equal(true, req.verify(@rsa1024))
assert_equal(false, req.verify(@rsa2048))
assert_equal(false, req.verify(@dsa256))
assert_equal(false, req.verify(@dsa512))
req.version = 1
assert_equal(false, req.verify(@rsa1024))
req = issue_csr(0, @dn, @rsa2048, OpenSSL::Digest::MD5.new)
assert_equal(false, req.verify(@rsa1024))
assert_equal(true, req.verify(@rsa2048))
assert_equal(false, req.verify(@dsa256))
assert_equal(false, req.verify(@dsa512))
req.subject = OpenSSL::X509::Name.parse("/C=JP/CN=FooBar")
assert_equal(false, req.verify(@rsa2048))
req = issue_csr(0, @dn, @dsa512, OpenSSL::Digest::DSS1.new)
assert_equal(false, req.verify(@rsa1024))
assert_equal(false, req.verify(@rsa2048))
assert_equal(false, req.verify(@dsa256))
assert_equal(true, req.verify(@dsa512))
req.public_key = @rsa1024.public_key
assert_equal(false, req.verify(@dsa512))
assert_raise(OpenSSL::X509::RequestError){
issue_csr(0, @dn, @rsa1024, OpenSSL::Digest::DSS1.new) }
assert_raise(OpenSSL::X509::RequestError){
issue_csr(0, @dn, @dsa512, OpenSSL::Digest::SHA1.new) }
assert_raise(OpenSSL::X509::RequestError){
issue_csr(0, @dn, @dsa512, OpenSSL::Digest::MD5.new) }
end
def test_create_from_pem
req = <<END
-----BEGIN CERTIFICATE REQUEST-----
MIIBVTCBvwIBADAWMRQwEgYDVQQDDAsxOTIuMTY4LjAuNDCBnzANBgkqhkiG9w0B
AQEFAAOBjQAwgYkCgYEA0oTTzFLydOTVtBpNdYl4S0356AysVkHlqD/tNEMxQT0l
dXdNoDKb/3TfM5WMciNxBb8rImJ51vEIf6WaWvPbaawcmhNWA9JmhMIeFCdeXyu/
XEjiiEOL4MkWf6qfsu6VoPr2YSnR0iiWLgWcnRPuy84+PE1XPPl1qGDA0apWJ9kC
AwEAAaAAMA0GCSqGSIb3DQEBBAUAA4GBAKdlyDzVrXRLkPdukQUTTy6uwhv35SKL
FfiKDrHtnFYd7VbynQ1sRre5CknuRrm+E7aEJEwpz6MS+6nqmQ6JwGcm/hlZM/m7
DVD201pI3p6LIxaRyXE20RYTp0Jj6jv+tNFd0wjVlzgStmcplNo8hu6Dtp1gKETW
qL7M4i48FXHn
-----END CERTIFICATE REQUEST-----
END
req = OpenSSL::X509::Request.new(req)
assert_equal(0, req.version)
assert_equal(OpenSSL::X509::Name.parse("/CN=192.168.0.4").to_der, req.subject.to_der)
end
def test_create_to_pem
req_s = <<END
-----BEGIN CERTIFICATE REQUEST-----
MIIBVTCBvwIBADAWMRQwEgYDVQQDDAsxOTIuMTY4LjAuNDCBnzANBgkqhkiG9w0B
AQEFAAOBjQAwgYkCgYEA0oTTzFLydOTVtBpNdYl4S0356AysVkHlqD/tNEMxQT0l
dXdNoDKb/3TfM5WMciNxBb8rImJ51vEIf6WaWvPbaawcmhNWA9JmhMIeFCdeXyu/
XEjiiEOL4MkWf6qfsu6VoPr2YSnR0iiWLgWcnRPuy84+PE1XPPl1qGDA0apWJ9kC
AwEAAaAAMA0GCSqGSIb3DQEBBAUAA4GBAKdlyDzVrXRLkPdukQUTTy6uwhv35SKL
FfiKDrHtnFYd7VbynQ1sRre5CknuRrm+E7aEJEwpz6MS+6nqmQ6JwGcm/hlZM/m7
DVD201pI3p6LIxaRyXE20RYTp0Jj6jv+tNFd0wjVlzgStmcplNo8hu6Dtp1gKETW
qL7M4i48FXHn
-----END CERTIFICATE REQUEST-----
END
req = OpenSSL::X509::Request.new(req_s)
assert_equal(req_s.gsub(/[\r\n]/, ''), req.to_pem.gsub(/[\r\n]/, ''))
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/openssl/test_hmac.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/openssl/test_hmac.rb | begin
require "openssl"
rescue LoadError
end
require "test/unit"
if defined?(OpenSSL)
class OpenSSL::TestHMAC < Test::Unit::TestCase
def setup
@digest = OpenSSL::Digest::MD5.new
@key = "KEY"
@data = "DATA"
@h1 = OpenSSL::HMAC.new(@key, @digest)
@h2 = OpenSSL::HMAC.new(@key, @digest)
end
def teardown
end
def test_hmac
@h1.update(@data)
assert_equal(OpenSSL::HMAC.digest(@digest, @key, @data), @h1.digest, "digest")
assert_equal(OpenSSL::HMAC.hexdigest(@digest, @key, @data), @h1.hexdigest, "hexdigest")
end
def test_dup
@h1.update(@data)
h = @h1.dup
assert_equal(@h1.digest, h.digest, "dup digest")
end
def test_sha256
digest256 = OpenSSL::Digest::Digest.new("sha256")
assert_equal(
"\210\236-\3270\331Yq\265\177sE\266\231hXa\332\250\026\235O&c*\307\001\227~\260n\362",
OpenSSL::HMAC.digest(digest256, 'blah', "blah"))
assert_equal(
"889e2dd730d95971b57f7345b699685861daa8169d4f26632ac701977eb06ef2",
OpenSSL::HMAC.hexdigest(digest256, 'blah', "blah"))
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/openssl/test_asn1.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/openssl/test_asn1.rb | begin
require "openssl"
require File.join(File.dirname(__FILE__), "utils.rb")
rescue LoadError
end
require 'test/unit'
class OpenSSL::TestASN1 < Test::Unit::TestCase
def test_decode
subj = OpenSSL::X509::Name.parse("/DC=org/DC=ruby-lang/CN=TestCA")
key = OpenSSL::TestUtils::TEST_KEY_RSA1024
now = Time.at(Time.now.to_i) # suppress usec
s = 0xdeadbeafdeadbeafdeadbeafdeadbeaf
exts = [
["basicConstraints","CA:TRUE,pathlen:1",true],
["keyUsage","keyCertSign, cRLSign",true],
["subjectKeyIdentifier","hash",false],
]
dgst = OpenSSL::Digest::SHA1.new
cert = OpenSSL::TestUtils.issue_cert(
subj, key, s, now, now+3600, exts, nil, nil, dgst)
asn1 = OpenSSL::ASN1.decode(cert)
assert_equal(OpenSSL::ASN1::Sequence, asn1.class)
assert_equal(3, asn1.value.size)
tbs_cert, sig_alg, sig_val = *asn1.value
assert_equal(OpenSSL::ASN1::Sequence, tbs_cert.class)
assert_equal(8, tbs_cert.value.size)
version = tbs_cert.value[0]
assert_equal(:CONTEXT_SPECIFIC, version.tag_class)
assert_equal(0, version.tag)
assert_equal(1, version.value.size)
assert_equal(OpenSSL::ASN1::Integer, version.value[0].class)
assert_equal(2, version.value[0].value)
serial = tbs_cert.value[1]
assert_equal(OpenSSL::ASN1::Integer, serial.class)
assert_equal(0xdeadbeafdeadbeafdeadbeafdeadbeaf, serial.value)
sig = tbs_cert.value[2]
assert_equal(OpenSSL::ASN1::Sequence, sig.class)
assert_equal(2, sig.value.size)
assert_equal(OpenSSL::ASN1::ObjectId, sig.value[0].class)
assert_equal("1.2.840.113549.1.1.5", sig.value[0].oid)
assert_equal(OpenSSL::ASN1::Null, sig.value[1].class)
dn = tbs_cert.value[3] # issuer
assert_equal(subj.hash, OpenSSL::X509::Name.new(dn).hash)
assert_equal(OpenSSL::ASN1::Sequence, dn.class)
assert_equal(3, dn.value.size)
assert_equal(OpenSSL::ASN1::Set, dn.value[0].class)
assert_equal(OpenSSL::ASN1::Set, dn.value[1].class)
assert_equal(OpenSSL::ASN1::Set, dn.value[2].class)
assert_equal(1, dn.value[0].value.size)
assert_equal(1, dn.value[1].value.size)
assert_equal(1, dn.value[2].value.size)
assert_equal(OpenSSL::ASN1::Sequence, dn.value[0].value[0].class)
assert_equal(OpenSSL::ASN1::Sequence, dn.value[1].value[0].class)
assert_equal(OpenSSL::ASN1::Sequence, dn.value[2].value[0].class)
assert_equal(2, dn.value[0].value[0].value.size)
assert_equal(2, dn.value[1].value[0].value.size)
assert_equal(2, dn.value[2].value[0].value.size)
oid, value = *dn.value[0].value[0].value
assert_equal(OpenSSL::ASN1::ObjectId, oid.class)
assert_equal("0.9.2342.19200300.100.1.25", oid.oid)
assert_equal(OpenSSL::ASN1::IA5String, value.class)
assert_equal("org", value.value)
oid, value = *dn.value[1].value[0].value
assert_equal(OpenSSL::ASN1::ObjectId, oid.class)
assert_equal("0.9.2342.19200300.100.1.25", oid.oid)
assert_equal(OpenSSL::ASN1::IA5String, value.class)
assert_equal("ruby-lang", value.value)
oid, value = *dn.value[2].value[0].value
assert_equal(OpenSSL::ASN1::ObjectId, oid.class)
assert_equal("2.5.4.3", oid.oid)
assert_equal(OpenSSL::ASN1::UTF8String, value.class)
assert_equal("TestCA", value.value)
validity = tbs_cert.value[4]
assert_equal(OpenSSL::ASN1::Sequence, validity.class)
assert_equal(2, validity.value.size)
assert_equal(OpenSSL::ASN1::UTCTime, validity.value[0].class)
assert_equal(now, validity.value[0].value)
assert_equal(OpenSSL::ASN1::UTCTime, validity.value[1].class)
assert_equal(now+3600, validity.value[1].value)
dn = tbs_cert.value[5] # subject
assert_equal(subj.hash, OpenSSL::X509::Name.new(dn).hash)
assert_equal(OpenSSL::ASN1::Sequence, dn.class)
assert_equal(3, dn.value.size)
assert_equal(OpenSSL::ASN1::Set, dn.value[0].class)
assert_equal(OpenSSL::ASN1::Set, dn.value[1].class)
assert_equal(OpenSSL::ASN1::Set, dn.value[2].class)
assert_equal(1, dn.value[0].value.size)
assert_equal(1, dn.value[1].value.size)
assert_equal(1, dn.value[2].value.size)
assert_equal(OpenSSL::ASN1::Sequence, dn.value[0].value[0].class)
assert_equal(OpenSSL::ASN1::Sequence, dn.value[1].value[0].class)
assert_equal(OpenSSL::ASN1::Sequence, dn.value[2].value[0].class)
assert_equal(2, dn.value[0].value[0].value.size)
assert_equal(2, dn.value[1].value[0].value.size)
assert_equal(2, dn.value[2].value[0].value.size)
oid, value = *dn.value[0].value[0].value
assert_equal(OpenSSL::ASN1::ObjectId, oid.class)
assert_equal("0.9.2342.19200300.100.1.25", oid.oid)
assert_equal(OpenSSL::ASN1::IA5String, value.class)
assert_equal("org", value.value)
oid, value = *dn.value[1].value[0].value
assert_equal(OpenSSL::ASN1::ObjectId, oid.class)
assert_equal("0.9.2342.19200300.100.1.25", oid.oid)
assert_equal(OpenSSL::ASN1::IA5String, value.class)
assert_equal("ruby-lang", value.value)
oid, value = *dn.value[2].value[0].value
assert_equal(OpenSSL::ASN1::ObjectId, oid.class)
assert_equal("2.5.4.3", oid.oid)
assert_equal(OpenSSL::ASN1::UTF8String, value.class)
assert_equal("TestCA", value.value)
pkey = tbs_cert.value[6]
assert_equal(OpenSSL::ASN1::Sequence, pkey.class)
assert_equal(2, pkey.value.size)
assert_equal(OpenSSL::ASN1::Sequence, pkey.value[0].class)
assert_equal(2, pkey.value[0].value.size)
assert_equal(OpenSSL::ASN1::ObjectId, pkey.value[0].value[0].class)
assert_equal("1.2.840.113549.1.1.1", pkey.value[0].value[0].oid)
assert_equal(OpenSSL::ASN1::BitString, pkey.value[1].class)
assert_equal(0, pkey.value[1].unused_bits)
spkey = OpenSSL::ASN1.decode(pkey.value[1].value)
assert_equal(OpenSSL::ASN1::Sequence, spkey.class)
assert_equal(2, spkey.value.size)
assert_equal(OpenSSL::ASN1::Integer, spkey.value[0].class)
assert_equal(143085709396403084580358323862163416700436550432664688288860593156058579474547937626086626045206357324274536445865308750491138538454154232826011964045825759324933943290377903384882276841880081931690695505836279972214003660451338124170055999155993192881685495391496854691199517389593073052473319331505702779271, spkey.value[0].value)
assert_equal(OpenSSL::ASN1::Integer, spkey.value[1].class)
assert_equal(65537, spkey.value[1].value)
extensions = tbs_cert.value[7]
assert_equal(:CONTEXT_SPECIFIC, extensions.tag_class)
assert_equal(3, extensions.tag)
assert_equal(1, extensions.value.size)
assert_equal(OpenSSL::ASN1::Sequence, extensions.value[0].class)
assert_equal(3, extensions.value[0].value.size)
ext = extensions.value[0].value[0] # basicConstraints
assert_equal(OpenSSL::ASN1::Sequence, ext.class)
assert_equal(3, ext.value.size)
assert_equal(OpenSSL::ASN1::ObjectId, ext.value[0].class)
assert_equal("2.5.29.19", ext.value[0].oid)
assert_equal(OpenSSL::ASN1::Boolean, ext.value[1].class)
assert_equal(true, ext.value[1].value)
assert_equal(OpenSSL::ASN1::OctetString, ext.value[2].class)
extv = OpenSSL::ASN1.decode(ext.value[2].value)
assert_equal(OpenSSL::ASN1::Sequence, extv.class)
assert_equal(2, extv.value.size)
assert_equal(OpenSSL::ASN1::Boolean, extv.value[0].class)
assert_equal(true, extv.value[0].value)
assert_equal(OpenSSL::ASN1::Integer, extv.value[1].class)
assert_equal(1, extv.value[1].value)
ext = extensions.value[0].value[1] # keyUsage
assert_equal(OpenSSL::ASN1::Sequence, ext.class)
assert_equal(3, ext.value.size)
assert_equal(OpenSSL::ASN1::ObjectId, ext.value[0].class)
assert_equal("2.5.29.15", ext.value[0].oid)
assert_equal(OpenSSL::ASN1::Boolean, ext.value[1].class)
assert_equal(true, ext.value[1].value)
assert_equal(OpenSSL::ASN1::OctetString, ext.value[2].class)
extv = OpenSSL::ASN1.decode(ext.value[2].value)
assert_equal(OpenSSL::ASN1::BitString, extv.class)
str = "\000"; str[0] = 0b00000110
assert_equal(str, extv.value)
ext = extensions.value[0].value[2] # subjetKeyIdentifier
assert_equal(OpenSSL::ASN1::Sequence, ext.class)
assert_equal(2, ext.value.size)
assert_equal(OpenSSL::ASN1::ObjectId, ext.value[0].class)
assert_equal("2.5.29.14", ext.value[0].oid)
assert_equal(OpenSSL::ASN1::OctetString, ext.value[1].class)
extv = OpenSSL::ASN1.decode(ext.value[1].value)
assert_equal(OpenSSL::ASN1::OctetString, extv.class)
sha1 = OpenSSL::Digest::SHA1.new
sha1.update(pkey.value[1].value)
assert_equal(sha1.digest, extv.value)
assert_equal(OpenSSL::ASN1::Sequence, sig_alg.class)
assert_equal(2, sig_alg.value.size)
assert_equal(OpenSSL::ASN1::ObjectId, pkey.value[0].value[0].class)
assert_equal("1.2.840.113549.1.1.1", pkey.value[0].value[0].oid)
assert_equal(OpenSSL::ASN1::Null, pkey.value[0].value[1].class)
assert_equal(OpenSSL::ASN1::BitString, sig_val.class)
cululated_sig = key.sign(OpenSSL::Digest::SHA1.new, tbs_cert.to_der)
assert_equal(cululated_sig, sig_val.value)
end
end if defined?(OpenSSL)
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/openssl/test_pkcs7.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/openssl/test_pkcs7.rb | begin
require "openssl"
require File.join(File.dirname(__FILE__), "utils.rb")
rescue LoadError
end
require "test/unit"
if defined?(OpenSSL)
class OpenSSL::TestPKCS7 < Test::Unit::TestCase
def setup
@rsa1024 = OpenSSL::TestUtils::TEST_KEY_RSA1024
@rsa2048 = OpenSSL::TestUtils::TEST_KEY_RSA2048
ca = OpenSSL::X509::Name.parse("/DC=org/DC=ruby-lang/CN=CA")
ee1 = OpenSSL::X509::Name.parse("/DC=org/DC=ruby-lang/CN=EE1")
ee2 = OpenSSL::X509::Name.parse("/DC=org/DC=ruby-lang/CN=EE2")
now = Time.now
ca_exts = [
["basicConstraints","CA:TRUE",true],
["keyUsage","keyCertSign, cRLSign",true],
["subjectKeyIdentifier","hash",false],
["authorityKeyIdentifier","keyid:always",false],
]
@ca_cert = issue_cert(ca, @rsa2048, 1, Time.now, Time.now+3600, ca_exts,
nil, nil, OpenSSL::Digest::SHA1.new)
ee_exts = [
["keyUsage","Non Repudiation, Digital Signature, Key Encipherment",true],
["authorityKeyIdentifier","keyid:always",false],
["extendedKeyUsage","clientAuth, emailProtection, codeSigning",false],
["nsCertType","client,email",false],
]
@ee1_cert = issue_cert(ee1, @rsa1024, 2, Time.now, Time.now+1800, ee_exts,
@ca_cert, @rsa2048, OpenSSL::Digest::SHA1.new)
@ee2_cert = issue_cert(ee2, @rsa1024, 3, Time.now, Time.now+1800, ee_exts,
@ca_cert, @rsa2048, OpenSSL::Digest::SHA1.new)
end
def issue_cert(*args)
OpenSSL::TestUtils.issue_cert(*args)
end
def test_signed
store = OpenSSL::X509::Store.new
store.add_cert(@ca_cert)
ca_certs = [@ca_cert]
data = "aaaaa\r\nbbbbb\r\nccccc\r\n"
tmp = OpenSSL::PKCS7.sign(@ee1_cert, @rsa1024, data, ca_certs)
p7 = OpenSSL::PKCS7.new(tmp.to_der)
certs = p7.certificates
signers = p7.signers
assert(p7.verify([], store))
assert_equal(data, p7.data)
assert_equal(2, certs.size)
assert_equal(@ee1_cert.subject.to_s, certs[0].subject.to_s)
assert_equal(@ca_cert.subject.to_s, certs[1].subject.to_s)
assert_equal(1, signers.size)
assert_equal(@ee1_cert.serial, signers[0].serial)
assert_equal(@ee1_cert.issuer.to_s, signers[0].issuer.to_s)
# Normaly OpenSSL tries to translate the supplied content into canonical
# MIME format (e.g. a newline character is converted into CR+LF).
# If the content is a binary, PKCS7::BINARY flag should be used.
data = "aaaaa\nbbbbb\nccccc\n"
flag = OpenSSL::PKCS7::BINARY
tmp = OpenSSL::PKCS7.sign(@ee1_cert, @rsa1024, data, ca_certs, flag)
p7 = OpenSSL::PKCS7.new(tmp.to_der)
certs = p7.certificates
signers = p7.signers
assert(p7.verify([], store))
assert_equal(data, p7.data)
assert_equal(2, certs.size)
assert_equal(@ee1_cert.subject.to_s, certs[0].subject.to_s)
assert_equal(@ca_cert.subject.to_s, certs[1].subject.to_s)
assert_equal(1, signers.size)
assert_equal(@ee1_cert.serial, signers[0].serial)
assert_equal(@ee1_cert.issuer.to_s, signers[0].issuer.to_s)
# A signed-data which have multiple signatures can be created
# through the following steps.
# 1. create two signed-data
# 2. copy signerInfo and certificate from one to another
tmp1 = OpenSSL::PKCS7.sign(@ee1_cert, @rsa1024, data, [], flag)
tmp2 = OpenSSL::PKCS7.sign(@ee2_cert, @rsa1024, data, [], flag)
tmp1.add_signer(tmp2.signers[0])
tmp1.add_certificate(@ee2_cert)
p7 = OpenSSL::PKCS7.new(tmp1.to_der)
certs = p7.certificates
signers = p7.signers
assert(p7.verify([], store))
assert_equal(data, p7.data)
assert_equal(2, certs.size)
assert_equal(2, signers.size)
assert_equal(@ee1_cert.serial, signers[0].serial)
assert_equal(@ee1_cert.issuer.to_s, signers[0].issuer.to_s)
assert_equal(@ee2_cert.serial, signers[1].serial)
assert_equal(@ee2_cert.issuer.to_s, signers[1].issuer.to_s)
end
def test_detached_sign
store = OpenSSL::X509::Store.new
store.add_cert(@ca_cert)
ca_certs = [@ca_cert]
data = "aaaaa\nbbbbb\nccccc\n"
flag = OpenSSL::PKCS7::BINARY|OpenSSL::PKCS7::DETACHED
tmp = OpenSSL::PKCS7.sign(@ee1_cert, @rsa1024, data, ca_certs, flag)
p7 = OpenSSL::PKCS7.new(tmp.to_der)
a1 = OpenSSL::ASN1.decode(p7)
certs = p7.certificates
signers = p7.signers
assert(!p7.verify([], store))
assert(p7.verify([], store, data))
assert_equal(data, p7.data)
assert_equal(2, certs.size)
assert_equal(@ee1_cert.subject.to_s, certs[0].subject.to_s)
assert_equal(@ca_cert.subject.to_s, certs[1].subject.to_s)
assert_equal(1, signers.size)
assert_equal(@ee1_cert.serial, signers[0].serial)
assert_equal(@ee1_cert.issuer.to_s, signers[0].issuer.to_s)
end
def test_enveloped
if OpenSSL::OPENSSL_VERSION_NUMBER <= 0x0090704f
# PKCS7_encrypt() of OpenSSL-0.9.7d goes to SEGV.
# http://www.mail-archive.com/openssl-dev@openssl.org/msg17376.html
return
end
certs = [@ee1_cert, @ee2_cert]
cipher = OpenSSL::Cipher::AES.new("128-CBC")
data = "aaaaa\nbbbbb\nccccc\n"
tmp = OpenSSL::PKCS7.encrypt(certs, data, cipher, OpenSSL::PKCS7::BINARY)
p7 = OpenSSL::PKCS7.new(tmp.to_der)
recip = p7.recipients
assert_equal(:enveloped, p7.type)
assert_equal(2, recip.size)
assert_equal(@ca_cert.subject.to_s, recip[0].issuer.to_s)
assert_equal(2, recip[0].serial)
assert_equal(data, p7.decrypt(@rsa1024, @ee1_cert))
assert_equal(@ca_cert.subject.to_s, recip[1].issuer.to_s)
assert_equal(3, recip[1].serial)
assert_equal(data, p7.decrypt(@rsa1024, @ee2_cert))
end
def test_envelope_des3
certs = [@ee1_cert]
cipher = OpenSSL::Cipher.new("des-ede3-cbc")
data = "aaaaa\nbbbbb\nccccc\n"
tmp = OpenSSL::PKCS7.encrypt(certs, data, cipher, OpenSSL::PKCS7::BINARY)
p7 = OpenSSL::PKCS7.new(tmp.to_der)
assert_equal(data, p7.decrypt(@rsa1024, @ee1_cert))
end
def test_envelope_nil # RC2-40-CBC by default
certs = [@ee1_cert]
data = "aaaaa\nbbbbb\nccccc\n"
tmp = OpenSSL::PKCS7.encrypt(certs, data, nil, OpenSSL::PKCS7::BINARY)
p7 = OpenSSL::PKCS7.new(tmp.to_der)
assert_equal(data, p7.decrypt(@rsa1024, @ee1_cert))
end
def test_envelope_des3_compat
data = "aaaaa\nbbbbb\nccccc\n"
cruby_envelope = <<EOP
-----BEGIN PKCS7-----
MIIBMgYJKoZIhvcNAQcDoIIBIzCCAR8CAQAxgdwwgdkCAQAwQjA9MRMwEQYKCZIm
iZPyLGQBGRYDb3JnMRkwFwYKCZImiZPyLGQBGRYJcnVieS1sYW5nMQswCQYDVQQD
DAJDQQIBAjANBgkqhkiG9w0BAQEFAASBgECDOPwRb0Vimo3bXAypvnhB/JvHZ0hV
5CWFdAmovioiu1fnMEqawJWudznUZ1rsCKKX4qzqfvSXk+8w7IZ5rqEFoGmLRQQ+
GR8yPJnDwNyQJwRjvcX2WzJnFDFIfROb+ySu8UCmxkTd/5jB3jsREXVqSIxezTif
IT8Q8X7CCx8+MDsGCSqGSIb3DQEHATAUBggqhkiG9w0DBwQIaH1JJe6+hX+AGD8E
j3/kwFY3IOUxly+lPJNEQLpWBoSHZA==
-----END PKCS7-----
EOP
p7 = OpenSSL::PKCS7.new(cruby_envelope)
assert_equal(data, p7.decrypt(@rsa1024, @ee1_cert))
#
jruby_envelope = <<EOP
-----BEGIN PKCS7-----
MIIBMAYJKoZIhvcNAQcDoIIBITCCAR0CAQAxgdowgdcCAQAwQjA9MRMwEQYKCZIm
iZPyLGQBGRYDb3JnMRkwFwYKCZImiZPyLGQBGRYJcnVieS1sYW5nMQswCQYDVQQD
DAJDQQIBAjALBgkqhkiG9w0BAQEEgYBqCQY/oP0Gv1XbAJ5HjZ9HNZN9gBFlmMDx
fb9YWDQZH24KrTUEssr6jyJuyMsONTdaYWIfG/RWHxw970AkXUXcXDeO8Ze+vSVh
8tohLGLTsBKdvizuC/5jFHLAoNaa5qJZEFanmqMXlO5HiImUZB2BHwJddRuRTg0y
UuAnFtLd+DA7BgkqhkiG9w0BBwEwFAYIKoZIhvcNAwcECP1rHLNHCtyWgBgFQDex
XDgcukPOkDwRcUQJAKu3x5HtQpw=
-----END PKCS7-----
EOP
p7 = OpenSSL::PKCS7.new(jruby_envelope)
assert_equal(data, p7.decrypt(@rsa1024, @ee1_cert))
end
def test_envelope_aes_compat
data = "aaaaa\nbbbbb\nccccc\n"
cruby_envelope = <<EOP
-----BEGIN PKCS7-----
MIICIAYJKoZIhvcNAQcDoIICETCCAg0CAQAxggG4MIHZAgEAMEIwPTETMBEGCgmS
JomT8ixkARkWA29yZzEZMBcGCgmSJomT8ixkARkWCXJ1YnktbGFuZzELMAkGA1UE
AwwCQ0ECAQIwDQYJKoZIhvcNAQEBBQAEgYCHIMVl+WKzjnTuslePlItMq4A+klIZ
rU+5U0UvaOPPpr2UgjD3J1OL09W19De7pKNSSZUd0QWQBB3IG4IzefWzYxt2ejZY
rJDO/wdHa6Mdq1ZsdbLP1sIRxTyWskc3O8VJvo5boFG/bZxLHA6CPnhifnfqEkkq
wVbjAbBGI61HxTCB2QIBADBCMD0xEzARBgoJkiaJk/IsZAEZFgNvcmcxGTAXBgoJ
kiaJk/IsZAEZFglydWJ5LWxhbmcxCzAJBgNVBAMMAkNBAgEDMA0GCSqGSIb3DQEB
AQUABIGASvO7jsPCAB/TcRgmIKEHRDqPThQrSAJRE+uDVeiPlIHsCaUDspGX8niH
4+UPsLhdd6H68Ecay93Hi78SYR/w0NbrwwMBGRlU3/AFhq/OseosuBb303mAqnoz
kU6qlNwJuy/4NIReldsaVJJuZ4nkEBfZAw+99Mxh7IQYx069fwIwTAYJKoZIhvcN
AQcBMB0GCWCGSAFlAwQBAgQQf1IrOpN2OmqMHz1t7biX/oAgubIiBzarCuTKPMby
eg4/+hy0xJsT0IkF1O0G1XTOWcE=
-----END PKCS7-----
EOP
p7 = OpenSSL::PKCS7.new(cruby_envelope)
assert_equal(data, p7.decrypt(@rsa1024, @ee1_cert))
#
jruby_envelope = <<EOP
-----BEGIN PKCS7-----
MIICHAYJKoZIhvcNAQcDoIICDTCCAgkCAQAxggG0MIHXAgEAMEIwPTETMBEGCgmS
JomT8ixkARkWA29yZzEZMBcGCgmSJomT8ixkARkWCXJ1YnktbGFuZzELMAkGA1UE
AwwCQ0ECAQIwCwYJKoZIhvcNAQEBBIGAg0Yz54LwCKM9l128jjh0FlA5Wvzfsjd2
S3dYESzxnxqdhKkSDya16lkYyZZ+aVWmC8XOgkGGwGJTudq3gGn2p3wsgx63J4Ar
PfslsDslIaddp8op4i+ifDi15qCjWXIyQaYMSN/DsFN8DlB8jMjPAlQO3MFtifb2
D7vFjLjSrogwgdcCAQAwQjA9MRMwEQYKCZImiZPyLGQBGRYDb3JnMRkwFwYKCZIm
iZPyLGQBGRYJcnVieS1sYW5nMQswCQYDVQQDDAJDQQIBAzALBgkqhkiG9w0BAQEE
gYCfAEL80vCsFo9kalePlb73lL2iDPbbDfjpWs0nnlXX8BhS/H781kvUkDpwl/qT
9KcFCaPGJ2IYgEjys6VPK9ho/hIIIz+BX8MIuWbweQTn1Y0TTlTL91Zr66xyZP1p
zyStG6Zc1u26hiX31hk1P6ihhhXu+I5bserKNYUnYsxJSjBMBgkqhkiG9w0BBwEw
HQYJYIZIAWUDBAECBBD42Hndr47SEdUoc6SWOKsbgCCylxb34kE14eBc9nN9MnC+
SaVrDPgso584FIimP6o+Fw==
-----END PKCS7-----
EOP
p7 = OpenSSL::PKCS7.new(jruby_envelope)
assert_equal(data, p7.decrypt(@rsa1024, @ee1_cert))
end
def test_signed_compat
=begin
# how to generate signature
ca_certs = [@ca_cert]
data = "aaaaa\r\nbbbbb\r\nccccc\r\n"
tmp = OpenSSL::PKCS7.sign(@ee1_cert, @rsa1024, data, ca_certs)
puts tmp
=end
cruby_sign = <<EOP
-----BEGIN PKCS7-----
MIIILgYJKoZIhvcNAQcCoIIIHzCCCBsCAQExCzAJBgUrDgMCGgUAMCQGCSqGSIb3
DQEHAaAXBBVhYWFhYQ0KYmJiYmINCmNjY2NjDQqgggZBMIIC4TCCAcmgAwIBAgIB
AjANBgkqhkiG9w0BAQUFADA9MRMwEQYKCZImiZPyLGQBGRYDb3JnMRkwFwYKCZIm
iZPyLGQBGRYJcnVieS1sYW5nMQswCQYDVQQDDAJDQTAeFw0wOTEyMTYxNTQ1MzRa
Fw0wOTEyMTYxNjE1MzRaMD4xEzARBgoJkiaJk/IsZAEZFgNvcmcxGTAXBgoJkiaJ
k/IsZAEZFglydWJ5LWxhbmcxDDAKBgNVBAMMA0VFMTCBnzANBgkqhkiG9w0BAQEF
AAOBjQAwgYkCgYEAy8LEsNRApz7U/j5DoB4XBgO9Z8Atv5y/OVQRp0ag8Tqo1Yew
sWijxEWB7JOATwpBN267U4T1nPZIxxEEO7n/WNa2ws9JWsjah8ssEBFSxZqdXKSL
f0N4Hi7/GQ/aYoaMCiQ8jA4jegK2FJmXM71uPe+jFN/peeBOpRfyXxRFOYcCAwEA
AaNvMG0wDgYDVR0PAQH/BAQDAgXgMB8GA1UdIwQYMBaAFJc5ncP7zbqPVAyQe0Y/
6tZDdbHLMCcGA1UdJQQgMB4GCCsGAQUFBwMCBggrBgEFBQcDBAYIKwYBBQUHAwMw
EQYJYIZIAYb4QgEBBAQDAgWgMA0GCSqGSIb3DQEBBQUAA4IBAQB9jL0H9qAeWZmA
lmEr7WbVibFwod6ZgNmbFhoP6a9PANDdYwp1EQ7J2o3Dzw1hNjsxDVE5uf3qgA0F
df/YoFkfi4xoL1pKdZv9ZMOlctC1po7MbFakjeHdxMtdIM70DMxbS4o4HzXrKtC3
of1SmKh+g+r4R1YHCrbBCspEX+s2Y4mKD0IP0XkVvv1d4YICAnKYGCYEC9OS4fr7
JPB2cL1yXnjPL0OOvSeAOC2uIkDq1SVZk6Xq4sSaHAKwBNGg0HrqOhrdgcB0Ftpi
7Paty9PUmSIjoqre/WzfGNF1MrtTC0wf0PDw/aUzWgInlIXJhcbJOMyhWM/SO5ok
50rcYfObMIIDWDCCAkCgAwIBAgIBATANBgkqhkiG9w0BAQUFADA9MRMwEQYKCZIm
iZPyLGQBGRYDb3JnMRkwFwYKCZImiZPyLGQBGRYJcnVieS1sYW5nMQswCQYDVQQD
DAJDQTAeFw0wOTEyMTYxNTQ1MzRaFw0wOTEyMTYxNjQ1MzRaMD0xEzARBgoJkiaJ
k/IsZAEZFgNvcmcxGTAXBgoJkiaJk/IsZAEZFglydWJ5LWxhbmcxCzAJBgNVBAMM
AkNBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuV9ht9J7k4NBs38j
OXvvTKY9gW8nLICSno5EETR1cuF7i4pNs9I1QJGAFAX0BEO4KbzXmuOvfCpD3CU+
Slp1enenfzq/t/e/1IRW0wkJUJUFQign4CtrkJL+P07yx18UjyPlBXb81ApEmAB5
mrJVSrWmqbjs07JbuS4QQGGXLc+Su96DkYKmSNVjBiLxVVSpyZfAY3hD37d60uG+
X8xdW5v68JkRFIhdGlb6JL8fllf/A/blNwdJOhVr9mESHhwGjwfSeTDPfd8ZLE02
7E5lyAVX9KZYcU00mOX+fdxOSnGqS/8JDRh0EPHDL15RcJjV2J6vZjPb0rOYGDoM
cH+94wIDAQABo2MwYTAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAd
BgNVHQ4EFgQUlzmdw/vNuo9UDJB7Rj/q1kN1scswHwYDVR0jBBgwFoAUlzmdw/vN
uo9UDJB7Rj/q1kN1scswDQYJKoZIhvcNAQEFBQADggEBAFa1X5xX5+NlXOI3z2vh
Vp9tPvIAtftqkhdMbfS1dAAIIZKVLPfvQ+ZLqx/AzQXmDajg3Pg9YoBB3RRDx1xh
A9ECO4Lpbv5fYAkIul6XQ2D3U1IjnkhdfYHcU5iRl58nhjlDNd+3vOp1/h9D9Pp6
lRILuFCoRcOogcXzChuDA06CDbMao1dDcwdNe1SdV54hzZs1DVqoKIjj4182HUST
getU2RDFXh76VtF35iYDzdA+iCAWOqXSMAq7GnZJvL//0Ndffc7Oc6QXCicwiUSw
Wrj72gEakBOeC8XxlYaP7TSXFkasdg1Eccz7+U6LgWaYrgwgTdGXarT3ewjs/mvb
sgsxggGcMIIBmAIBATBCMD0xEzARBgoJkiaJk/IsZAEZFgNvcmcxGTAXBgoJkiaJ
k/IsZAEZFglydWJ5LWxhbmcxCzAJBgNVBAMMAkNBAgECMAkGBSsOAwIaBQCggbEw
GAYJKoZIhvcNAQkDMQsGCSqGSIb3DQEHATAcBgkqhkiG9w0BCQUxDxcNMDkxMjE2
MTU0NTM0WjAjBgkqhkiG9w0BCQQxFgQUTqRiQxhezJlftad5eZ6u7hNacV0wUgYJ
KoZIhvcNAQkPMUUwQzAKBggqhkiG9w0DBzAOBggqhkiG9w0DAgICAIAwDQYIKoZI
hvcNAwICAUAwBwYFKw4DAgcwDQYIKoZIhvcNAwICASgwDQYJKoZIhvcNAQEBBQAE
gYCMPxJNaR29Yeo/3JWtUTTRq+IlUWHP4bHoZJHQzyFkFPS3fk+9q9KjlTcFY1rT
YbBOUD+QxwU/jlks6Y5PZByIpnWvVy0RujcCzGcMyEY6xKBBkps9X5VuezMB0nbW
xM2k+0e3B7V0KU8fMcO8Ajq9jGn8/hVixbUkyvhq3Xx2Nw==
-----END PKCS7-----
EOP
jruby_sign = <<EOP
-----BEGIN PKCS7-----
MIIIKAYJKoZIhvcNAQcCoIIIGTCCCBUCAQExCTAHBgUrDgMCGjAkBgkqhkiG9w0B
BwGgFwQVYWFhYWENCmJiYmJiDQpjY2NjYw0KoIIGQTCCAuEwggHJoAMCAQICAQIw
DQYJKoZIhvcNAQEFBQAwPTETMBEGCgmSJomT8ixkARkWA29yZzEZMBcGCgmSJomT
8ixkARkWCXJ1YnktbGFuZzELMAkGA1UEAwwCQ0EwHhcNMDkxMjE2MTU0NjE5WhcN
MDkxMjE2MTYxNjE5WjA+MRMwEQYKCZImiZPyLGQBGRYDb3JnMRkwFwYKCZImiZPy
LGQBGRYJcnVieS1sYW5nMQwwCgYDVQQDDANFRTEwgZ8wDQYJKoZIhvcNAQEBBQAD
gY0AMIGJAoGBAMvCxLDUQKc+1P4+Q6AeFwYDvWfALb+cvzlUEadGoPE6qNWHsLFo
o8RFgeyTgE8KQTduu1OE9Zz2SMcRBDu5/1jWtsLPSVrI2ofLLBARUsWanVyki39D
eB4u/xkP2mKGjAokPIwOI3oCthSZlzO9bj3voxTf6XngTqUX8l8URTmHAgMBAAGj
bzBtMA4GA1UdDwEB/wQEAwIF4DAfBgNVHSMEGDAWBBSXOZ3D+826j1QMkHtGP+rW
Q3WxyzAnBgNVHSUEIDAeBggrBgEFBQcDAgYIKwYBBQUHAwQGCCsGAQUFBwMDMBEG
CWCGSAGG+EIBAQQEAwIFoDANBgkqhkiG9w0BAQUFAAOCAQEAZPqFEX/azn4squHn
mh+o3tulK/XqdnPA+mx+yvhg53QqWewpSeNQnhH/Y/wnGva6bEFqDd7WTlhkSp0P
2qtCP3C5MI2aLPZBUjFJq6cxEC+CUAD7ggIoV8/Z3XCGOa1z/m+QKpBq5t13Hewb
Kd8Ab5lojN15XYyLFQ8wJsrkvjA+z943Ux+4aAv2DoOv0Y+GuvgOuqNCs+frZYHR
OdOsnhg48A+UsjlLh5wsHzsZEMmtEfP59TdCZ/HbW2WIbdoij+GsK3uoITjhLNyO
RK/XeuBwnaksrBiIeCfVQxNHriTPL/4xolOAWVtlhJOj+i8iMPJnbi9M3lVO5fLd
9ShiZDCCA1gwggJAoAMCAQICAQEwDQYJKoZIhvcNAQEFBQAwPTETMBEGCgmSJomT
8ixkARkWA29yZzEZMBcGCgmSJomT8ixkARkWCXJ1YnktbGFuZzELMAkGA1UEAwwC
Q0EwHhcNMDkxMjE2MTU0NjE4WhcNMDkxMjE2MTY0NjE4WjA9MRMwEQYKCZImiZPy
LGQBGRYDb3JnMRkwFwYKCZImiZPyLGQBGRYJcnVieS1sYW5nMQswCQYDVQQDDAJD
QTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALlfYbfSe5ODQbN/Izl7
70ymPYFvJyyAkp6ORBE0dXLhe4uKTbPSNUCRgBQF9ARDuCm815rjr3wqQ9wlPkpa
dXp3p386v7f3v9SEVtMJCVCVBUIoJ+Ara5CS/j9O8sdfFI8j5QV2/NQKRJgAeZqy
VUq1pqm47NOyW7kuEEBhly3Pkrveg5GCpkjVYwYi8VVUqcmXwGN4Q9+3etLhvl/M
XVub+vCZERSIXRpW+iS/H5ZX/wP25TcHSToVa/ZhEh4cBo8H0nkwz33fGSxNNuxO
ZcgFV/SmWHFNNJjl/n3cTkpxqkv/CQ0YdBDxwy9eUXCY1dier2Yz29KzmBg6DHB/
veMCAwEAAaNjMGEwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYD
VR0OBBYEFJc5ncP7zbqPVAyQe0Y/6tZDdbHLMB8GA1UdIwQYMBYEFJc5ncP7zbqP
VAyQe0Y/6tZDdbHLMA0GCSqGSIb3DQEBBQUAA4IBAQBK/6fISsbbIY1uCX4WMENG
V1dCmDAFaZwgewhg09n3rgs4lWKVOWG6X57oML9YSVuz05kkFaSIox+vi36awVf6
7YY0V+JdNEQRle/0ptLxmEY8gGD1HvM8JAsQdotMl6hFfzMQ8Uu0IHePYFMyU9aU
9Z4k1kCEPc222Uyt7whCWHloWMgjKNeCRjMLUvw9HUxGeq/2Y+t8d65SrqsxpHJd
dszJvG+fl0UPoAdB0c4jCGWIzfoGP74CXVAGcuuFZlImmV5cY0+sDo7dtwRDp0DF
307/n8+qlsMqpIummFV2mhZTGrtgW+bTZSYQsSJTJZ6nK3c0rQCH4wyUP3rBNhRf
MYIBmDCCAZQCAQEwQjA9MRMwEQYKCZImiZPyLGQBGRYDb3JnMRkwFwYKCZImiZPy
LGQBGRYJcnVieS1sYW5nMQswCQYDVQQDDAJDQQIBAjAHBgUrDgMCGqCBsTAYBgkq
hkiG9w0BCQMxCwYJKoZIhvcNAQcBMBwGCSqGSIb3DQEJBTEPFw0wOTEyMTYxNTQ2
MTlaMCMGCSqGSIb3DQEJBDEWBBROpGJDGF7MmV+1p3l5nq7uE1pxXTBSBgkqhkiG
9w0BCQ8xRTBDMAoGCCqGSIb3DQMHMA4GCCqGSIb3DQMCAgIAgDANBggqhkiG9w0D
AgIBQDANBggqhkiG9w0DAgIBKDAHBgUrDgMCBzALBgkqhkiG9w0BAQEEgYBygH60
/1zLRnXaPKh8fTaQtQCTobefRqGLxbWJaTmO83UeDEmS8HXyr6t5KkZ4qZL6BA50
bQSlVx3I9SiqevP0vEiXGzmb4m1blFzdH5HHZk4ZUWqWYyTqOdXTSfwFp53VAUhi
9d8f3IBfFoxCvORtzYZKCzW/ZRvEqBO3xJlVuQ==
-----END PKCS7-----
EOP
store = OpenSSL::X509::Store.new
store.add_cert(@ca_cert)
# just checks pubkey's n to avoid certificate expiration.
# this test is for PKCS#7, not for certificate verification.
store.verify_callback = proc { |ok, ctx|
# !! CAUTION: NEVER DO THIS KIND OF NEGLIGENCE !!
[@ca_cert.public_key.n, @ee1_cert.public_key.n].include?(ctx.current_cert.public_key.n)
# should return 'ok' here
}
p7 = OpenSSL::PKCS7.new(cruby_sign)
assert(p7.verify([], store))
p7 = OpenSSL::PKCS7.new(jruby_sign)
assert(p7.verify([], store))
end
def test_detached_sign_compat
=begin
# how to generate signature
ca_certs = [@ca_cert]
flag = OpenSSL::PKCS7::BINARY|OpenSSL::PKCS7::DETACHED
tmp = OpenSSL::PKCS7.sign(@ee1_cert, @rsa1024, data, ca_certs, flag)
puts tmp
=end
cruby_sign = <<EOP
-----BEGIN PKCS7-----
MIIIFQYJKoZIhvcNAQcCoIIIBjCCCAICAQExCzAJBgUrDgMCGgUAMAsGCSqGSIb3
DQEHAaCCBkEwggLhMIIByaADAgECAgECMA0GCSqGSIb3DQEBBQUAMD0xEzARBgoJ
kiaJk/IsZAEZFgNvcmcxGTAXBgoJkiaJk/IsZAEZFglydWJ5LWxhbmcxCzAJBgNV
BAMMAkNBMB4XDTA5MTIxNjE1NDkyN1oXDTA5MTIxNjE2MTkyN1owPjETMBEGCgmS
JomT8ixkARkWA29yZzEZMBcGCgmSJomT8ixkARkWCXJ1YnktbGFuZzEMMAoGA1UE
AwwDRUUxMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDLwsSw1ECnPtT+PkOg
HhcGA71nwC2/nL85VBGnRqDxOqjVh7CxaKPERYHsk4BPCkE3brtThPWc9kjHEQQ7
uf9Y1rbCz0layNqHyywQEVLFmp1cpIt/Q3geLv8ZD9pihowKJDyMDiN6ArYUmZcz
vW4976MU3+l54E6lF/JfFEU5hwIDAQABo28wbTAOBgNVHQ8BAf8EBAMCBeAwHwYD
VR0jBBgwFoAUlzmdw/vNuo9UDJB7Rj/q1kN1scswJwYDVR0lBCAwHgYIKwYBBQUH
AwIGCCsGAQUFBwMEBggrBgEFBQcDAzARBglghkgBhvhCAQEEBAMCBaAwDQYJKoZI
hvcNAQEFBQADggEBAJ4qQEkUVLW7s3JNKWVOxDwPmDGQsN9uG5ULT3ub76gaC8XH
Ljh59zzN2o3bJ5yH4oW+zejcDtGP2R2RBDCu5X7uuLhEbjv4xarSSgLeQHAXhEXa
pXY3nXa6DM6HVWKL176FQfN+B7ouejR17ESeMMVAgYjTrr7jjVpaZxXGKXnLeqVv
qd4TojjibzoeRw7BxIjmoa+74KO+N6Z+d0R5bNBh+40HyTpCww0O7RjGsOV2ANxW
sPREa3KmGmKdlyXsZP1VJyBDymSJSee1zCYmmc+S532+537ygGZEGk8FysRtJXPc
71XhPEXMjimn3wVSt1jPhzk4HmXoYwcCI2pKVfMwggNYMIICQKADAgECAgEBMA0G
CSqGSIb3DQEBBQUAMD0xEzARBgoJkiaJk/IsZAEZFgNvcmcxGTAXBgoJkiaJk/Is
ZAEZFglydWJ5LWxhbmcxCzAJBgNVBAMMAkNBMB4XDTA5MTIxNjE1NDkyNloXDTA5
MTIxNjE2NDkyNlowPTETMBEGCgmSJomT8ixkARkWA29yZzEZMBcGCgmSJomT8ixk
ARkWCXJ1YnktbGFuZzELMAkGA1UEAwwCQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IB
DwAwggEKAoIBAQC5X2G30nuTg0GzfyM5e+9Mpj2BbycsgJKejkQRNHVy4XuLik2z
0jVAkYAUBfQEQ7gpvNea4698KkPcJT5KWnV6d6d/Or+397/UhFbTCQlQlQVCKCfg
K2uQkv4/TvLHXxSPI+UFdvzUCkSYAHmaslVKtaapuOzTslu5LhBAYZctz5K73oOR
gqZI1WMGIvFVVKnJl8BjeEPft3rS4b5fzF1bm/rwmREUiF0aVvokvx+WV/8D9uU3
B0k6FWv2YRIeHAaPB9J5MM993xksTTbsTmXIBVf0plhxTTSY5f593E5KcapL/wkN
GHQQ8cMvXlFwmNXYnq9mM9vSs5gYOgxwf73jAgMBAAGjYzBhMA8GA1UdEwEB/wQF
MAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBSXOZ3D+826j1QMkHtGP+rW
Q3WxyzAfBgNVHSMEGDAWgBSXOZ3D+826j1QMkHtGP+rWQ3WxyzANBgkqhkiG9w0B
AQUFAAOCAQEAicOGMs494jNo6buyvWgYwCMEHTgf8snOR6F5Xs7R4CsIfF+Y1Q8S
urL2ZrabYP0bWNZO0eYyUwNi9QCYn8n5UsYPu5HoC04maVlimAnf8kUoWK4/Es4F
0geMJGG7TOn17aQYj4v8CMBuYBAuO/poQgbpjxZnNLBqSkWz3uSl+LF6Zwlu/jIa
jcRNTix/soQwTO02EtG3ZhNFmSLwL4cMljjXHuVgTl++mO7w/3qzGgtldkot9W87
pnx0u9UgZkgsRVhIkvSsTNaTe0ylA3Lqa5COd89PrCjm66IdAjyND3puWP4etFP6
ycc7rtc0302ndadSEJRgul9pFJ4xtuAN5jGCAZwwggGYAgEBMEIwPTETMBEGCgmS
JomT8ixkARkWA29yZzEZMBcGCgmSJomT8ixkARkWCXJ1YnktbGFuZzELMAkGA1UE
AwwCQ0ECAQIwCQYFKw4DAhoFAKCBsTAYBgkqhkiG9w0BCQMxCwYJKoZIhvcNAQcB
MBwGCSqGSIb3DQEJBTEPFw0wOTEyMTYxNTQ5MjdaMCMGCSqGSIb3DQEJBDEWBBT2
oG8gOR1i/LHuubBgBOVTjSF6lzBSBgkqhkiG9w0BCQ8xRTBDMAoGCCqGSIb3DQMH
MA4GCCqGSIb3DQMCAgIAgDANBggqhkiG9w0DAgIBQDAHBgUrDgMCBzANBggqhkiG
9w0DAgIBKDANBgkqhkiG9w0BAQEFAASBgCPxDWHnvO3pMg0XUDGtisZgbjFG+sJy
brFi2QG0IR+iQ6kOrBWkBW15SDgj0te1ze6ddLx3VT0aaOHMzGS103oWQT6l+xqV
C+A/FA5O+hefjqusgl289gFvApuGVSaMisHBcMAN059E1rsSTnG3LoHqkKjOgKkJ
zyAlR+YeT270
-----END PKCS7-----
EOP
jruby_sign = <<EOP
-----BEGIN PKCS7-----
MIIIEwYJKoZIhvcNAQcCoIIIBDCCCAACAQExCTAHBgUrDgMCGjAPBgkqhkiG9w0B
BwGgAgQAoIIGQTCCAuEwggHJoAMCAQICAQIwDQYJKoZIhvcNAQEFBQAwPTETMBEG
CgmSJomT8ixkARkWA29yZzEZMBcGCgmSJomT8ixkARkWCXJ1YnktbGFuZzELMAkG
A1UEAwwCQ0EwHhcNMDkxMjE2MTU0OTU3WhcNMDkxMjE2MTYxOTU3WjA+MRMwEQYK
CZImiZPyLGQBGRYDb3JnMRkwFwYKCZImiZPyLGQBGRYJcnVieS1sYW5nMQwwCgYD
VQQDDANFRTEwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMvCxLDUQKc+1P4+
Q6AeFwYDvWfALb+cvzlUEadGoPE6qNWHsLFoo8RFgeyTgE8KQTduu1OE9Zz2SMcR
BDu5/1jWtsLPSVrI2ofLLBARUsWanVyki39DeB4u/xkP2mKGjAokPIwOI3oCthSZ
lzO9bj3voxTf6XngTqUX8l8URTmHAgMBAAGjbzBtMA4GA1UdDwEB/wQEAwIF4DAf
BgNVHSMEGDAWBBSXOZ3D+826j1QMkHtGP+rWQ3WxyzAnBgNVHSUEIDAeBggrBgEF
BQcDAgYIKwYBBQUHAwQGCCsGAQUFBwMDMBEGCWCGSAGG+EIBAQQEAwIFoDANBgkq
hkiG9w0BAQUFAAOCAQEAAVeRavmpW+ez0dpDs1ksEZSKIr+JQHPIfgyF1P0x/uLH
tkUssR1puDsYB9bWQncYz2PyFzDdXHUneKLu01hSrY9fS85S3w/sa6scGtMD1SDS
Ptm93a67pvNoXY8rrdW67Wughyix78TOpe7F/D8tLxm7dRfZVLCtV/OIgnjTKK36
NNBAX4Ef0+43EDUZYQIbEudqcjjYN0Dti0dH4FuUW5PPTAs9nuNfkAWr0hTyBwlC
qhlgFY3ParJ9Yug7BVZj99vrI4F9KFzWkoSd5pIl+mR1aNQ3uQgks7aNqnZ8PeJo
gP9zcZqZniuj7sa92t1bPxn5JmLy+vnxeWiQPw8fhDCCA1gwggJAoAMCAQICAQEw
DQYJKoZIhvcNAQEFBQAwPTETMBEGCgmSJomT8ixkARkWA29yZzEZMBcGCgmSJomT
8ixkARkWCXJ1YnktbGFuZzELMAkGA1UEAwwCQ0EwHhcNMDkxMjE2MTU0OTU3WhcN
MDkxMjE2MTY0OTU3WjA9MRMwEQYKCZImiZPyLGQBGRYDb3JnMRkwFwYKCZImiZPy
LGQBGRYJcnVieS1sYW5nMQswCQYDVQQDDAJDQTCCASIwDQYJKoZIhvcNAQEBBQAD
ggEPADCCAQoCggEBALlfYbfSe5ODQbN/Izl770ymPYFvJyyAkp6ORBE0dXLhe4uK
TbPSNUCRgBQF9ARDuCm815rjr3wqQ9wlPkpadXp3p386v7f3v9SEVtMJCVCVBUIo
J+Ara5CS/j9O8sdfFI8j5QV2/NQKRJgAeZqyVUq1pqm47NOyW7kuEEBhly3Pkrve
g5GCpkjVYwYi8VVUqcmXwGN4Q9+3etLhvl/MXVub+vCZERSIXRpW+iS/H5ZX/wP2
5TcHSToVa/ZhEh4cBo8H0nkwz33fGSxNNuxOZcgFV/SmWHFNNJjl/n3cTkpxqkv/
CQ0YdBDxwy9eUXCY1dier2Yz29KzmBg6DHB/veMCAwEAAaNjMGEwDwYDVR0TAQH/
BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFJc5ncP7zbqPVAyQe0Y/
6tZDdbHLMB8GA1UdIwQYMBYEFJc5ncP7zbqPVAyQe0Y/6tZDdbHLMA0GCSqGSIb3
DQEBBQUAA4IBAQBxj2quNTT3/vKTM6bFtEDmXUcruEnbM+VQ1oaDGc8Zh1c/0GIh
l4AGnoD611tdUazZbz7EtLLwfjhEFFJtwxro4Hdc0YEeBwO/ehx8mdclbMzbfQVF
l+wyPpcsWYH8aRAZ/AKY31lS/vPp/vDOJ+SAkYgT3f3g8NCOLCXeivkWze5CDzME
Qj9GGl8BzhxQAMwzXVkmBNmdsTBlpWE1fJBUNCyvFLVRn09LphQ2SDOXr16af9v0
4K8WBTi0/qYcrGvgpl5DIqOg0bfjEwz9Ze5XKa1aem0DdEcM91eEbe5VkakIXvTX
0jUoDm9R5iJ7fAt+vmW/Kcif4VK/nDzJnPx+MYIBmDCCAZQCAQEwQjA9MRMwEQYK
CZImiZPyLGQBGRYDb3JnMRkwFwYKCZImiZPyLGQBGRYJcnVieS1sYW5nMQswCQYD
VQQDDAJDQQIBAjAHBgUrDgMCGqCBsTAYBgkqhkiG9w0BCQMxCwYJKoZIhvcNAQcB
MBwGCSqGSIb3DQEJBTEPFw0wOTEyMTYxNTQ5NTdaMCMGCSqGSIb3DQEJBDEWBBT2
oG8gOR1i/LHuubBgBOVTjSF6lzBSBgkqhkiG9w0BCQ8xRTBDMAoGCCqGSIb3DQMH
MA4GCCqGSIb3DQMCAgIAgDANBggqhkiG9w0DAgIBQDANBggqhkiG9w0DAgIBKDAH
BgUrDgMCBzALBgkqhkiG9w0BAQEEgYBPjfO6ZkzbNhlRI9Y58QpOxdqdF/NmWBJE
rYoqlDUeMcH5RHb+MLUBEeo666u0xIXYzG9CWrlVjJa42FDNEl5sGRB1Oic6LNIB
YBFvB2CAX9R3+d34WMLXKwl6ikeN6VVud+TeB5SpLR/hltWIb1FJMeJ4wM8fNI/t
RfHXsdxTuA==
-----END PKCS7-----
EOP
data = "aaaaa\nbbbbb\nccccc\n"
store = OpenSSL::X509::Store.new
store.add_cert(@ca_cert)
# just checks pubkey's n to avoid certificate expiration.
# this test is for PKCS#7, not for certificate verification.
store.verify_callback = proc { |ok, ctx|
# !! CAUTION: NEVER DO THIS KIND OF NEGLIGENCE !!
[@ca_cert.public_key.n, @ee1_cert.public_key.n].include?(ctx.current_cert.public_key.n)
# should return 'ok' here
}
p7 = OpenSSL::PKCS7.new(cruby_sign)
assert(!p7.verify([], store))
assert(p7.verify([], store, data))
p7 = OpenSSL::PKCS7.new(jruby_sign)
assert(!p7.verify([], store))
assert(p7.verify([], store, data))
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/openssl/test_x509crl.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/openssl/test_x509crl.rb | begin
require "openssl"
require File.join(File.dirname(__FILE__), "utils.rb")
rescue LoadError
end
require "test/unit"
if defined?(OpenSSL)
class OpenSSL::TestX509CRL < Test::Unit::TestCase
def setup
@rsa1024 = OpenSSL::TestUtils::TEST_KEY_RSA1024
@rsa2048 = OpenSSL::TestUtils::TEST_KEY_RSA2048
@dsa256 = OpenSSL::TestUtils::TEST_KEY_DSA256
@dsa512 = OpenSSL::TestUtils::TEST_KEY_DSA512
@ca = OpenSSL::X509::Name.parse("/DC=org/DC=ruby-lang/CN=CA")
@ee1 = OpenSSL::X509::Name.parse("/DC=org/DC=ruby-lang/CN=EE1")
@ee2 = OpenSSL::X509::Name.parse("/DC=org/DC=ruby-lang/CN=EE2")
end
def teardown
end
def issue_crl(*args)
OpenSSL::TestUtils.issue_crl(*args)
end
def issue_cert(*args)
OpenSSL::TestUtils.issue_cert(*args)
end
def test_basic
now = Time.at(Time.now.to_i)
cert = issue_cert(@ca, @rsa2048, 1, now, now+3600, [],
nil, nil, OpenSSL::Digest::SHA1.new)
crl = issue_crl([], 1, now, now+1600, [],
cert, @rsa2048, OpenSSL::Digest::SHA1.new)
assert_equal(1, crl.version)
assert_equal(cert.issuer.to_der, crl.issuer.to_der)
assert_equal(now, crl.last_update)
assert_equal(now+1600, crl.next_update)
crl = OpenSSL::X509::CRL.new(crl.to_der)
assert_equal(1, crl.version)
assert_equal(cert.issuer.to_der, crl.issuer.to_der)
assert_equal(now, crl.last_update)
assert_equal(now+1600, crl.next_update)
end
def test_revoked
# CRLReason ::= ENUMERATED {
# unspecified (0),
# keyCompromise (1),
# cACompromise (2),
# affiliationChanged (3),
# superseded (4),
# cessationOfOperation (5),
# certificateHold (6),
# removeFromCRL (8),
# privilegeWithdrawn (9),
# aACompromise (10) }
now = Time.at(Time.now.to_i)
revoke_info = [
[1, Time.at(0), 1],
[2, Time.at(0x7fffffff), 2],
[3, now, 3],
[4, now, 4],
[5, now, 5],
]
cert = issue_cert(@ca, @rsa2048, 1, Time.now, Time.now+3600, [],
nil, nil, OpenSSL::Digest::SHA1.new)
crl = issue_crl(revoke_info, 1, Time.now, Time.now+1600, [],
cert, @rsa2048, OpenSSL::Digest::SHA1.new)
revoked = crl.revoked
assert_equal(5, revoked.size)
assert_equal(1, revoked[0].serial)
assert_equal(2, revoked[1].serial)
assert_equal(3, revoked[2].serial)
assert_equal(4, revoked[3].serial)
assert_equal(5, revoked[4].serial)
assert_equal(Time.at(0), revoked[0].time)
assert_equal(Time.at(0x7fffffff), revoked[1].time)
assert_equal(now, revoked[2].time)
assert_equal(now, revoked[3].time)
assert_equal(now, revoked[4].time)
assert_equal("CRLReason", revoked[0].extensions[0].oid)
assert_equal("CRLReason", revoked[1].extensions[0].oid)
assert_equal("CRLReason", revoked[2].extensions[0].oid)
assert_equal("CRLReason", revoked[3].extensions[0].oid)
assert_equal("CRLReason", revoked[4].extensions[0].oid)
assert_equal("Key Compromise", revoked[0].extensions[0].value)
assert_equal("CA Compromise", revoked[1].extensions[0].value)
assert_equal("Affiliation Changed", revoked[2].extensions[0].value)
assert_equal("Superseded", revoked[3].extensions[0].value)
assert_equal("Cessation Of Operation", revoked[4].extensions[0].value)
assert_equal(false, revoked[0].extensions[0].critical?)
assert_equal(false, revoked[1].extensions[0].critical?)
assert_equal(false, revoked[2].extensions[0].critical?)
assert_equal(false, revoked[3].extensions[0].critical?)
assert_equal(false, revoked[4].extensions[0].critical?)
crl = OpenSSL::X509::CRL.new(crl.to_der)
assert_equal("Key Compromise", revoked[0].extensions[0].value)
assert_equal("CA Compromise", revoked[1].extensions[0].value)
assert_equal("Affiliation Changed", revoked[2].extensions[0].value)
assert_equal("Superseded", revoked[3].extensions[0].value)
assert_equal("Cessation Of Operation", revoked[4].extensions[0].value)
revoke_info = (1..1000).collect{|i| [i, now, 0] }
crl = issue_crl(revoke_info, 1, Time.now, Time.now+1600, [],
cert, @rsa2048, OpenSSL::Digest::SHA1.new)
revoked = crl.revoked
assert_equal(1000, revoked.size)
assert_equal(1, revoked[0].serial)
assert_equal(1000, revoked[999].serial)
end
def test_extension
cert_exts = [
["basicConstraints", "CA:TRUE", true],
["subjectKeyIdentifier", "hash", false],
["authorityKeyIdentifier", "keyid:always", false],
["subjectAltName", "email:xyzzy@ruby-lang.org", false],
["keyUsage", "cRLSign, keyCertSign", true],
]
crl_exts = [
["authorityKeyIdentifier", "keyid:always", false],
["issuerAltName", "issuer:copy", false],
]
cert = issue_cert(@ca, @rsa2048, 1, Time.now, Time.now+3600, cert_exts,
nil, nil, OpenSSL::Digest::SHA1.new)
crl = issue_crl([], 1, Time.now, Time.now+1600, crl_exts,
cert, @rsa2048, OpenSSL::Digest::SHA1.new)
exts = crl.extensions
assert_equal(3, exts.size)
assert_equal("1", exts[0].value)
assert_equal("crlNumber", exts[0].oid)
assert_equal(false, exts[0].critical?)
assert_equal("authorityKeyIdentifier", exts[1].oid)
keyid = OpenSSL::TestUtils.get_subject_key_id(cert)
assert_match(/^keyid:#{keyid}/, exts[1].value)
assert_equal(false, exts[1].critical?)
assert_equal("issuerAltName", exts[2].oid)
assert_equal("email:xyzzy@ruby-lang.org", exts[2].value)
assert_equal(false, exts[2].critical?)
crl = OpenSSL::X509::CRL.new(crl.to_der)
exts = crl.extensions
assert_equal(3, exts.size)
assert_equal("1", exts[0].value)
assert_equal("crlNumber", exts[0].oid)
assert_equal(false, exts[0].critical?)
assert_equal("authorityKeyIdentifier", exts[1].oid)
keyid = OpenSSL::TestUtils.get_subject_key_id(cert)
assert_match(/^keyid:#{keyid}/, exts[1].value)
assert_equal(false, exts[1].critical?)
assert_equal("issuerAltName", exts[2].oid)
assert_equal("email:xyzzy@ruby-lang.org", exts[2].value)
assert_equal(false, exts[2].critical?)
end
def test_crlnumber
cert = issue_cert(@ca, @rsa2048, 1, Time.now, Time.now+3600, [],
nil, nil, OpenSSL::Digest::SHA1.new)
crl = issue_crl([], 1, Time.now, Time.now+1600, [],
cert, @rsa2048, OpenSSL::Digest::SHA1.new)
assert_match(1.to_s, crl.extensions[0].value)
assert_match(/X509v3 CRL Number:\s+#{1}/m, crl.to_text)
crl = issue_crl([], 2**32, Time.now, Time.now+1600, [],
cert, @rsa2048, OpenSSL::Digest::SHA1.new)
assert_match((2**32).to_s, crl.extensions[0].value)
assert_match(/X509v3 CRL Number:\s+#{2**32}/m, crl.to_text)
crl = issue_crl([], 2**100, Time.now, Time.now+1600, [],
cert, @rsa2048, OpenSSL::Digest::SHA1.new)
assert_match(/X509v3 CRL Number:\s+#{2**100}/m, crl.to_text)
assert_match((2**100).to_s, crl.extensions[0].value)
end
def test_sign_and_verify
cert = issue_cert(@ca, @rsa2048, 1, Time.now, Time.now+3600, [],
nil, nil, OpenSSL::Digest::SHA1.new)
crl = issue_crl([], 1, Time.now, Time.now+1600, [],
cert, @rsa2048, OpenSSL::Digest::SHA1.new)
assert_equal(false, crl.verify(@rsa1024))
assert_equal(true, crl.verify(@rsa2048))
assert_equal(false, crl.verify(@dsa256))
assert_equal(false, crl.verify(@dsa512))
crl.version = 0
assert_equal(false, crl.verify(@rsa2048))
cert = issue_cert(@ca, @dsa512, 1, Time.now, Time.now+3600, [],
nil, nil, OpenSSL::Digest::DSS1.new)
crl = issue_crl([], 1, Time.now, Time.now+1600, [],
cert, @dsa512, OpenSSL::Digest::DSS1.new)
assert_equal(false, crl.verify(@rsa1024))
assert_equal(false, crl.verify(@rsa2048))
assert_equal(false, crl.verify(@dsa256))
assert_equal(true, crl.verify(@dsa512))
crl.version = 0
assert_equal(false, crl.verify(@dsa512))
end
def test_create_from_pem
crl = <<END
-----BEGIN X509 CRL-----
MIHkME8CAQEwDQYJKoZIhvcNAQEFBQAwDTELMAkGA1UEAwwCY2EXDTA5MDUyMzEw
MTkyM1oXDTE0MDUyMjEwMTkyM1qgDjAMMAoGA1UdFAQDAgEAMA0GCSqGSIb3DQEB
BQUAA4GBAGrGXN03TQdoluA5Xjv64We9EOvmE0EviKMeaZ/n8krEwFhUK7Yq3GVD
BFrb40cdFX1433buCZHG7Tq7eGv8cG1eO5RasuiedurMQXmVRDTDjGor/58Dk/Wy
owO/GR8ASm6Fx6AUKEgLAaoaaptpaWtEB+N4uaGvc0LFO9WY+ZMq
-----END X509 CRL-----
END
crl = OpenSSL::X509::CRL.new(crl)
assert_equal(1, crl.version)
assert_equal(OpenSSL::X509::Name.parse("/CN=ca").to_der, crl.issuer.to_der)
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/openssl/utils.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/openssl/utils.rb | require "openssl"
require "test/unit"
module OpenSSL::TestUtils
TEST_KEY_RSA1024 = OpenSSL::PKey::RSA.new <<-_end_of_pem_
-----BEGIN RSA PRIVATE KEY-----
MIICXgIBAAKBgQDLwsSw1ECnPtT+PkOgHhcGA71nwC2/nL85VBGnRqDxOqjVh7Cx
aKPERYHsk4BPCkE3brtThPWc9kjHEQQ7uf9Y1rbCz0layNqHyywQEVLFmp1cpIt/
Q3geLv8ZD9pihowKJDyMDiN6ArYUmZczvW4976MU3+l54E6lF/JfFEU5hwIDAQAB
AoGBAKSl/MQarye1yOysqX6P8fDFQt68VvtXkNmlSiKOGuzyho0M+UVSFcs6k1L0
maDE25AMZUiGzuWHyaU55d7RXDgeskDMakD1v6ZejYtxJkSXbETOTLDwUWTn618T
gnb17tU1jktUtU67xK/08i/XodlgnQhs6VoHTuCh3Hu77O6RAkEA7+gxqBuZR572
74/akiW/SuXm0SXPEviyO1MuSRwtI87B02D0qgV8D1UHRm4AhMnJ8MCs1809kMQE
JiQUCrp9mQJBANlt2ngBO14us6NnhuAseFDTBzCHXwUUu1YKHpMMmxpnGqaldGgX
sOZB3lgJsT9VlGf3YGYdkLTNVbogQKlKpB8CQQDiSwkb4vyQfDe8/NpU5Not0fII
8jsDUCb+opWUTMmfbxWRR3FBNu8wnym/m19N4fFj8LqYzHX4KY0oVPu6qvJxAkEA
wa5snNekFcqONLIE4G5cosrIrb74sqL8GbGb+KuTAprzj5z1K8Bm0UW9lTjVDjDi
qRYgZfZSL+x1P/54+xTFSwJAY1FxA/N3QPCXCjPh5YqFxAMQs2VVYTfg+t0MEcJD
dPMQD5JX6g5HKnHFg2mZtoXQrWmJSn7p8GJK8yNTopEErA==
-----END RSA PRIVATE KEY-----
_end_of_pem_
TEST_KEY_RSA2048 = OpenSSL::PKey::RSA.new <<-_end_of_pem_
-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEAuV9ht9J7k4NBs38jOXvvTKY9gW8nLICSno5EETR1cuF7i4pN
s9I1QJGAFAX0BEO4KbzXmuOvfCpD3CU+Slp1enenfzq/t/e/1IRW0wkJUJUFQign
4CtrkJL+P07yx18UjyPlBXb81ApEmAB5mrJVSrWmqbjs07JbuS4QQGGXLc+Su96D
kYKmSNVjBiLxVVSpyZfAY3hD37d60uG+X8xdW5v68JkRFIhdGlb6JL8fllf/A/bl
NwdJOhVr9mESHhwGjwfSeTDPfd8ZLE027E5lyAVX9KZYcU00mOX+fdxOSnGqS/8J
DRh0EPHDL15RcJjV2J6vZjPb0rOYGDoMcH+94wIDAQABAoIBAAzsamqfYQAqwXTb
I0CJtGg6msUgU7HVkOM+9d3hM2L791oGHV6xBAdpXW2H8LgvZHJ8eOeSghR8+dgq
PIqAffo4x1Oma+FOg3A0fb0evyiACyrOk+EcBdbBeLo/LcvahBtqnDfiUMQTpy6V
seSoFCwuN91TSCeGIsDpRjbG1vxZgtx+uI+oH5+ytqJOmfCksRDCkMglGkzyfcl0
Xc5CUhIJ0my53xijEUQl19rtWdMnNnnkdbG8PT3LZlOta5Do86BElzUYka0C6dUc
VsBDQ0Nup0P6rEQgy7tephHoRlUGTYamsajGJaAo1F3IQVIrRSuagi7+YpSpCqsW
wORqorkCgYEA7RdX6MDVrbw7LePnhyuaqTiMK+055/R1TqhB1JvvxJ1CXk2rDL6G
0TLHQ7oGofd5LYiemg4ZVtWdJe43BPZlVgT6lvL/iGo8JnrncB9Da6L7nrq/+Rvj
XGjf1qODCK+LmreZWEsaLPURIoR/Ewwxb9J2zd0CaMjeTwafJo1CZvcCgYEAyCgb
aqoWvUecX8VvARfuA593Lsi50t4MEArnOXXcd1RnXoZWhbx5rgO8/ATKfXr0BK/n
h2GF9PfKzHFm/4V6e82OL7gu/kLy2u9bXN74vOvWFL5NOrOKPM7Kg+9I131kNYOw
Ivnr/VtHE5s0dY7JChYWE1F3vArrOw3T00a4CXUCgYEA0SqY+dS2LvIzW4cHCe9k
IQqsT0yYm5TFsUEr4sA3xcPfe4cV8sZb9k/QEGYb1+SWWZ+AHPV3UW5fl8kTbSNb
v4ng8i8rVVQ0ANbJO9e5CUrepein2MPL0AkOATR8M7t7dGGpvYV0cFk8ZrFx0oId
U0PgYDotF/iueBWlbsOM430CgYEAqYI95dFyPI5/AiSkY5queeb8+mQH62sdcCCr
vd/w/CZA/K5sbAo4SoTj8dLk4evU6HtIa0DOP63y071eaxvRpTNqLUOgmLh+D6gS
Cc7TfLuFrD+WDBatBd5jZ+SoHccVrLR/4L8jeodo5FPW05A+9gnKXEXsTxY4LOUC
9bS4e1kCgYAqVXZh63JsMwoaxCYmQ66eJojKa47VNrOeIZDZvd2BPVf30glBOT41
gBoDG3WMPZoQj9pb7uMcrnvs4APj2FIhMU8U15LcPAj59cD6S6rWnAxO8NFK7HQG
4Jxg3JNNf8ErQoCHb1B3oVdXJkmbJkARoDpBKmTCgKtP8ADYLmVPQw==
-----END RSA PRIVATE KEY-----
_end_of_pem_
TEST_KEY_DSA256 = OpenSSL::PKey::DSA.new <<-_end_of_pem_
-----BEGIN DSA PRIVATE KEY-----
MIH3AgEAAkEAhk2libbY2a8y2Pt21+YPYGZeW6wzaW2yfj5oiClXro9XMR7XWLkE
9B7XxLNFCS2gmCCdMsMW1HulaHtLFQmB2wIVAM43JZrcgpu6ajZ01VkLc93gu/Ed
AkAOhujZrrKV5CzBKutKLb0GVyVWmdC7InoNSMZEeGU72rT96IjM59YzoqmD0pGM
3I1o4cGqg1D1DfM1rQlnN1eSAkBq6xXfEDwJ1mLNxF6q8Zm/ugFYWR5xcX/3wFiT
b4+EjHP/DbNh9Vm5wcfnDBJ1zKvrMEf2xqngYdrV/3CiGJeKAhRvL57QvJZcQGvn
ISNX5cMzFHRW3Q==
-----END DSA PRIVATE KEY-----
_end_of_pem_
TEST_KEY_DSA512 = OpenSSL::PKey::DSA.new <<-_end_of_pem_
-----BEGIN DSA PRIVATE KEY-----
MIH4AgEAAkEA5lB4GvEwjrsMlGDqGsxrbqeFRh6o9OWt6FgTYiEEHaOYhkIxv0Ok
RZPDNwOG997mDjBnvDJ1i56OmS3MbTnovwIVAJgub/aDrSDB4DZGH7UyarcaGy6D
AkB9HdFw/3td8K4l1FZHv7TCZeJ3ZLb7dF3TWoGUP003RCqoji3/lHdKoVdTQNuR
S/m6DlCwhjRjiQ/lBRgCLCcaAkEAjN891JBjzpMj4bWgsACmMggFf57DS0Ti+5++
Q1VB8qkJN7rA7/2HrCR3gTsWNb1YhAsnFsoeRscC+LxXoXi9OAIUBG98h4tilg6S
55jreJD3Se3slps=
-----END DSA PRIVATE KEY-----
_end_of_pem_
module_function
def issue_cert(dn, key, serial, not_before, not_after, extensions,
issuer, issuer_key, digest)
cert = OpenSSL::X509::Certificate.new
issuer = cert unless issuer
issuer_key = key unless issuer_key
cert.version = 2
cert.serial = serial
cert.subject = dn
cert.issuer = issuer.subject
cert.public_key = key.public_key
cert.not_before = not_before
cert.not_after = not_after
ef = OpenSSL::X509::ExtensionFactory.new
ef.subject_certificate = cert
ef.issuer_certificate = issuer
extensions.each{|oid, value, critical|
cert.add_extension(ef.create_extension(oid, value, critical))
}
cert.sign(issuer_key, digest)
cert
end
def issue_crl(revoke_info, serial, lastup, nextup, extensions,
issuer, issuer_key, digest)
crl = OpenSSL::X509::CRL.new
crl.issuer = issuer.subject
crl.version = 1
crl.last_update = lastup
crl.next_update = nextup
revoke_info.each{|serial, time, reason_code|
revoked = OpenSSL::X509::Revoked.new
revoked.serial = serial
revoked.time = time
enum = OpenSSL::ASN1::Enumerated(reason_code)
ext = OpenSSL::X509::Extension.new("CRLReason", enum)
revoked.add_extension(ext)
crl.add_revoked(revoked)
}
ef = OpenSSL::X509::ExtensionFactory.new
ef.issuer_certificate = issuer
ef.crl = crl
crlnum = OpenSSL::ASN1::Integer(serial)
crl.add_extension(OpenSSL::X509::Extension.new("crlNumber", crlnum))
extensions.each{|oid, value, critical|
crl.add_extension(ef.create_extension(oid, value, critical))
}
crl.sign(issuer_key, digest)
crl
end
def get_subject_key_id(cert)
asn1_cert = OpenSSL::ASN1.decode(cert)
tbscert = asn1_cert.value[0]
pkinfo = tbscert.value[6]
publickey = pkinfo.value[1]
pkvalue = publickey.value
OpenSSL::Digest::SHA1.hexdigest(pkvalue).scan(/../).join(":").upcase
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/openssl/test_x509cert.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/openssl/test_x509cert.rb | begin
require "openssl"
require File.join(File.dirname(__FILE__), "utils.rb")
rescue LoadError
end
require "test/unit"
if defined?(OpenSSL)
class OpenSSL::TestX509Certificate < Test::Unit::TestCase
def setup
@rsa1024 = OpenSSL::TestUtils::TEST_KEY_RSA1024
@rsa2048 = OpenSSL::TestUtils::TEST_KEY_RSA2048
@dsa256 = OpenSSL::TestUtils::TEST_KEY_DSA256
@dsa512 = OpenSSL::TestUtils::TEST_KEY_DSA512
@ca = OpenSSL::X509::Name.parse("/DC=org/DC=ruby-lang/CN=CA")
@ee1 = OpenSSL::X509::Name.parse("/DC=org/DC=ruby-lang/CN=EE1")
@ee2 = OpenSSL::X509::Name.parse("/DC=org/DC=ruby-lang/CN=EE2")
end
def teardown
end
def issue_cert(*args)
OpenSSL::TestUtils.issue_cert(*args)
end
def test_serial
[1, 2**32, 2**100].each{|s|
cert = issue_cert(@ca, @rsa2048, s, Time.now, Time.now+3600, [],
nil, nil, OpenSSL::Digest::SHA1.new)
assert_equal(s, cert.serial)
cert = OpenSSL::X509::Certificate.new(cert.to_der)
assert_equal(s, cert.serial)
}
end
def test_public_key
exts = [
["basicConstraints","CA:TRUE",true],
["subjectKeyIdentifier","hash",false],
["authorityKeyIdentifier","keyid:always",false],
]
sha1 = OpenSSL::Digest::SHA1.new
dss1 = OpenSSL::Digest::DSS1.new
[
[@rsa1024, sha1], [@rsa2048, sha1], [@dsa256, dss1], [@dsa512, dss1],
].each{|pk, digest|
cert = issue_cert(@ca, pk, 1, Time.now, Time.now+3600, exts,
nil, nil, digest)
assert_equal(cert.extensions[1].value,
OpenSSL::TestUtils.get_subject_key_id(cert))
cert = OpenSSL::X509::Certificate.new(cert.to_der)
assert_equal(cert.extensions[1].value,
OpenSSL::TestUtils.get_subject_key_id(cert))
}
end
def test_validity
now = Time.now until now && now.usec != 0
cert = issue_cert(@ca, @rsa2048, 1, now, now+3600, [],
nil, nil, OpenSSL::Digest::SHA1.new)
assert_not_equal(now, cert.not_before)
assert_not_equal(now+3600, cert.not_after)
now = Time.at(now.to_i)
cert = issue_cert(@ca, @rsa2048, 1, now, now+3600, [],
nil, nil, OpenSSL::Digest::SHA1.new)
assert_equal(now.getutc, cert.not_before)
assert_equal((now+3600).getutc, cert.not_after)
now = Time.at(0)
cert = issue_cert(@ca, @rsa2048, 1, now, now, [],
nil, nil, OpenSSL::Digest::SHA1.new)
assert_equal(now.getutc, cert.not_before)
assert_equal(now.getutc, cert.not_after)
now = Time.at(0x7fffffff)
cert = issue_cert(@ca, @rsa2048, 1, now, now, [],
nil, nil, OpenSSL::Digest::SHA1.new)
assert_equal(now.getutc, cert.not_before)
assert_equal(now.getutc, cert.not_after)
end
def test_extension
ca_exts = [
["basicConstraints","CA:TRUE",true],
["keyUsage","keyCertSign, cRLSign",true],
["subjectKeyIdentifier","hash",false],
["authorityKeyIdentifier","keyid:always",false],
]
ca_cert = issue_cert(@ca, @rsa2048, 1, Time.now, Time.now+3600, ca_exts,
nil, nil, OpenSSL::Digest::SHA1.new)
ca_cert.extensions.each_with_index{|ext, i|
assert_equal(ca_exts[i].first, ext.oid)
assert_equal(ca_exts[i].last, ext.critical?)
}
ee1_exts = [
["keyUsage","Non Repudiation, Digital Signature, Key Encipherment",true],
["subjectKeyIdentifier","hash",false],
["authorityKeyIdentifier","keyid:always",false],
["extendedKeyUsage","clientAuth, emailProtection, codeSigning",false],
["subjectAltName","email:ee1@ruby-lang.org",false],
]
ee1_cert = issue_cert(@ee1, @rsa1024, 2, Time.now, Time.now+1800, ee1_exts,
ca_cert, @rsa2048, OpenSSL::Digest::SHA1.new)
assert_equal(ca_cert.subject.to_der, ee1_cert.issuer.to_der)
ee1_cert.extensions.each_with_index{|ext, i|
assert_equal(ee1_exts[i].first, ext.oid)
assert_equal(ee1_exts[i].last, ext.critical?)
}
ee2_exts = [
["keyUsage","Non Repudiation, Digital Signature, Key Encipherment",true],
["subjectKeyIdentifier","hash",false],
["authorityKeyIdentifier","issuer:always",false],
["extendedKeyUsage","clientAuth, emailProtection, codeSigning",false],
["subjectAltName","email:ee2@ruby-lang.org",false],
]
ee2_cert = issue_cert(@ee2, @rsa1024, 3, Time.now, Time.now+1800, ee2_exts,
ca_cert, @rsa2048, OpenSSL::Digest::MD5.new)
assert_equal(ca_cert.subject.to_der, ee2_cert.issuer.to_der)
ee2_cert.extensions.each_with_index{|ext, i|
assert_equal(ee2_exts[i].first, ext.oid)
assert_equal(ee2_exts[i].last, ext.critical?)
}
end
def test_sign_and_verify
cert = issue_cert(@ca, @rsa2048, 1, Time.now, Time.now+3600, [],
nil, nil, OpenSSL::Digest::SHA1.new)
assert_equal(false, cert.verify(@rsa1024))
assert_equal(true, cert.verify(@rsa2048))
assert_equal(false, cert.verify(@dsa256))
assert_equal(false, cert.verify(@dsa512))
cert.serial = 2
assert_equal(false, cert.verify(@rsa2048))
cert = issue_cert(@ca, @rsa2048, 1, Time.now, Time.now+3600, [],
nil, nil, OpenSSL::Digest::MD5.new)
assert_equal(false, cert.verify(@rsa1024))
assert_equal(true, cert.verify(@rsa2048))
assert_equal(false, cert.verify(@dsa256))
assert_equal(false, cert.verify(@dsa512))
cert.subject = @ee1
assert_equal(false, cert.verify(@rsa2048))
cert = issue_cert(@ca, @dsa512, 1, Time.now, Time.now+3600, [],
nil, nil, OpenSSL::Digest::DSS1.new)
assert_equal(false, cert.verify(@rsa1024))
assert_equal(false, cert.verify(@rsa2048))
assert_equal(false, cert.verify(@dsa256))
assert_equal(true, cert.verify(@dsa512))
cert.not_after = Time.now
assert_equal(false, cert.verify(@dsa512))
assert_raise(OpenSSL::X509::CertificateError){
cert = issue_cert(@ca, @rsa2048, 1, Time.now, Time.now+3600, [],
nil, nil, OpenSSL::Digest::DSS1.new)
}
assert_raise(OpenSSL::X509::CertificateError){
cert = issue_cert(@ca, @dsa512, 1, Time.now, Time.now+3600, [],
nil, nil, OpenSSL::Digest::MD5.new)
}
assert_raise(OpenSSL::X509::CertificateError){
cert = issue_cert(@ca, @dsa512, 1, Time.now, Time.now+3600, [],
nil, nil, OpenSSL::Digest::SHA1.new)
}
end
def test_check_private_key
cert = issue_cert(@ca, @rsa2048, 1, Time.now, Time.now+3600, [],
nil, nil, OpenSSL::Digest::SHA1.new)
assert_equal(true, cert.check_private_key(@rsa2048))
end
def test_to_text
cert_pem = <<END
-----BEGIN CERTIFICATE-----
MIIC8zCCAdugAwIBAgIBATANBgkqhkiG9w0BAQQFADA9MRMwEQYKCZImiZPyLGQB
GRYDb3JnMRkwFwYKCZImiZPyLGQBGRYJcnVieS1sYW5nMQswCQYDVQQDDAJDQTAe
Fw0wOTA1MjMxNTAzNDNaFw0wOTA1MjMxNjAzNDNaMD0xEzARBgoJkiaJk/IsZAEZ
FgNvcmcxGTAXBgoJkiaJk/IsZAEZFglydWJ5LWxhbmcxCzAJBgNVBAMMAkNBMIIB
IjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuV9ht9J7k4NBs38jOXvvTKY9
gW8nLICSno5EETR1cuF7i4pNs9I1QJGAFAX0BEO4KbzXmuOvfCpD3CU+Slp1enen
fzq/t/e/1IRW0wkJUJUFQign4CtrkJL+P07yx18UjyPlBXb81ApEmAB5mrJVSrWm
qbjs07JbuS4QQGGXLc+Su96DkYKmSNVjBiLxVVSpyZfAY3hD37d60uG+X8xdW5v6
8JkRFIhdGlb6JL8fllf/A/blNwdJOhVr9mESHhwGjwfSeTDPfd8ZLE027E5lyAVX
9KZYcU00mOX+fdxOSnGqS/8JDRh0EPHDL15RcJjV2J6vZjPb0rOYGDoMcH+94wID
AQABMA0GCSqGSIb3DQEBBAUAA4IBAQB8UTw1agA9wdXxHMUACduYu6oNL7pdF0dr
w7a4QPJyj62h4+Umxvp13q0PBw0E+mSjhXMcqUhDLjrmMcvvNGhuh5Sdjbe3GI/M
3lCC9OwYYIzzul7omvGC3JEIGfzzdNnPPCPKEWp5X9f0MKLMR79qOf+sjHTjN2BY
SY3YGsEFxyTXDdqrlaYaOtTAdi/C+g1WxR8fkPLefymVwIFwvyc9/bnp7iBn7Hcw
mbxtLPbtQ9mURT0GHewZRTGJ1aiTq9Ag3xXME2FPF04eFRd3mclOQZNXKQ+LDxYf
k0X5FeZvsWf4srFxoVxlcDdJtHh91ZRpDDJYGQlsUm9CPTnO+e4E
-----END CERTIFICATE-----
END
cert = OpenSSL::X509::Certificate.new(cert_pem)
cert_text = <<END
[0] Version: 3
SerialNumber: 1
IssuerDN: DC=org,DC=ruby-lang,CN=CA
Start Date: Sat May 23 17:03:43 CEST 2009
Final Date: Sat May 23 18:03:43 CEST 2009
SubjectDN: DC=org,DC=ruby-lang,CN=CA
Public Key: RSA Public Key
modulus: b95f61b7d27b938341b37f23397bef4ca63d816f272c80929e8e4411347572e17b8b8a4db3d2354091801405f40443b829bcd79ae3af7c2a43dc253e4a5a757a77a77f3abfb7f7bfd48456d30909509505422827e02b6b9092fe3f4ef2c75f148f23e50576fcd40a449800799ab2554ab5a6a9b8ecd3b25bb92e104061972dcf92bbde839182a648d5630622f15554a9c997c0637843dfb77ad2e1be5fcc5d5b9bfaf0991114885d1a56fa24bf1f9657ff03f6e53707493a156bf661121e1c068f07d27930cf7ddf192c4d36ec4e65c80557f4a658714d3498e5fe7ddc4e4a71aa4bff090d187410f1c32f5e517098d5d89eaf6633dbd2b398183a0c707fbde3
public exponent: 10001
Signature Algorithm: MD5withRSA
Signature: 7c513c356a003dc1d5f11cc50009db98bbaa0d2f
ba5d17476bc3b6b840f2728fada1e3e526c6fa75
dead0f070d04fa64a385731ca948432e3ae631cb
ef34686e87949d8db7b7188fccde5082f4ec1860
8cf3ba5ee89af182dc910819fcf374d9cf3c23ca
116a795fd7f430a2cc47bf6a39ffac8c74e33760
58498dd81ac105c724d70ddaab95a61a3ad4c076
2fc2fa0d56c51f1f90f2de7f2995c08170bf273d
fdb9e9ee2067ec773099bc6d2cf6ed43d994453d
061dec19453189d5a893abd020df15cc13614f17
4e1e15177799c94e419357290f8b0f161f9345f9
15e66fb167f8b2b171a15c65703749b4787dd594
690c325819096c526f423d39cef9ee04
END
assert_not_nil(cert.to_text)
# This is commented out because it doesn't take timezone into consideration; FIXME
#assert_equal(cert_text, cert.to_text)
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/openssl/test_ec.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/openssl/test_ec.rb | begin
require "openssl"
require File.join(File.dirname(__FILE__), "utils.rb")
rescue LoadError
end
require "test/unit"
if defined?(OpenSSL::PKey::EC)
class OpenSSL::TestEC < Test::Unit::TestCase
def setup
@data1 = 'foo'
@data2 = 'bar' * 1000 # data too long for DSA sig
@group1 = OpenSSL::PKey::EC::Group.new('secp112r1')
@group2 = OpenSSL::PKey::EC::Group.new('sect163k1')
@key1 = OpenSSL::PKey::EC.new
@key1.group = @group1
@key1.generate_key
@key2 = OpenSSL::PKey::EC.new(@group2.curve_name)
@key2.generate_key
@groups = [@group1, @group2]
@keys = [@key1, @key2]
end
def compare_keys(k1, k2)
assert_equal(k1.to_pem, k2.to_pem)
end
def test_curve_names
@groups.each_with_index do |group, idx|
key = @keys[idx]
assert_equal(group.curve_name, key.group.curve_name)
end
end
def test_check_key
for key in @keys
assert_equal(key.check_key, true)
assert_equal(key.private_key?, true)
assert_equal(key.public_key?, true)
end
end
def test_encoding
for group in @groups
for meth in [:to_der, :to_pem]
txt = group.send(meth)
gr = OpenSSL::PKey::EC::Group.new(txt)
assert_equal(txt, gr.send(meth))
assert_equal(group.generator.to_bn, gr.generator.to_bn)
assert_equal(group.cofactor, gr.cofactor)
assert_equal(group.order, gr.order)
assert_equal(group.seed, gr.seed)
assert_equal(group.degree, gr.degree)
end
end
for key in @keys
group = key.group
for meth in [:to_der, :to_pem]
txt = key.send(meth)
assert_equal(txt, OpenSSL::PKey::EC.new(txt).send(meth))
end
bn = key.public_key.to_bn
assert_equal(bn, OpenSSL::PKey::EC::Point.new(group, bn).to_bn)
end
end
def test_set_keys
for key in @keys
k = OpenSSL::PKey::EC.new
k.group = key.group
k.private_key = key.private_key
k.public_key = key.public_key
compare_keys(key, k)
end
end
def test_dsa_sign_verify
for key in @keys
sig = key.dsa_sign_asn1(@data1)
assert_equal(key.dsa_verify_asn1(@data1, sig), true)
assert_raise(OpenSSL::PKey::ECError) { key.dsa_sign_asn1(@data2) }
end
end
def test_dh_compute_key
for key in @keys
k = OpenSSL::PKey::EC.new(key.group)
k.generate_key
puba = key.public_key
pubb = k.public_key
a = key.dh_compute_key(pubb)
b = k.dh_compute_key(puba)
assert_equal(a, b)
end
end
# test Group: asn1_flag, point_conversion
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/openssl/test_cipher.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/openssl/test_cipher.rb | begin
require "openssl"
rescue LoadError
end
require "test/unit"
if defined?(OpenSSL)
class OpenSSL::TestCipher < Test::Unit::TestCase
def setup
@c1 = OpenSSL::Cipher::Cipher.new("DES-EDE3-CBC")
@c2 = OpenSSL::Cipher::DES.new(:EDE3, "CBC")
@key = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
@iv = "\0\0\0\0\0\0\0\0"
@iv1 = "\1\1\1\1\1\1\1\1"
@hexkey = "0000000000000000000000000000000000000000000000"
@hexiv = "0000000000000000"
@data = "DATA"
end
def teardown
@c1 = @c2 = nil
end
def test_crypt
@c1.encrypt.pkcs5_keyivgen(@key, @iv)
@c2.encrypt.pkcs5_keyivgen(@key, @iv)
s1 = @c1.update(@data) + @c1.final
s2 = @c2.update(@data) + @c2.final
assert_equal(s1, s2, "encrypt")
@c1.decrypt.pkcs5_keyivgen(@key, @iv)
@c2.decrypt.pkcs5_keyivgen(@key, @iv)
assert_equal(@data, @c1.update(s1)+@c1.final, "decrypt")
assert_equal(@data, @c2.update(s2)+@c2.final, "decrypt")
end
def test_info
assert_equal("DES-EDE3-CBC", @c1.name, "name")
assert_equal("DES-EDE3-CBC", @c2.name, "name")
assert_kind_of(Fixnum, @c1.key_len, "key_len")
assert_kind_of(Fixnum, @c1.iv_len, "iv_len")
end
def test_dup
assert_equal(@c1.name, @c1.dup.name, "dup")
assert_equal(@c1.name, @c1.clone.name, "clone")
@c1.encrypt
@c1.key = @key
@c1.iv = @iv
tmpc = @c1.dup
s1 = @c1.update(@data) + @c1.final
s2 = tmpc.update(@data) + tmpc.final
assert_equal(s1, s2, "encrypt dup")
end
def test_reset
@c1.encrypt
@c1.key = @key
@c1.iv = @iv
s1 = @c1.update(@data) + @c1.final
@c1.reset
s2 = @c1.update(@data) + @c1.final
assert_equal(s1, s2, "encrypt reset")
end
def test_set_iv
@c1.encrypt
@c1.key = @key
@c1.iv = @iv
s1 = @c1.update(@data) + @c1.final
@c1.iv = @iv1
s1 += @c1.update(@data) + @c1.final
@c1.reset
@c1.iv = @iv
s2 = @c1.update(@data) + @c1.final
@c1.iv = @iv1
s2 += @c1.update(@data) + @c1.final
assert_equal(s1, s2, "encrypt reset")
end
def test_empty_data
@c1.encrypt
assert_raise(ArgumentError){ @c1.update("") }
end
def test_disable_padding(padding=0)
# assume a padding size of 8
# encrypt the data with padding
@c1.encrypt
@c1.key = @key
@c1.iv = @iv
encrypted_data = @c1.update(@data) + @c1.final
assert_equal(8, encrypted_data.size)
# decrypt with padding disabled
@c1.decrypt
@c1.padding = padding
decrypted_data = @c1.update(encrypted_data) + @c1.final
# check that the result contains the padding
assert_equal(8, decrypted_data.size)
assert_equal(@data, decrypted_data[0...@data.size])
end
if PLATFORM =~ /java/
# JRuby extension - using Java padding types
def test_disable_padding_javastyle
test_disable_padding('NoPadding')
end
def test_iso10126_padding
@c1.encrypt
@c1.key = @key
@c1.iv = @iv
@c1.padding = 'ISO10126Padding'
encrypted_data = @c1.update(@data) + @c1.final
# decrypt with padding disabled to see the padding
@c1.decrypt
@c1.padding = 0
decrypted_data = @c1.update(encrypted_data) + @c1.final
assert_equal(@data, decrypted_data[0...@data.size])
# last byte should be the amount of padding
assert_equal(4, decrypted_data[-1])
end
def test_iso10126_padding_boundry
@data = 'HELODATA' # 8 bytes, same as padding size
@c1.encrypt
@c1.key = @key
@c1.iv = @iv
@c1.padding = 'ISO10126Padding'
encrypted_data = @c1.update(@data) + @c1.final
# decrypt with padding disabled to see the padding
@c1.decrypt
@c1.padding = 0
decrypted_data = @c1.update(encrypted_data) + @c1.final
assert_equal(@data, decrypted_data[0...@data.size])
# padding should be one whole block
assert_equal(8, decrypted_data[-1])
end
end
if OpenSSL::OPENSSL_VERSION_NUMBER > 0x00907000
def test_ciphers
OpenSSL::Cipher.ciphers.each{|name|
assert(OpenSSL::Cipher::Cipher.new(name).is_a?(OpenSSL::Cipher::Cipher))
}
end
def test_AES
pt = File.read(__FILE__)
%w(ECB CBC CFB OFB).each{|mode|
c1 = OpenSSL::Cipher::AES256.new(mode)
c1.encrypt
assert_nothing_raised('This test fails w/o Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files') do
c1.pkcs5_keyivgen("passwd")
end
ct = c1.update(pt) + c1.final
c2 = OpenSSL::Cipher::AES256.new(mode)
c2.decrypt
c2.pkcs5_keyivgen("passwd")
assert_equal(pt, c2.update(ct) + c2.final)
}
end
end
# JRUBY-4028
def test_jruby_4028
key = "0599E113A7EE32A9"
data = "1234567890~5J96LC303C1D22DD~20090930005944~http%3A%2F%2Flocalhost%3A8080%2Flogin%3B0%3B1~http%3A%2F%2Fmix-stage.oracle.com%2F~00"
c1 = OpenSSL::Cipher::Cipher.new("DES-CBC")
c1.padding = 0
c1.iv = "0" * 8
c1.encrypt
c1.key = key
e = c1.update data
e << c1.final
c2 = OpenSSL::Cipher::Cipher.new("DES-CBC")
c2.padding = 0
c2.iv = "0" * 8
c2.decrypt
c2.key = key
d = c2.update e
d << c2.final
assert_equal "\342\320B.\300&X\310\344\253\025\215\017*\22015\344\024D\342\213\361\336\311\271\326\016\243\214\026\2545\002\237,\017s\202\316&Ew\323\221H\376\200\304\201\365\332Im\240\361\037\246\3536\001A2\341\324o0\350\364%=\325\330\240\324u\225\304h\277\272\361f\024\324\352\336\353N\002/]C\370!\003)\212oa\225\207\333\340\245\207\024\351\037\327[\212\001{\216\f\315\345\372\v\226\r\233?\002\vJK", e
assert_equal data, d
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/openssl/test_x509ext.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/openssl/test_x509ext.rb | begin
require "openssl"
require File.join(File.dirname(__FILE__), "utils.rb")
rescue LoadError
end
require "test/unit"
if defined?(OpenSSL)
class OpenSSL::TestX509Extension < Test::Unit::TestCase
def setup
@basic_constraints_value = OpenSSL::ASN1::Sequence([
OpenSSL::ASN1::Boolean(true), # CA
OpenSSL::ASN1::Integer(2) # pathlen
])
@basic_constraints = OpenSSL::ASN1::Sequence([
OpenSSL::ASN1::ObjectId("basicConstraints"),
OpenSSL::ASN1::Boolean(true),
OpenSSL::ASN1::OctetString(@basic_constraints_value.to_der),
])
end
def teardown
end
def test_new
ext = OpenSSL::X509::Extension.new(@basic_constraints.to_der)
assert_equal("basicConstraints", ext.oid)
assert_equal(true, ext.critical?)
assert_equal("CA:TRUE, pathlen:2", ext.value)
ext = OpenSSL::X509::Extension.new("2.5.29.19",
@basic_constraints_value.to_der, true)
assert_equal(@basic_constraints.to_der, ext.to_der)
end
def test_create_by_factory
ef = OpenSSL::X509::ExtensionFactory.new
bc = ef.create_extension("basicConstraints", "critical, CA:TRUE, pathlen:2")
assert_equal(@basic_constraints.to_der, bc.to_der)
bc = ef.create_extension("basicConstraints", "CA:TRUE, pathlen:2", true)
assert_equal(@basic_constraints.to_der, bc.to_der)
begin
ef.config = OpenSSL::Config.parse(<<-_end_of_cnf_)
[crlDistPts]
URI.1 = http://www.example.com/crl
URI.2 = ldap://ldap.example.com/cn=ca?certificateRevocationList;binary
_end_of_cnf_
rescue NotImplementedError
return
end
cdp = ef.create_extension("crlDistributionPoints", "@crlDistPts")
assert_equal(false, cdp.critical?)
assert_equal("crlDistributionPoints", cdp.oid)
assert_match(%{URI:http://www\.example\.com/crl}, cdp.value)
assert_match(
%r{URI:ldap://ldap\.example\.com/cn=ca\?certificateRevocationList;binary},
cdp.value)
cdp = ef.create_extension("crlDistributionPoints", "critical, @crlDistPts")
assert_equal(true, cdp.critical?)
assert_equal("crlDistributionPoints", cdp.oid)
assert_match(%{URI:http://www.example.com/crl}, cdp.value)
assert_match(
%r{URI:ldap://ldap.example.com/cn=ca\?certificateRevocationList;binary},
cdp.value)
end
# JRUBY-3888
# Problems with subjectKeyIdentifier with non 20-bytes sha1 digested keys
def test_certificate_with_rare_extension
cert_file = File.expand_path('../fixture/max.pem', File.dirname(__FILE__))
cer = OpenSSL::X509::Certificate.new(File.read(cert_file))
exts = Hash.new
cer.extensions.each{|ext| exts[ext.oid] = ext.value}
assert exts["subjectKeyIdentifier"] == "4C:B9:E1:DC:7A:AC:35:CF"
end
def test_extension_from_20_byte_sha1_digests
cert_file = File.expand_path('../fixture/common.pem', File.dirname(__FILE__))
cer = OpenSSL::X509::Certificate.new(File.read(cert_file))
exts = Hash.new
cer.extensions.each{|ext| exts[ext.oid] = ext.value}
assert exts["subjectKeyIdentifier"] == "B4:AC:83:5D:21:FB:D6:8A:56:7E:B2:49:6D:69:BB:E4:6F:D8:5A:AC"
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/openssl/test_ns_spki.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/openssl/test_ns_spki.rb | begin
require "openssl"
require File.join(File.dirname(__FILE__), "utils.rb")
rescue LoadError
end
require "test/unit"
if defined?(OpenSSL)
class OpenSSL::TestNSSPI < Test::Unit::TestCase
def setup
# This request data is adopt from the specification of
# "Netscape Extensions for User Key Generation".
# -- http://wp.netscape.com/eng/security/comm4-keygen.html
@b64 = "MIHFMHEwXDANBgkqhkiG9w0BAQEFAANLADBIAkEAnX0TILJrOMUue+PtwBRE6XfV"
@b64 << "WtKQbsshxk5ZhcUwcwyvcnIq9b82QhJdoACdD34rqfCAIND46fXKQUnb0mvKzQID"
@b64 << "AQABFhFNb3ppbGxhSXNNeUZyaWVuZDANBgkqhkiG9w0BAQQFAANBAAKv2Eex2n/S"
@b64 << "r/7iJNroWlSzSMtTiQTEB+ADWHGj9u1xrUrOilq/o2cuQxIfZcNZkYAkWP4DubqW"
@b64 << "i0//rgBvmco="
end
def teardown
end
def pr(obj, ind=0)
if obj.respond_to?(:value)
puts((" "*ind) + obj.class.to_s + ":")
pr(obj.value,(ind+1))
elsif obj.respond_to?(:each) && !(String===obj)
obj.each {|v| pr(v,ind+1) }
else
puts((" "*ind) + obj.inspect)
end
end
def test_build_data
key1 = OpenSSL::TestUtils::TEST_KEY_RSA1024
key2 = OpenSSL::TestUtils::TEST_KEY_RSA2048
spki = OpenSSL::Netscape::SPKI.new
spki.challenge = "RandomString"
spki.public_key = key1.public_key
spki.sign(key1, OpenSSL::Digest::SHA1.new)
assert(spki.verify(spki.public_key))
assert(spki.verify(key1.public_key))
assert(!spki.verify(key2.public_key))
der = spki.to_der
spki = OpenSSL::Netscape::SPKI.new(der)
assert_equal("RandomString", spki.challenge)
assert_equal(key1.public_key.to_der, spki.public_key.to_der)
assert(spki.verify(spki.public_key))
end
def test_decode_data
spki = OpenSSL::Netscape::SPKI.new(@b64)
assert_equal(@b64, spki.to_pem)
assert_equal(@b64.unpack("m").first, spki.to_der)
assert_equal("MozillaIsMyFriend", spki.challenge)
assert_equal(OpenSSL::PKey::RSA, spki.public_key.class)
spki = OpenSSL::Netscape::SPKI.new(@b64.unpack("m").first)
assert_equal(@b64, spki.to_pem)
assert_equal(@b64.unpack("m").first, spki.to_der)
assert_equal("MozillaIsMyFriend", spki.challenge)
assert_equal(OpenSSL::PKey::RSA, spki.public_key.class)
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/openssl/test_digest.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/openssl/test_digest.rb | begin
require "openssl"
rescue LoadError
end
require "digest/md5"
require "test/unit"
if defined?(OpenSSL)
class OpenSSL::TestDigest < Test::Unit::TestCase
def setup
@d1 = OpenSSL::Digest::Digest::new("MD5")
@d2 = OpenSSL::Digest::MD5.new
@md = Digest::MD5.new
@data = "DATA"
end
def teardown
@d1 = @d2 = @md = nil
end
def test_digest
assert_equal(@md.digest, @d1.digest)
assert_equal(@md.hexdigest, @d1.hexdigest)
@d1 << @data
@d2 << @data
@md << @data
assert_equal(@md.digest, @d1.digest)
assert_equal(@md.hexdigest, @d1.hexdigest)
assert_equal(@d1.digest, @d2.digest)
assert_equal(@d1.hexdigest, @d2.hexdigest)
assert_equal(@md.digest, OpenSSL::Digest::MD5.digest(@data))
assert_equal(@md.hexdigest, OpenSSL::Digest::MD5.hexdigest(@data))
end
def test_eql
assert(@d1 == @d2, "==")
d = @d1.clone
assert(d == @d1, "clone")
end
def test_info
assert_equal("MD5", @d1.name, "name")
assert_equal("MD5", @d2.name, "name")
assert_equal(16, @d1.size, "size")
end
def test_dup
@d1.update(@data)
assert_equal(@d1.name, @d1.dup.name, "dup")
assert_equal(@d1.name, @d1.clone.name, "clone")
assert_equal(@d1.digest, @d1.clone.digest, "clone .digest")
end
def test_reset
@d1.update(@data)
dig1 = @d1.digest
@d1.reset
@d1.update(@data)
dig2 = @d1.digest
assert_equal(dig1, dig2, "reset")
end
if OpenSSL::OPENSSL_VERSION_NUMBER > 0x00908000
def encode16(str)
str.unpack("H*").first
end
def test_098_features
sha224_a = "abd37534c7d9a2efb9465de931cd7055ffdb8879563ae98078d6d6d5"
sha256_a = "ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb"
sha384_a = "54a59b9f22b0b80880d8427e548b7c23abd873486e1f035dce9cd697e85175033caa88e6d57bc35efae0b5afd3145f31"
sha512_a = "1f40fc92da241694750979ee6cf582f2d5d7d28e18335de05abc54d0560e0f5302860c652bf08d560252aa5e74210546f369fbbbce8c12cfc7957b2652fe9a75"
assert_equal(sha224_a, OpenSSL::Digest::SHA224.hexdigest("a"))
assert_equal(sha256_a, OpenSSL::Digest::SHA256.hexdigest("a"))
assert_equal(sha384_a, OpenSSL::Digest::SHA384.hexdigest("a"))
assert_equal(sha512_a, OpenSSL::Digest::SHA512.hexdigest("a"))
assert_equal(sha224_a, encode16(OpenSSL::Digest::SHA224.digest("a")))
assert_equal(sha256_a, encode16(OpenSSL::Digest::SHA256.digest("a")))
assert_equal(sha384_a, encode16(OpenSSL::Digest::SHA384.digest("a")))
assert_equal(sha512_a, encode16(OpenSSL::Digest::SHA512.digest("a")))
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/openssl/test_pair.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/openssl/test_pair.rb | begin
require "openssl"
rescue LoadError
end
require 'test/unit'
if defined?(OpenSSL)
require 'socket'
dir = File.expand_path(__FILE__)
2.times {dir = File.dirname(dir)}
$:.replace([File.join(dir, "ruby")] | $:)
require 'ut_eof'
module SSLPair
def server
host = "127.0.0.1"
port = 0
ctx = OpenSSL::SSL::SSLContext.new()
ctx.ciphers = "ADH"
tcps = TCPServer.new(host, port)
ssls = OpenSSL::SSL::SSLServer.new(tcps, ctx)
return ssls
end
def client(port)
host = "127.0.0.1"
ctx = OpenSSL::SSL::SSLContext.new()
ctx.ciphers = "ADH"
s = TCPSocket.new(host, port)
ssl = OpenSSL::SSL::SSLSocket.new(s, ctx)
ssl.connect
ssl.sync_close = true
ssl
end
def ssl_pair
ssls = server
th = Thread.new {
ns = ssls.accept
ssls.close
ns
}
port = ssls.to_io.addr[1]
c = client(port)
s = th.value
if block_given?
begin
yield c, s
ensure
c.close unless c.closed?
s.close unless s.closed?
end
else
return c, s
end
end
end
class OpenSSL::TestEOF1 < Test::Unit::TestCase
include TestEOF
include SSLPair
def open_file(content)
s1, s2 = ssl_pair
Thread.new { s2 << content; s2.close }
yield s1
end
end
class OpenSSL::TestEOF2 < Test::Unit::TestCase
include TestEOF
include SSLPair
def open_file(content)
s1, s2 = ssl_pair
Thread.new { s1 << content; s1.close }
yield s2
end
end
class OpenSSL::TestPair < Test::Unit::TestCase
include SSLPair
def test_getc
ssl_pair {|s1, s2|
s1 << "a"
assert_equal(?a, s2.getc)
}
end
def test_readpartial
ssl_pair {|s1, s2|
s2.write "a\nbcd"
assert_equal("a\n", s1.gets)
assert_equal("bcd", s1.readpartial(10))
s2.write "efg"
assert_equal("efg", s1.readpartial(10))
s2.close
assert_raise(EOFError) { s1.readpartial(10) }
assert_raise(EOFError) { s1.readpartial(10) }
assert_equal("", s1.readpartial(0))
}
end
def test_readall
ssl_pair {|s1, s2|
s2.close
assert_equal("", s1.read)
}
end
def test_readline
ssl_pair {|s1, s2|
s2.close
assert_raise(EOFError) { s1.readline }
}
end
def test_puts_meta
ssl_pair {|s1, s2|
begin
old = $/
$/ = '*'
s1.puts 'a'
ensure
$/ = old
end
s1.close
assert_equal("a\n", s2.read)
}
end
def test_puts_empty
ssl_pair {|s1, s2|
s1.puts
s1.close
assert_equal("\n", s2.read)
}
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/openssl/test_x509name.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/openssl/test_x509name.rb | begin
require "openssl"
rescue LoadError
end
require "test/unit"
if defined?(OpenSSL)
require 'digest/md5'
class OpenSSL::TestX509Name < Test::Unit::TestCase
OpenSSL::ASN1::ObjectId.register(
"1.2.840.113549.1.9.1", "emailAddress", "emailAddress")
OpenSSL::ASN1::ObjectId.register(
"2.5.4.5", "serialNumber", "serialNumber")
def setup
@obj_type_tmpl = Hash.new(OpenSSL::ASN1::PRINTABLESTRING)
@obj_type_tmpl.update(OpenSSL::X509::Name::OBJECT_TYPE_TEMPLATE)
end
def teardown
end
def test_s_new
dn = [ ["C", "JP"], ["O", "example"], ["CN", "www.example.jp"] ]
name = OpenSSL::X509::Name.new(dn)
ary = name.to_a
assert_equal("/C=JP/O=example/CN=www.example.jp", name.to_s)
assert_equal("C", ary[0][0])
assert_equal("O", ary[1][0])
assert_equal("CN", ary[2][0])
assert_equal("JP", ary[0][1])
assert_equal("example", ary[1][1])
assert_equal("www.example.jp", ary[2][1])
assert_equal(OpenSSL::ASN1::PRINTABLESTRING, ary[0][2])
assert_equal(OpenSSL::ASN1::UTF8STRING, ary[1][2])
assert_equal(OpenSSL::ASN1::UTF8STRING, ary[2][2])
dn = [
["countryName", "JP"],
["organizationName", "example"],
["commonName", "www.example.jp"]
]
name = OpenSSL::X509::Name.new(dn)
ary = name.to_a
assert_equal("/C=JP/O=example/CN=www.example.jp", name.to_s)
assert_equal("C", ary[0][0])
assert_equal("O", ary[1][0])
assert_equal("CN", ary[2][0])
assert_equal("JP", ary[0][1])
assert_equal("example", ary[1][1])
assert_equal("www.example.jp", ary[2][1])
assert_equal(OpenSSL::ASN1::PRINTABLESTRING, ary[0][2])
assert_equal(OpenSSL::ASN1::UTF8STRING, ary[1][2])
assert_equal(OpenSSL::ASN1::UTF8STRING, ary[2][2])
name = OpenSSL::X509::Name.new(dn, @obj_type_tmpl)
ary = name.to_a
assert_equal("/C=JP/O=example/CN=www.example.jp", name.to_s)
assert_equal(OpenSSL::ASN1::PRINTABLESTRING, ary[0][2])
assert_equal(OpenSSL::ASN1::PRINTABLESTRING, ary[1][2])
assert_equal(OpenSSL::ASN1::PRINTABLESTRING, ary[2][2])
dn = [
["countryName", "JP", OpenSSL::ASN1::PRINTABLESTRING],
["organizationName", "example", OpenSSL::ASN1::PRINTABLESTRING],
["commonName", "www.example.jp", OpenSSL::ASN1::PRINTABLESTRING]
]
name = OpenSSL::X509::Name.new(dn)
ary = name.to_a
assert_equal("/C=JP/O=example/CN=www.example.jp", name.to_s)
assert_equal(OpenSSL::ASN1::PRINTABLESTRING, ary[0][2])
assert_equal(OpenSSL::ASN1::PRINTABLESTRING, ary[1][2])
assert_equal(OpenSSL::ASN1::PRINTABLESTRING, ary[2][2])
dn = [
["DC", "org"],
["DC", "ruby-lang"],
["CN", "GOTOU Yuuzou"],
["emailAddress", "gotoyuzo@ruby-lang.org"],
["serialNumber", "123"],
]
name = OpenSSL::X509::Name.new(dn)
ary = name.to_a
assert_equal("/DC=org/DC=ruby-lang/CN=GOTOU Yuuzou/emailAddress=gotoyuzo@ruby-lang.org/serialNumber=123", name.to_s)
assert_equal("DC", ary[0][0])
assert_equal("DC", ary[1][0])
assert_equal("CN", ary[2][0])
assert_equal("emailAddress", ary[3][0])
assert_equal("serialNumber", ary[4][0])
assert_equal("org", ary[0][1])
assert_equal("ruby-lang", ary[1][1])
assert_equal("GOTOU Yuuzou", ary[2][1])
assert_equal("gotoyuzo@ruby-lang.org", ary[3][1])
assert_equal("123", ary[4][1])
assert_equal(OpenSSL::ASN1::IA5STRING, ary[0][2])
assert_equal(OpenSSL::ASN1::IA5STRING, ary[1][2])
assert_equal(OpenSSL::ASN1::UTF8STRING, ary[2][2])
assert_equal(OpenSSL::ASN1::IA5STRING, ary[3][2])
assert_equal(OpenSSL::ASN1::PRINTABLESTRING, ary[4][2])
name_from_der = OpenSSL::X509::Name.new(name.to_der)
assert_equal(name_from_der.to_s, name.to_s)
assert_equal(name_from_der.to_a, name.to_a)
assert_equal(name_from_der.to_der, name.to_der)
end
def test_s_parse
dn = "/DC=org/DC=ruby-lang/CN=www.ruby-lang.org"
name = OpenSSL::X509::Name.parse(dn)
assert_equal(dn, name.to_s)
ary = name.to_a
assert_equal("DC", ary[0][0])
assert_equal("DC", ary[1][0])
assert_equal("CN", ary[2][0])
assert_equal("org", ary[0][1])
assert_equal("ruby-lang", ary[1][1])
assert_equal("www.ruby-lang.org", ary[2][1])
assert_equal(OpenSSL::ASN1::IA5STRING, ary[0][2])
assert_equal(OpenSSL::ASN1::IA5STRING, ary[1][2])
assert_equal(OpenSSL::ASN1::UTF8STRING, ary[2][2])
dn2 = "DC=org, DC=ruby-lang, CN=www.ruby-lang.org"
name = OpenSSL::X509::Name.parse(dn)
ary = name.to_a
assert_equal(dn, name.to_s)
assert_equal("org", ary[0][1])
assert_equal("ruby-lang", ary[1][1])
assert_equal("www.ruby-lang.org", ary[2][1])
name = OpenSSL::X509::Name.parse(dn, @obj_type_tmpl)
ary = name.to_a
assert_equal(OpenSSL::ASN1::IA5STRING, ary[0][2])
assert_equal(OpenSSL::ASN1::IA5STRING, ary[1][2])
assert_equal(OpenSSL::ASN1::PRINTABLESTRING, ary[2][2])
end
def test_s_parse_rfc2253
scanner = OpenSSL::X509::Name::RFC2253DN.method(:scan)
assert_equal([["C", "JP"]], scanner.call("C=JP"))
assert_equal([
["DC", "org"],
["DC", "ruby-lang"],
["CN", "GOTOU Yuuzou"],
["emailAddress", "gotoyuzo@ruby-lang.org"],
],
scanner.call(
"emailAddress=gotoyuzo@ruby-lang.org,CN=GOTOU Yuuzou,"+
"DC=ruby-lang,DC=org")
)
u8 = OpenSSL::ASN1::UTF8STRING
assert_equal([
["DC", "org"],
["DC", "ruby-lang"],
["O", ",=+<>#;"],
["O", ",=+<>#;"],
["OU", ""],
["OU", ""],
["L", "aaa=\"bbb, ccc\""],
["L", "aaa=\"bbb, ccc\""],
["CN", "\345\276\214\350\227\244\350\243\225\350\224\265"],
["CN", "\345\276\214\350\227\244\350\243\225\350\224\265"],
["CN", "\345\276\214\350\227\244\350\243\225\350\224\265"],
["CN", "\345\276\214\350\227\244\350\243\225\350\224\265", u8],
["2.5.4.3", "GOTOU, Yuuzou"],
["2.5.4.3", "GOTOU, Yuuzou"],
["2.5.4.3", "GOTOU, Yuuzou"],
["2.5.4.3", "GOTOU, Yuuzou"],
["CN", "GOTOU \"gotoyuzo\" Yuuzou"],
["CN", "GOTOU \"gotoyuzo\" Yuuzou"],
["1.2.840.113549.1.9.1", "gotoyuzo@ruby-lang.org"],
["emailAddress", "gotoyuzo@ruby-lang.org"],
],
scanner.call(
"emailAddress=gotoyuzo@ruby-lang.org," +
"1.2.840.113549.1.9.1=gotoyuzo@ruby-lang.org," +
'CN=GOTOU \"gotoyuzo\" Yuuzou,' +
'CN="GOTOU \"gotoyuzo\" Yuuzou",' +
'2.5.4.3=GOTOU\,\20Yuuzou,' +
'2.5.4.3=GOTOU\, Yuuzou,' +
'2.5.4.3="GOTOU, Yuuzou",' +
'2.5.4.3="GOTOU\, Yuuzou",' +
"CN=#0C0CE5BE8CE897A4E8A395E894B5," +
'CN=\E5\BE\8C\E8\97\A4\E8\A3\95\E8\94\B5,' +
"CN=\"\xE5\xBE\x8C\xE8\x97\xA4\xE8\xA3\x95\xE8\x94\xB5\"," +
"CN=\xE5\xBE\x8C\xE8\x97\xA4\xE8\xA3\x95\xE8\x94\xB5," +
'L=aaa\=\"bbb\, ccc\",' +
'L="aaa=\"bbb, ccc\"",' +
'OU=,' +
'OU="",' +
'O=\,\=\+\<\>\#\;,' +
'O=",=+<>#;",' +
"DC=ruby-lang," +
"DC=org")
)
[
"DC=org+DC=jp",
"DC=org,DC=ruby-lang+DC=rubyist,DC=www"
].each{|dn|
ex = scanner.call(dn) rescue $!
dn_r = Regexp.escape(dn)
assert_match(/^multi-valued RDN is not supported: #{dn_r}/, ex.message)
}
[
["DC=org,DC=exapmle,CN", "CN"],
["DC=org,DC=example,", ""],
["DC=org,DC=exapmle,CN=www.example.org;", "CN=www.example.org;"],
["DC=org,DC=exapmle,CN=#www.example.org", "CN=#www.example.org"],
["DC=org,DC=exapmle,CN=#777777.example.org", "CN=#777777.example.org"],
["DC=org,DC=exapmle,CN=\"www.example\".org", "CN=\"www.example\".org"],
["DC=org,DC=exapmle,CN=www.\"example.org\"", "CN=www.\"example.org\""],
["DC=org,DC=exapmle,CN=www.\"example\".org", "CN=www.\"example\".org"],
].each{|dn, msg|
ex = scanner.call(dn) rescue $!
assert_match(/^malformed RDN: .*=>#{Regexp.escape(msg)}/, ex.message)
}
dn = "CN=www.ruby-lang.org,DC=ruby-lang,DC=org"
name = OpenSSL::X509::Name.parse_rfc2253(dn)
assert_equal(dn, name.to_s(OpenSSL::X509::Name::RFC2253))
ary = name.to_a
assert_equal("DC", ary[0][0])
assert_equal("DC", ary[1][0])
assert_equal("CN", ary[2][0])
assert_equal("org", ary[0][1])
assert_equal("ruby-lang", ary[1][1])
assert_equal("www.ruby-lang.org", ary[2][1])
assert_equal(OpenSSL::ASN1::IA5STRING, ary[0][2])
assert_equal(OpenSSL::ASN1::IA5STRING, ary[1][2])
assert_equal(OpenSSL::ASN1::UTF8STRING, ary[2][2])
end
def test_add_entry
dn = [
["DC", "org"],
["DC", "ruby-lang"],
["CN", "GOTOU Yuuzou"],
["emailAddress", "gotoyuzo@ruby-lang.org"],
["serialNumber", "123"],
]
name = OpenSSL::X509::Name.new
dn.each{|attr| name.add_entry(*attr) }
ary = name.to_a
assert_equal("/DC=org/DC=ruby-lang/CN=GOTOU Yuuzou/emailAddress=gotoyuzo@ruby-lang.org/serialNumber=123", name.to_s)
assert_equal("DC", ary[0][0])
assert_equal("DC", ary[1][0])
assert_equal("CN", ary[2][0])
assert_equal("emailAddress", ary[3][0])
assert_equal("serialNumber", ary[4][0])
assert_equal("org", ary[0][1])
assert_equal("ruby-lang", ary[1][1])
assert_equal("GOTOU Yuuzou", ary[2][1])
assert_equal("gotoyuzo@ruby-lang.org", ary[3][1])
assert_equal("123", ary[4][1])
assert_equal(OpenSSL::ASN1::IA5STRING, ary[0][2])
assert_equal(OpenSSL::ASN1::IA5STRING, ary[1][2])
assert_equal(OpenSSL::ASN1::UTF8STRING, ary[2][2])
assert_equal(OpenSSL::ASN1::IA5STRING, ary[3][2])
assert_equal(OpenSSL::ASN1::PRINTABLESTRING, ary[4][2])
end
def test_hash
dn = "/DC=org/DC=ruby-lang/CN=www.ruby-lang.org"
name = OpenSSL::X509::Name.parse(dn)
d = Digest::MD5.digest(name.to_der)
expected = (d[0] & 0xff) | (d[1] & 0xff) << 8 | (d[2] & 0xff) << 16 | (d[3] & 0xff) << 24
assert_equal(expected, name.hash)
#
dn = "/DC=org/DC=ruby-lang/CN=baz.ruby-lang.org"
name = OpenSSL::X509::Name.parse(dn)
d = Digest::MD5.digest(name.to_der)
expected = (d[0] & 0xff) | (d[1] & 0xff) << 8 | (d[2] & 0xff) << 16 | (d[3] & 0xff) << 24
assert_equal(expected, name.hash)
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/fixture/purpose/scripts/init_ca.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/fixture/purpose/scripts/init_ca.rb | #!/usr/bin/env ruby
require 'openssl'
require 'ca_config'
include OpenSSL
$stdout.sync = true
cn = ARGV.shift || 'CA'
unless FileTest.exist?('private')
Dir.mkdir('private', 0700)
end
unless FileTest.exist?('newcerts')
Dir.mkdir('newcerts')
end
unless FileTest.exist?('crl')
Dir.mkdir('crl')
end
unless FileTest.exist?('serial')
File.open('serial', 'w') do |f|
f << '2'
end
end
print "Generating CA keypair: "
keypair = PKey::RSA.new(CAConfig::CA_RSA_KEY_LENGTH) { putc "." }
putc "\n"
now = Time.now
cert = X509::Certificate.new
name = CAConfig::NAME.dup << ['CN', cn]
cert.subject = cert.issuer = X509::Name.new(name)
cert.not_before = now
cert.not_after = now + CAConfig::CA_CERT_DAYS * 24 * 60 * 60
cert.public_key = keypair.public_key
cert.serial = 0x1
cert.version = 2 # X509v3
key_usage = ["cRLSign", "keyCertSign"]
ef = X509::ExtensionFactory.new
ef.subject_certificate = cert
ef.issuer_certificate = cert # we needed subjectKeyInfo inside, now we have it
ext1 = ef.create_extension("basicConstraints","CA:TRUE", true)
ext2 = ef.create_extension("nsComment","Ruby/OpenSSL Generated Certificate")
ext3 = ef.create_extension("subjectKeyIdentifier", "hash")
ext4 = ef.create_extension("keyUsage", key_usage.join(","), true)
cert.extensions = [ext1, ext2, ext3, ext4]
ext0 = ef.create_extension("authorityKeyIdentifier", "keyid:always,issuer:always")
cert.add_extension(ext0)
cert.sign(keypair, OpenSSL::Digest::SHA1.new)
keypair_file = CAConfig::KEYPAIR_FILE
puts "Writing keypair."
File.open(keypair_file, "w", 0400) do |f|
f << keypair.export(Cipher::DES.new(:EDE3, :CBC), &CAConfig::PASSWD_CB)
end
cert_file = CAConfig::CERT_FILE
puts "Writing #{cert_file}."
File.open(cert_file, "w", 0644) do |f|
f << cert.to_pem
end
puts "DONE. (Generated certificate for '#{cert.subject}')"
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/fixture/purpose/scripts/gen_csr.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/fixture/purpose/scripts/gen_csr.rb | #!/usr/bin/env ruby
require 'getopts'
require 'openssl'
include OpenSSL
def usage
myname = File::basename($0)
$stderr.puts <<EOS
Usage: #{myname} [--key keypair_file] name
name ... ex. /C=JP/O=RRR/OU=CA/CN=NaHi/emailAddress=nahi@example.org
EOS
exit
end
getopts nil, "key:", "csrout:", "keyout:"
keypair_file = $OPT_key
csrout = $OPT_csrout || "csr.pem"
keyout = $OPT_keyout || "keypair.pem"
$stdout.sync = true
name_str = ARGV.shift or usage()
p name_str
name = X509::Name.parse(name_str)
keypair = nil
if keypair_file
keypair = PKey::RSA.new(File.open(keypair_file).read)
else
keypair = PKey::RSA.new(1024) { putc "." }
puts
puts "Writing #{keyout}..."
File.open(keyout, "w", 0400) do |f|
f << keypair.to_pem
end
end
puts "Generating CSR for #{name_str}"
req = X509::Request.new
req.version = 0
req.subject = name
req.public_key = keypair.public_key
req.sign(keypair, OpenSSL::Digest::MD5.new)
puts "Writing #{csrout}..."
File.open(csrout, "w") do |f|
f << req.to_pem
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/fixture/purpose/scripts/gen_cert.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/fixture/purpose/scripts/gen_cert.rb | #!/usr/bin/env ruby
require 'openssl'
require 'ca_config'
require 'fileutils'
require 'getopts'
include OpenSSL
def usage
myname = File::basename($0)
$stderr.puts "Usage: #{myname} [--type (client|server|ca|ocsp)] [--out certfile] csr_file"
exit
end
getopts nil, 'type:client', 'out:', 'force'
cert_type = $OPT_type
out_file = $OPT_out || 'cert.pem'
csr_file = ARGV.shift or usage
ARGV.empty? or usage
csr = X509::Request.new(File.open(csr_file).read)
unless csr.verify(csr.public_key)
raise "CSR sign verification failed."
end
p csr.public_key
if csr.public_key.n.num_bits < CAConfig::CERT_KEY_LENGTH_MIN
raise "Key length too short"
end
if csr.public_key.n.num_bits > CAConfig::CERT_KEY_LENGTH_MAX
raise "Key length too long"
end
if csr.subject.to_a[0, CAConfig::NAME.size] != CAConfig::NAME
unless $OPT_force
p csr.subject.to_a
p CAConfig::NAME
raise "DN does not match"
end
end
# Only checks signature here. You must verify CSR according to your CP/CPS.
$stdout.sync = true
# CA setup
ca_file = CAConfig::CERT_FILE
puts "Reading CA cert (from #{ca_file})"
ca = X509::Certificate.new(File.read(ca_file))
ca_keypair_file = CAConfig::KEYPAIR_FILE
puts "Reading CA keypair (from #{ca_keypair_file})"
ca_keypair = PKey::RSA.new(File.read(ca_keypair_file), &CAConfig::PASSWD_CB)
serial = File.open(CAConfig::SERIAL_FILE, "r").read.chomp.hex
File.open(CAConfig::SERIAL_FILE, "w") do |f|
f << sprintf("%04X", serial + 1)
end
# Generate new cert
cert = X509::Certificate.new
from = Time.now # + 30 * 60 # Wait 30 minutes.
cert.subject = csr.subject
cert.issuer = ca.subject
cert.not_before = from
cert.not_after = from + CAConfig::CERT_DAYS * 24 * 60 * 60
cert.public_key = csr.public_key
cert.serial = serial
cert.version = 2 # X509v3
basic_constraint = nil
key_usage = []
ext_key_usage = []
case cert_type
when "ca"
basic_constraint = "CA:TRUE"
key_usage << "cRLSign" << "keyCertSign"
when "terminalsubca"
basic_constraint = "CA:TRUE,pathlen:0"
key_usage << "cRLSign" << "keyCertSign"
when "server"
basic_constraint = "CA:FALSE"
key_usage << "digitalSignature" << "keyEncipherment"
ext_key_usage << "serverAuth"
when "ocsp"
basic_constraint = "CA:FALSE"
key_usage << "nonRepudiation" << "digitalSignature"
ext_key_usage << "serverAuth" << "OCSPSigning"
when "client"
basic_constraint = "CA:FALSE"
key_usage << "nonRepudiation" << "digitalSignature" << "keyEncipherment"
ext_key_usage << "clientAuth" << "emailProtection"
else
raise "unknonw cert type \"#{cert_type}\" is specified."
end
ef = X509::ExtensionFactory.new
ef.subject_certificate = cert
ef.issuer_certificate = ca
ex = []
ex << ef.create_extension("basicConstraints", basic_constraint, true)
ex << ef.create_extension("nsComment","Ruby/OpenSSL Generated Certificate")
ex << ef.create_extension("subjectKeyIdentifier", "hash")
#ex << ef.create_extension("nsCertType", "client,email")
ex << ef.create_extension("keyUsage", key_usage.join(",")) unless key_usage.empty?
#ex << ef.create_extension("authorityKeyIdentifier", "keyid:always,issuer:always")
#ex << ef.create_extension("authorityKeyIdentifier", "keyid:always")
ex << ef.create_extension("extendedKeyUsage", ext_key_usage.join(",")) unless ext_key_usage.empty?
ex << ef.create_extension("crlDistributionPoints", CAConfig::CDP_LOCATION) if CAConfig::CDP_LOCATION
ex << ef.create_extension("authorityInfoAccess", "OCSP;" << CAConfig::OCSP_LOCATION) if CAConfig::OCSP_LOCATION
cert.extensions = ex
cert.sign(ca_keypair, OpenSSL::Digest::SHA1.new)
# For backup
cert_file = CAConfig::NEW_CERTS_DIR + "/#{cert.serial}_cert.pem"
File.open(cert_file, "w", 0644) do |f|
f << cert.to_pem
end
puts "Writing cert.pem..."
FileUtils.copy(cert_file, out_file)
puts "DONE. (Generated certificate for '#{cert.subject}')"
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/fixture/purpose/ca/ca_config.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/fixture/purpose/ca/ca_config.rb | class CAConfig
BASE_DIR = File.dirname(__FILE__)
KEYPAIR_FILE = "#{BASE_DIR}/private/cakeypair.pem"
CERT_FILE = "#{BASE_DIR}/cacert.pem"
SERIAL_FILE = "#{BASE_DIR}/serial"
NEW_CERTS_DIR = "#{BASE_DIR}/newcerts"
NEW_KEYPAIR_DIR = "#{BASE_DIR}/private/keypair_backup"
CRL_DIR = "#{BASE_DIR}/crl"
NAME = [['C', 'JP'], ['O', 'www.ruby-lang.org'], ['OU', 'development']]
CA_CERT_DAYS = 20 * 365
CA_RSA_KEY_LENGTH = 2048
CERT_DAYS = 19 * 365
CERT_KEY_LENGTH_MIN = 1024
CERT_KEY_LENGTH_MAX = 2048
CDP_LOCATION = nil
OCSP_LOCATION = nil
CRL_FILE = "#{CRL_DIR}/jruby.crl"
CRL_PEM_FILE = "#{CRL_DIR}/jruby.pem"
CRL_DAYS = 14
PASSWD_CB = Proc.new { |flag|
print "Enter password: "
pass = $stdin.gets.chop!
# when the flag is true, this passphrase
# will be used to perform encryption; otherwise it will
# be used to perform decryption.
if flag
print "Verify password: "
pass2 = $stdin.gets.chop!
raise "verify failed." if pass != pass2
end
pass
}
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/java/test_java_smime.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/java/test_java_smime.rb | module PKCS7Test
class TestJavaSMIME < Test::Unit::TestCase
def test_read_pkcs7_should_raise_error_when_parsing_headers_fails
bio = BIO.new
mime = Mime.new
mime.stubs(:parseHeaders).returns(nil)
begin
SMIME.new(mime).readPKCS7(bio, nil)
assert false
rescue PKCS7Exception => e
assert_equal PKCS7::F_SMIME_READ_PKCS7, e.cause.get_method
assert_equal PKCS7::R_MIME_PARSE_ERROR, e.cause.get_reason
end
end
def test_read_pkcs7_should_raise_error_when_content_type_is_not_there
bio = BIO.new
mime = Mime.new
headers = ArrayList.new
mime.expects(:parseHeaders).with(bio).returns(headers)
mime.expects(:findHeader).with(headers, "content-type").returns(nil)
begin
SMIME.new(mime).readPKCS7(bio, nil)
assert false
rescue PKCS7Exception => e
assert_equal PKCS7::F_SMIME_READ_PKCS7, e.cause.get_method
assert_equal PKCS7::R_NO_CONTENT_TYPE, e.cause.get_reason
end
mime = Mime.new
mime.expects(:parseHeaders).with(bio).returns(headers)
mime.expects(:findHeader).with(headers, "content-type").returns(MimeHeader.new("content-type", nil))
begin
SMIME.new(mime).readPKCS7(bio, nil)
assert false
rescue PKCS7Exception => e
assert_equal PKCS7::F_SMIME_READ_PKCS7, e.cause.get_method
assert_equal PKCS7::R_NO_CONTENT_TYPE, e.cause.get_reason
end
end
def test_read_pkcs7_should_set_the_second_arguments_contents_to_null_if_its_there
mime = Mime.new
mime.stubs(:parseHeaders).raises("getOutOfJailForFree")
bio2 = BIO.new
arr = [bio2].to_java BIO
begin
SMIME.new(mime).readPKCS7(nil, arr)
rescue
end
assert_nil arr[0]
arr = [bio2, bio2].to_java BIO
begin
SMIME.new(mime).readPKCS7(nil, arr)
rescue
end
assert_nil arr[0]
assert_equal bio2, arr[1]
end
def test_read_pkcs7_should_call_methods_on_mime
bio = BIO.new
mime = Mime.new
headers = ArrayList.new
mime.expects(:parseHeaders).with(bio).returns(headers)
mime.expects(:findHeader).with(headers, "content-type").returns(MimeHeader.new("content-type", "application/pkcs7-mime"))
begin
SMIME.new(mime).readPKCS7(bio, nil)
rescue java.lang.UnsupportedOperationException
# This error is expected, since the bio used is not a real one
end
end
def test_read_pkcs7_throws_correct_exception_if_wrong_content_type
bio = BIO.new
mime = Mime.new
headers = ArrayList.new
mime.expects(:parseHeaders).with(bio).returns(headers)
mime.expects(:findHeader).with(headers, "content-type").returns(MimeHeader.new("content-type", "foo"))
begin
SMIME.new(mime).readPKCS7(bio, nil)
assert false
rescue PKCS7Exception => e
assert_equal PKCS7::F_SMIME_READ_PKCS7, e.cause.get_method
assert_equal PKCS7::R_INVALID_MIME_TYPE, e.cause.get_reason
assert_equal "type: foo", e.cause.error_data
end
end
def test_read_pkcs7_with_multipart_should_fail_if_no_boundary_found
bio = BIO.new
mime = Mime.new
headers = ArrayList.new
hdr = MimeHeader.new("content-type", "multipart/signed")
mime.expects(:parseHeaders).with(bio).returns(headers)
mime.expects(:findHeader).with(headers, "content-type").returns(hdr)
mime.expects(:findParam).with(hdr, "boundary").returns(nil)
begin
SMIME.new(mime).readPKCS7(bio, nil)
assert false
rescue PKCS7Exception => e
assert_equal PKCS7::F_SMIME_READ_PKCS7, e.cause.get_method
assert_equal PKCS7::R_NO_MULTIPART_BOUNDARY, e.cause.get_reason
end
end
def test_read_pkcs7_with_multipart_should_fail_if_null_boundary_value
bio = BIO.new
mime = Mime.new
headers = ArrayList.new
hdr = MimeHeader.new("content-type", "multipart/signed")
mime.expects(:parseHeaders).with(bio).returns(headers)
mime.expects(:findHeader).with(headers, "content-type").returns(hdr)
mime.expects(:findParam).with(hdr, "boundary").returns(MimeParam.new("boundary", nil))
begin
SMIME.new(mime).readPKCS7(bio, nil)
assert false
rescue PKCS7Exception => e
assert_equal PKCS7::F_SMIME_READ_PKCS7, e.cause.get_method
assert_equal PKCS7::R_NO_MULTIPART_BOUNDARY, e.cause.get_reason
end
end
# TODO: redo this test to be an integration test
def _test_read_pkcs7_happy_path_without_multipart
bio = BIO.new
mime = Mime.new
headers = ArrayList.new
mime.expects(:parseHeaders).with(bio).returns(headers)
mime.expects(:findHeader).with(headers, "content-type").returns(MimeHeader.new("content-type", "application/pkcs7-mime"))
SMIME.new(mime).readPKCS7(bio, nil)
end
def test_read_pkcs7_happy_path_multipart
bio = BIO::from_string(MultipartSignedString)
mime = Mime::DEFAULT
p7 = SMIME.new(mime).readPKCS7(bio, nil)
end
def test_read_pkcs7_happy_path_without_multipart_enveloped
bio = BIO::from_string(MimeEnvelopedString)
mime = Mime::DEFAULT
p7 = SMIME.new(mime).readPKCS7(bio, nil)
end
def test_read_pkcs7_happy_path_without_multipart_signed
bio = BIO::from_string(MimeSignedString)
mime = Mime::DEFAULT
p7 = SMIME.new(mime).readPKCS7(bio, nil)
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/java/test_java_attribute.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/java/test_java_attribute.rb | module PKCS7Test
class TestJavaAttribute < Test::Unit::TestCase
def test_attributes
val = ASN1::OctetString.new("foo".to_java_bytes)
val2 = ASN1::OctetString.new("bar".to_java_bytes)
attr = Attribute.create(123, 444, val)
assert_raise NoMethodError do
attr.type = 12
end
assert_raise NoMethodError do
attr.value = val2
end
assert_equal 123, attr.type
assert_equal val, attr.set.get(0)
attr2 = Attribute.create(123, 444, val)
assert_equal attr, attr2
assert_not_equal Attribute.create(124, 444, val), attr
assert_not_equal Attribute.create(123, 444, val2), attr
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/java/test_java_mime.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/java/test_java_mime.rb | module PKCS7Test
class TestJavaMime < Test::Unit::TestCase
def test_find_header_returns_null_on_nonexisting_header
headers = []
assert_nil Mime::DEFAULT.find_header(headers, "foo")
headers = [MimeHeader.new("blarg", "bluff")]
assert_nil Mime::DEFAULT.find_header(headers, "foo")
end
def test_find_header_returns_the_header_with_the_same_name
hdr = MimeHeader.new("one", "two")
assert_equal hdr, Mime::DEFAULT.find_header([hdr], "one")
end
def test_find_param_returns_null_on_nonexisting_param
assert_nil Mime::DEFAULT.find_param(MimeHeader.new("one", "two", []), "foo")
assert_nil Mime::DEFAULT.find_param(MimeHeader.new("one", "two", [MimeParam.new("hi", "ho")]), "foo")
end
def test_find_param_returns_the_param_with_the_same_name
par = MimeParam.new("hox", "box")
hdr = MimeHeader.new("one", "two", [par])
assert_equal par, Mime::DEFAULT.find_param(hdr, "hox")
end
def test_simple_parse_headers
bio = BIO::from_string("Foo: bar")
result = Mime::DEFAULT.parse_headers(bio)
assert_equal 1, result.size
assert_equal MimeHeader.new("Foo", "bar"), result[0]
assert_equal "foo", result[0].name
end
def test_simple_parse_headers2
bio = BIO::from_string("Foo:bar")
result = Mime::DEFAULT.parse_headers(bio)
assert_equal 1, result.size
assert_equal MimeHeader.new("Foo", "bar"), result[0]
assert_equal "foo", result[0].name
end
def test_simple_parse_headers3
bio = BIO::from_string("Foo: bar")
result = Mime::DEFAULT.parse_headers(bio)
assert_equal 1, result.size
assert_equal MimeHeader.new("Foo", "bar"), result[0]
assert_equal "foo", result[0].name
end
def test_simple_parse_headers4
bio = BIO::from_string("Foo: bar\n")
result = Mime::DEFAULT.parse_headers(bio)
assert_equal 1, result.size
assert_equal MimeHeader.new("Foo", "bar"), result[0]
assert_equal "foo", result[0].name
end
def test_simple_parse_headers5
bio = BIO::from_string(" Foo : bar \n")
result = Mime::DEFAULT.parse_headers(bio)
assert_equal 1, result.size
assert_equal MimeHeader.new("Foo", "bar"), result[0]
assert_equal "foo", result[0].name
end
def test_simple_parse_headers6
bio = BIO::from_string("Foo: bar;\n")
result = Mime::DEFAULT.parse_headers(bio)
assert_equal 1, result.size
assert_equal MimeHeader.new("Foo", "bar"), result[0]
assert_equal "foo", result[0].name
end
def test_simple_parse_headers7
bio = BIO::from_string("Foo: bar;\nFlurg: blarg")
result = Mime::DEFAULT.parse_headers(bio)
assert_equal 2, result.size
assert_equal MimeHeader.new("Foo", "bar"), result[0]
assert_equal MimeHeader.new("Flurg", "blarg"), result[1]
assert_equal "foo", result[0].name
assert_equal "flurg", result[1].name
end
def test_simple_parse_headers_quotes
bio = BIO::from_string("Foo: \"bar\"")
result = Mime::DEFAULT.parse_headers(bio)
assert_equal 1, result.size
assert_equal MimeHeader.new("Foo", "bar"), result[0]
assert_equal "foo", result[0].name
end
def test_simple_parse_headers_comment
bio = BIO::from_string("Foo: (this is the right thing)ba(and this is the wrong one)r")
result = Mime::DEFAULT.parse_headers(bio)
assert_equal 1, result.size
assert_equal MimeHeader.new("Foo", "(this is the right thing)ba(and this is the wrong one)r"), result[0]
assert_equal "foo", result[0].name
end
def test_parse_headers_with_param
bio = BIO::from_string("Content-Type: Multipart/Related; boundary=MIME_boundary; type=text/xml")
result = Mime::DEFAULT.parse_headers(bio)
assert_equal 1, result.size
header = result[0]
assert_equal "content-type", header.name
assert_equal "multipart/related", header.value
assert_equal [MimeParam.new("boundary","MIME_boundary"),
MimeParam.new("type","text/xml")], header.params.to_a
end
def test_parse_headers_with_param_newline
bio = BIO::from_string("Content-Type: Multipart/Related\n boundary=MIME_boundary; type=text/xml")
result = Mime::DEFAULT.parse_headers(bio)
assert_equal 1, result.size
header = result[0]
assert_equal "content-type", header.name
assert_equal "multipart/related", header.value
assert_equal [MimeParam.new("boundary","MIME_boundary"),
MimeParam.new("type","text/xml")], header.params.to_a
end
def test_parse_headers_with_param_newline_and_semicolon
bio = BIO::from_string("Content-Type: Multipart/Related;\n boundary=MIME_boundary;\n Type=text/xml")
result = Mime::DEFAULT.parse_headers(bio)
assert_equal 1, result.size
header = result[0]
assert_equal "content-type", header.name
assert_equal "multipart/related", header.value
assert_equal [MimeParam.new("boundary","MIME_boundary"),
MimeParam.new("type","text/xml")], header.params.to_a
end
def test_advanced_mime_message
bio = BIO::from_string(MultipartSignedString)
result = Mime::DEFAULT.parse_headers(bio)
assert_equal "mime-version", result[0].name
assert_equal "1.0", result[0].value
assert_equal "to", result[1].name
assert_equal "user2@examples.com", result[1].value
assert_equal "from", result[2].name
assert_equal "alicedss@examples.com", result[2].value
assert_equal "subject", result[3].name
assert_equal "example 4.8", result[3].value
assert_equal "message-id", result[4].name
assert_equal "<020906002550300.249@examples.com>", result[4].value
assert_equal "date", result[5].name
assert_equal "fri, 06 sep 2002 00:25:21 -0300", result[5].value
assert_equal "content-type", result[6].name
assert_equal "multipart/signed", result[6].value
assert_equal "micalg", result[6].params[0].param_name
assert_equal "SHA1", result[6].params[0].param_value
assert_equal "boundary", result[6].params[1].param_name
assert_equal "----=_NextBoundry____Fri,_06_Sep_2002_00:25:21", result[6].params[1].param_value
assert_equal "protocol", result[6].params[2].param_name
assert_equal "application/pkcs7-signature", result[6].params[2].param_value
assert_equal 3, result[6].params.length
assert_equal 7, result.length
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/java/test_java_bio.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/java/test_java_bio.rb | module PKCS7Test
class TestJavaBIO < Test::Unit::TestCase
def test_string_bio_simple
bio = BIO::from_string("abc")
arr = Java::byte[20].new
read = bio.gets(arr, 10)
assert_equal 3, read
assert_equal "abc".to_java_bytes.to_a, arr.to_a[0...read]
end
def test_string_bio_simple_with_newline
bio = BIO::from_string("abc\n")
arr = Java::byte[20].new
read = bio.gets(arr, 10)
assert_equal 4, read
assert_equal "abc\n".to_java_bytes.to_a, arr.to_a[0...read]
end
def test_string_bio_simple_with_newline_and_more_data
bio = BIO::from_string("abc\nfoo\n\nbar")
arr = Java::byte[20].new
read = bio.gets(arr, 10)
assert_equal 4, read
assert_equal "abc\n".to_java_bytes.to_a, arr.to_a[0...read]
read = bio.gets(arr, 10)
assert_equal 4, read
assert_equal "foo\n".to_java_bytes.to_a, arr.to_a[0...read]
read = bio.gets(arr, 10)
assert_equal 1, read
assert_equal "\n".to_java_bytes.to_a, arr.to_a[0...read]
read = bio.gets(arr, 10)
assert_equal 3, read
assert_equal "bar".to_java_bytes.to_a, arr.to_a[0...read]
read = bio.gets(arr, 10)
assert_equal 0, read
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/java/test_java_pkcs7.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/java/test_java_pkcs7.rb | module PKCS7Test
class TestJavaPKCS7 < Test::Unit::TestCase
def test_is_signed
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_signed
assert p7.signed?
assert !p7.encrypted?
assert !p7.enveloped?
assert !p7.signed_and_enveloped?
assert !p7.data?
assert !p7.digest?
end
def test_is_encrypted
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_encrypted
assert !p7.signed?
assert p7.encrypted?
assert !p7.enveloped?
assert !p7.signed_and_enveloped?
assert !p7.data?
assert !p7.digest?
end
def test_is_enveloped
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_enveloped
assert !p7.signed?
assert !p7.encrypted?
assert p7.enveloped?
assert !p7.signed_and_enveloped?
assert !p7.data?
assert !p7.digest?
end
def test_is_signed_and_enveloped
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_signedAndEnveloped
assert !p7.signed?
assert !p7.encrypted?
assert !p7.enveloped?
assert p7.signed_and_enveloped?
assert !p7.data?
assert !p7.digest?
end
def test_is_data
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_data
assert !p7.signed?
assert !p7.encrypted?
assert !p7.enveloped?
assert !p7.signed_and_enveloped?
assert p7.data?
assert !p7.digest?
end
def test_is_digest
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_digest
assert !p7.signed?
assert !p7.encrypted?
assert !p7.enveloped?
assert !p7.signed_and_enveloped?
assert !p7.data?
assert p7.digest?
end
def test_set_detached
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_signed
sign = Signed.new
p7.sign = sign
test_p7 = PKCS7.new
test_p7.type = ASN1Registry::NID_pkcs7_data
test_p7.data = ASN1::OctetString.new("foo".to_java_bytes)
sign.contents = test_p7
p7.detached = 2
assert_equal 1, p7.get_detached
assert_equal nil, test_p7.get_data
end
def test_set_not_detached
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_signed
sign = Signed.new
p7.sign = sign
test_p7 = PKCS7.new
test_p7.type = ASN1Registry::NID_pkcs7_data
data = ASN1::OctetString.new("foo".to_java_bytes)
test_p7.data = data
sign.contents = test_p7
p7.detached = 0
assert_equal 0, p7.get_detached
assert_equal data, test_p7.get_data
end
def test_is_detached
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_signed
sign = Signed.new
p7.sign = sign
test_p7 = PKCS7.new
test_p7.type = ASN1Registry::NID_pkcs7_data
data = ASN1::OctetString.new("foo".to_java_bytes)
test_p7.data = data
sign.contents = test_p7
p7.detached = 1
assert p7.detached?
end
def test_is_detached_with_wrong_type
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_data
assert !p7.detached?
end
def _test_encrypt_generates_enveloped_PKCS7_object
p7 = PKCS7.encrypt([], "".to_java_bytes, nil, 0)
assert !p7.signed?
assert !p7.encrypted?
assert p7.enveloped?
assert !p7.signed_and_enveloped?
assert !p7.data?
assert !p7.digest?
end
def test_set_type_throws_exception_on_wrong_argument
assert_raise NativeException do
# 42 is a value that is not one of the valid NID's for type
PKCS7.new.type = 42
end
end
def test_set_type_signed
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_signed
assert p7.signed?
assert_equal 1, p7.get_sign.version
assert_nil p7.get_data
assert_nil p7.get_enveloped
assert_nil p7.get_signed_and_enveloped
assert_nil p7.get_digest
assert_nil p7.get_encrypted
assert_nil p7.get_other
end
def test_set_type_data
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_data
assert p7.data?
assert_equal ASN1::OctetString.new("".to_java_bytes), p7.get_data
assert_nil p7.get_sign
assert_nil p7.get_enveloped
assert_nil p7.get_signed_and_enveloped
assert_nil p7.get_digest
assert_nil p7.get_encrypted
assert_nil p7.get_other
end
def test_set_type_signed_and_enveloped
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_signedAndEnveloped
assert p7.signed_and_enveloped?
assert_equal 1, p7.get_signed_and_enveloped.version
assert_equal ASN1Registry::NID_pkcs7_data, p7.get_signed_and_enveloped.enc_data.content_type
assert_nil p7.get_sign
assert_nil p7.get_enveloped
assert_nil p7.get_data
assert_nil p7.get_digest
assert_nil p7.get_encrypted
assert_nil p7.get_other
end
def test_set_type_enveloped
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_enveloped
assert p7.enveloped?
assert_equal 0, p7.get_enveloped.version
assert_equal ASN1Registry::NID_pkcs7_data, p7.get_enveloped.enc_data.content_type
assert_nil p7.get_sign
assert_nil p7.get_signed_and_enveloped
assert_nil p7.get_data
assert_nil p7.get_digest
assert_nil p7.get_encrypted
assert_nil p7.get_other
end
def test_set_type_encrypted
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_encrypted
assert p7.encrypted?
assert_equal 0, p7.get_encrypted.version
assert_equal ASN1Registry::NID_pkcs7_data, p7.get_encrypted.enc_data.content_type
assert_nil p7.get_sign
assert_nil p7.get_signed_and_enveloped
assert_nil p7.get_data
assert_nil p7.get_digest
assert_nil p7.get_enveloped
assert_nil p7.get_other
end
def test_set_type_digest
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_digest
assert p7.digest?
assert_equal 0, p7.get_digest.version
assert_nil p7.get_sign
assert_nil p7.get_signed_and_enveloped
assert_nil p7.get_data
assert_nil p7.get_encrypted
assert_nil p7.get_enveloped
assert_nil p7.get_other
end
def test_set_cipher_on_non_enveloped_object
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_digest
assert_raise NativeException do
p7.cipher = nil
end
p7.type = ASN1Registry::NID_pkcs7_encrypted
assert_raise NativeException do
p7.cipher = nil
end
p7.type = ASN1Registry::NID_pkcs7_data
assert_raise NativeException do
p7.cipher = nil
end
p7.type = ASN1Registry::NID_pkcs7_signed
assert_raise NativeException do
p7.cipher = nil
end
end
def test_set_cipher_on_enveloped_object
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_enveloped
c = javax.crypto.Cipher.getInstance("RSA")
cipher = CipherSpec.new(c, "RSA", 128)
p7.cipher = cipher
assert_equal cipher, p7.get_enveloped.enc_data.cipher
end
def test_set_cipher_on_signedAndEnveloped_object
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_signedAndEnveloped
c = javax.crypto.Cipher.getInstance("RSA")
cipher = CipherSpec.new(c, "RSA", 128)
p7.cipher = cipher
assert_equal cipher, p7.get_signed_and_enveloped.enc_data.cipher
end
def test_add_recipient_info_to_something_that_cant_have_recipients
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_signed
assert_raise NativeException do
p7.add_recipient(X509Cert)
end
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_data
assert_raise NativeException do
p7.add_recipient(X509Cert)
end
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_encrypted
assert_raise NativeException do
p7.add_recipient(X509Cert)
end
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_digest
assert_raise NativeException do
p7.add_recipient(X509Cert)
end
end
def test_add_recipient_info_to_enveloped_should_add_that_to_stack
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_enveloped
ri = p7.add_recipient(X509Cert)
assert_equal 1, p7.get_enveloped.recipient_info.size
assert_equal ri, p7.get_enveloped.recipient_info.iterator.next
end
def test_add_recipient_info_to_signedAndEnveloped_should_add_that_to_stack
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_signedAndEnveloped
ri = p7.add_recipient(X509Cert)
assert_equal 1, p7.get_signed_and_enveloped.recipient_info.size
assert_equal ri, p7.get_signed_and_enveloped.recipient_info.iterator.next
end
def test_add_signer_to_something_that_cant_have_signers
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_enveloped
assert_raise NativeException do
p7.add_signer(SignerInfoWithPkey.new(nil, nil, nil, nil, nil, nil, nil))
end
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_data
assert_raise NativeException do
p7.add_signer(SignerInfoWithPkey.new(nil, nil, nil, nil, nil, nil, nil))
end
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_encrypted
assert_raise NativeException do
p7.add_signer(SignerInfoWithPkey.new(nil, nil, nil, nil, nil, nil, nil))
end
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_digest
assert_raise NativeException do
p7.add_signer(SignerInfoWithPkey.new(nil, nil, nil, nil, nil, nil, nil))
end
end
def test_add_signer_to_signed_should_add_that_to_stack
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_signed
si = SignerInfoWithPkey.new(nil, nil, nil, nil, nil, nil, nil)
p7.add_signer(si)
assert_equal 1, p7.get_sign.signer_info.size
assert_equal si, p7.get_sign.signer_info.iterator.next
end
def test_add_signer_to_signedAndEnveloped_should_add_that_to_stack
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_signedAndEnveloped
si = SignerInfoWithPkey.new(nil, nil, nil, nil, nil, nil, nil)
p7.add_signer(si)
assert_equal 1, p7.get_signed_and_enveloped.signer_info.size
assert_equal si, p7.get_signed_and_enveloped.signer_info.iterator.next
end
def create_signer_info_with_algo(algo)
md5 = AlgorithmIdentifier.new(ASN1Registry.nid2obj(4))
SignerInfoWithPkey.new(DERInteger.new(BigInteger::ONE),
IssuerAndSerialNumber.new(X509Name.new("C=SE"), DERInteger.new(BigInteger::ONE)),
algo,
DERSet.new,
md5,
DEROctetString.new([].to_java(:byte)),
DERSet.new)
end
def test_add_signer_to_signed_with_new_algo_should_add_that_algo_to_the_algo_list
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_signed
# YES, these numbers are correct. Don't change them. They are OpenSSL internal NIDs
md5 = AlgorithmIdentifier.new(ASN1Registry.nid2obj(4))
md4 = AlgorithmIdentifier.new(ASN1Registry.nid2obj(5))
si = create_signer_info_with_algo(md5)
p7.add_signer(si)
assert_equal md5, p7.get_sign.md_algs.iterator.next
assert_equal 1, p7.get_sign.md_algs.size
si = create_signer_info_with_algo(md5)
p7.add_signer(si)
assert_equal md5, p7.get_sign.md_algs.iterator.next
assert_equal 1, p7.get_sign.md_algs.size
si = create_signer_info_with_algo(md4)
p7.add_signer(si)
assert_equal 2, p7.get_sign.md_algs.size
assert p7.get_sign.md_algs.contains(md4)
assert p7.get_sign.md_algs.contains(md5)
end
def test_add_signer_to_signedAndEnveloped_with_new_algo_should_add_that_algo_to_the_algo_list
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_signedAndEnveloped
# YES, these numbers are correct. Don't change them. They are OpenSSL internal NIDs
md5 = AlgorithmIdentifier.new(ASN1Registry.nid2obj(4))
md4 = AlgorithmIdentifier.new(ASN1Registry.nid2obj(5))
si = create_signer_info_with_algo(md5)
p7.add_signer(si)
assert_equal md5, p7.get_signed_and_enveloped.md_algs.iterator.next
assert_equal 1, p7.get_signed_and_enveloped.md_algs.size
si = create_signer_info_with_algo(md5)
p7.add_signer(si)
assert_equal md5, p7.get_signed_and_enveloped.md_algs.iterator.next
assert_equal 1, p7.get_signed_and_enveloped.md_algs.size
si = create_signer_info_with_algo(md4)
p7.add_signer(si)
assert_equal 2, p7.get_signed_and_enveloped.md_algs.size
assert p7.get_signed_and_enveloped.md_algs.contains(md4)
assert p7.get_signed_and_enveloped.md_algs.contains(md5)
end
def test_set_content_on_data_throws_exception
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_data
assert_raise NativeException do
p7.setContent(PKCS7.new)
end
end
def test_set_content_on_enveloped_throws_exception
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_enveloped
assert_raise NativeException do
p7.setContent(PKCS7.new)
end
end
def test_set_content_on_signedAndEnveloped_throws_exception
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_signedAndEnveloped
assert_raise NativeException do
p7.setContent(PKCS7.new)
end
end
def test_set_content_on_encrypted_throws_exception
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_encrypted
assert_raise NativeException do
p7.setContent(PKCS7.new)
end
end
def test_set_content_on_signed_sets_the_content
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_signed
p7new = PKCS7.new
p7.setContent(p7new)
assert_equal p7new, p7.get_sign.contents
end
def test_set_content_on_digest_sets_the_content
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_digest
p7new = PKCS7.new
p7.setContent(p7new)
assert_equal p7new, p7.get_digest.contents
end
def test_get_signer_info_on_digest_returns_null
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_digest
assert_nil p7.signer_info
end
def test_get_signer_info_on_data_returns_null
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_data
assert_nil p7.signer_info
end
def test_get_signer_info_on_encrypted_returns_null
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_encrypted
assert_nil p7.signer_info
end
def test_get_signer_info_on_enveloped_returns_null
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_enveloped
assert_nil p7.signer_info
end
def test_get_signer_info_on_signed_returns_signer_info
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_signed
assert_equal p7.get_sign.signer_info.object_id, p7.signer_info.object_id
end
def test_get_signer_info_on_signedAndEnveloped_returns_signer_info
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_signedAndEnveloped
assert_equal p7.get_signed_and_enveloped.signer_info.object_id, p7.signer_info.object_id
end
def test_content_new_on_data_raises_exception
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_data
assert_raise NativeException do
p7.content_new(ASN1Registry::NID_pkcs7_data)
end
end
def test_content_new_on_encrypted_raises_exception
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_encrypted
assert_raise NativeException do
p7.content_new(ASN1Registry::NID_pkcs7_data)
end
end
def test_content_new_on_enveloped_raises_exception
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_enveloped
assert_raise NativeException do
p7.content_new(ASN1Registry::NID_pkcs7_data)
end
end
def test_content_new_on_signedAndEnveloped_raises_exception
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_signedAndEnveloped
assert_raise NativeException do
p7.content_new(ASN1Registry::NID_pkcs7_data)
end
end
def test_content_new_on_digest_creates_new_content
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_digest
p7.content_new(ASN1Registry::NID_pkcs7_signedAndEnveloped)
assert p7.get_digest.contents.signed_and_enveloped?
p7.content_new(ASN1Registry::NID_pkcs7_encrypted)
assert p7.get_digest.contents.encrypted?
end
def test_content_new_on_signed_creates_new_content
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_signed
p7.content_new(ASN1Registry::NID_pkcs7_signedAndEnveloped)
assert p7.get_sign.contents.signed_and_enveloped?
p7.content_new(ASN1Registry::NID_pkcs7_encrypted)
assert p7.get_sign.contents.encrypted?
end
def test_add_certificate_on_data_throws_exception
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_data
assert_raise NativeException do
p7.add_certificate(X509Cert)
end
end
def test_add_certificate_on_enveloped_throws_exception
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_enveloped
assert_raise NativeException do
p7.add_certificate(X509Cert)
end
end
def test_add_certificate_on_encrypted_throws_exception
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_encrypted
assert_raise NativeException do
p7.add_certificate(X509Cert)
end
end
def test_add_certificate_on_digest_throws_exception
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_digest
assert_raise NativeException do
p7.add_certificate(X509Cert)
end
end
def test_add_certificate_on_signed_adds_the_certificate
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_signed
p7.add_certificate(X509Cert)
assert_equal 1, p7.get_sign.cert.size
assert_equal X509Cert, p7.get_sign.cert.iterator.next
end
def test_add_certificate_on_signedAndEnveloped_adds_the_certificate
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_signedAndEnveloped
p7.add_certificate(X509Cert)
assert_equal 1, p7.get_signed_and_enveloped.cert.size
assert_equal X509Cert, p7.get_signed_and_enveloped.cert.get(0)
end
def test_add_crl_on_data_throws_exception
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_data
assert_raise NativeException do
p7.add_crl(X509CRL)
end
end
def test_add_crl_on_enveloped_throws_exception
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_enveloped
assert_raise NativeException do
p7.add_crl(X509CRL)
end
end
def test_add_crl_on_encrypted_throws_exception
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_encrypted
assert_raise NativeException do
p7.add_crl(X509CRL)
end
end
def test_add_crl_on_digest_throws_exception
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_digest
assert_raise NativeException do
p7.add_crl(X509CRL)
end
end
def test_add_crl_on_signed_adds_the_crl
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_signed
p7.add_crl(X509CRL)
assert_equal 1, p7.get_sign.crl.size
assert_equal X509CRL, p7.get_sign.crl.iterator.next
end
def test_add_crl_on_signedAndEnveloped_adds_the_crl
p7 = PKCS7.new
p7.type = ASN1Registry::NID_pkcs7_signedAndEnveloped
p7.add_crl(X509CRL)
assert_equal 1, p7.get_signed_and_enveloped.crl.size
assert_equal X509CRL, p7.get_signed_and_enveloped.crl.get(0)
end
EXISTING_PKCS7_DEF = "0\202\002 \006\t*\206H\206\367\r\001\a\003\240\202\002\0210\202\002\r\002\001\0001\202\001\2700\201\331\002\001\0000B0=1\0230\021\006\n\t\222&\211\223\362,d\001\031\026\003org1\0310\027\006\n\t\222&\211\223\362,d\001\031\026\truby-lang1\v0\t\006\003U\004\003\f\002CA\002\001\0020\r\006\t*\206H\206\367\r\001\001\001\005\000\004\201\200\213kF\330\030\362\237\363$\311\351\207\271+_\310sr\344\233N\200\233)\272\226\343\003\224OOf\372 \r\301{\206\367\241\270\006\240\254\3179F\232\231Q\232\225\347\373\233\032\375\360\035o\371\275p\306\v5Z)\263\037\302|\307\300\327\a\375\023G'Ax\313\346\261\254\227K\026\364\242\337\367\362rk\276\023\217m\326\343F\366I1\263\nLuNf\234\203\261\300\030\232Q\277\231\f0\030\001\332\021\0030\201\331\002\001\0000B0=1\0230\021\006\n\t\222&\211\223\362,d\001\031\026\003org1\0310\027\006\n\t\222&\211\223\362,d\001\031\026\truby-lang1\v0\t\006\003U\004\003\f\002CA\002\001\0030\r\006\t*\206H\206\367\r\001\001\001\005\000\004\201\200\215\223\3428\2440]\0278\016\230,\315\023Tg\325`\376~\353\304\020\243N{\326H\003\005\361q\224OI\310\2324-\341?\355&r\215\233\361\245jF\255R\271\203D\304v\325\265\243\321$\bSh\031i\eS\240\227\362\221\364\232\035\202\f?x\031\223D\004ZHD\355'g\243\037\236mJ\323\210\347\274m\324-\351\332\353#A\273\002\"h\aM\202\347\236\265\aI$@\240bt=<\212\2370L\006\t*\206H\206\367\r\001\a\0010\035\006\t`\206H\001e\003\004\001\002\004\020L?\325\372\\\360\366\372\237|W\333nnI\255\200 \253\234\252\263\006\335\037\320\350{s\352r\337\304\305\216\223k\003\376f\027_\201\035#*\002yM\334"
EXISTING_PKCS7_1 = PKCS7::from_asn1(ASN1InputStream.new(EXISTING_PKCS7_DEF.to_java_bytes).read_object)
def test_encrypt_integration_test
certs = [X509Cert]
c = Cipher.get_instance("AES", BCP.new)
cipher = CipherSpec.new(c, "AES-128-CBC", 128)
data = "aaaaa\nbbbbb\nccccc\n".to_java_bytes
PKCS7::encrypt(certs, data, cipher, PKCS7::BINARY)
# puts
# puts PKCS7::encrypt(certs, data, cipher, PKCS7::BINARY)
# puts
# puts EXISTING_PKCS7_1
end
EXISTING_PKCS7_PEM = <<PKCS7STR
-----BEGIN PKCS7-----
MIICIAYJKoZIhvcNAQcDoIICETCCAg0CAQAxggG4MIHZAgEAMEIwPTETMBEGCgmS
JomT8ixkARkWA29yZzEZMBcGCgmSJomT8ixkARkWCXJ1YnktbGFuZzELMAkGA1UE
AwwCQ0ECAQIwDQYJKoZIhvcNAQEBBQAEgYCPGMV4KS/8amYA2xeIjj9qLseJf7dl
BtSDp+YAU3y1JnW7XufBCKxYw7eCuhWWA/mrxijr+wdsFDvSalM6nPX2P2NiVMWP
a7mzErZ4WrzkKIuGczYPYPJetwBYuhik3ya4ygYygoYssVRAITOSsEKpfqHAPmI+
AUJkqmCdGpQu9TCB2QIBADBCMD0xEzARBgoJkiaJk/IsZAEZFgNvcmcxGTAXBgoJ
kiaJk/IsZAEZFglydWJ5LWxhbmcxCzAJBgNVBAMMAkNBAgEDMA0GCSqGSIb3DQEB
AQUABIGAPaBX0KM3S+2jcrQrncu1jrvm1PUXlUvMfFIG2oBfPkMhiqCBvkOct1Ve
ws1hxvGtsqyjAUn02Yx1+gQJhTN4JZZHNqkfi0TwN32nlwLxclKcrbF9bvtMiVHx
V3LrSygblxxJsBf8reoV4yTJRa3w98bEoDhjUwjfy5xTml2cAn4wTAYJKoZIhvcN
AQcBMB0GCWCGSAFlAwQBAgQQath+2gUo4ntkKl8FO1LLhoAg58j0Jn/OfWG3rNRH
kTtUQfnBFk/UGbTZgExHILaGz8Y=
-----END PKCS7-----
PKCS7STR
PKCS7_PEM_CONTENTS = "\347\310\364&\177\316}a\267\254\324G\221;TA\371\301\026O\324\031\264\331\200LG \266\206\317\306"
PKCS7_PEM_FIRST_KEY = "\217\030\305x)/\374jf\000\333\027\210\216?j.\307\211\177\267e\006\324\203\247\346\000S|\265&u\273^\347\301\b\254X\303\267\202\272\025\226\003\371\253\306(\353\373\al\024;\322jS:\234\365\366?cbT\305\217k\271\263\022\266xZ\274\344(\213\206s6\017`\362^\267\000X\272\030\244\337&\270\312\0062\202\206,\261T@!3\222\260B\251~\241\300>b>\001Bd\252`\235\032\224.\365"
PKCS7_PEM_SECOND_KEY = "=\240W\320\2437K\355\243r\264+\235\313\265\216\273\346\324\365\027\225K\314|R\006\332\200_>C!\212\240\201\276C\234\267U^\302\315a\306\361\255\262\254\243\001I\364\331\214u\372\004\t\2053x%\226G6\251\037\213D\3607}\247\227\002\361rR\234\255\261}n\373L\211Q\361Wr\353K(\e\227\034I\260\027\374\255\352\025\343$\311E\255\360\367\306\304\2408cS\b\337\313\234S\232]\234\002~"
def test_PEM_read_pkcs7_bio
bio = BIO::mem_buf(EXISTING_PKCS7_PEM.to_java_bytes)
p7 = PKCS7.read_pem(bio)
assert_equal ASN1Registry::NID_pkcs7_enveloped, p7.type
env = p7.get_enveloped
assert_equal 0, env.version
enc_data = env.enc_data
assert_equal ASN1Registry::NID_pkcs7_data, enc_data.content_type
assert_equal ASN1Registry::NID_aes_128_cbc, ASN1Registry::obj2nid(enc_data.algorithm.get_object_id)
assert_equal PKCS7_PEM_CONTENTS, String.from_java_bytes(enc_data.enc_data.octets)
ris = env.recipient_info
assert_equal 2, ris.size
first = second = nil
tmp = ris.iterator.next
if tmp.issuer_and_serial.certificate_serial_number.value == 2
first = tmp
iter = ris.iterator
iter.next
second = iter.next
else
second = tmp
iter = ris.iterator
iter.next
first = iter.next
end
assert_equal 0, first.version
assert_equal 0, second.version
assert_equal "DC=org,DC=ruby-lang,CN=CA", first.issuer_and_serial.name.to_s
assert_equal "DC=org,DC=ruby-lang,CN=CA", second.issuer_and_serial.name.to_s
assert_equal ASN1Registry::NID_rsaEncryption, ASN1Registry::obj2nid(first.key_enc_algor.get_object_id)
assert_equal ASN1Registry::NID_rsaEncryption, ASN1Registry::obj2nid(second.key_enc_algor.get_object_id)
assert_equal PKCS7_PEM_FIRST_KEY, String.from_java_bytes(first.enc_key.octets)
assert_equal PKCS7_PEM_SECOND_KEY, String.from_java_bytes(second.enc_key.octets)
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/ref/compile.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/test/ref/compile.rb | #!/usr/bin/env ruby
name = ARGV[0]
system("rm -rf #{name}")
system("gcc -lssl -lcrypto -o #{name} #{name}.c")
system("chmod +x #{name}")
system("./#{name}")
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/lib/openssl.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/lib/openssl.rb | =begin
= $RCSfile$ -- Loader for all OpenSSL C-space and Ruby-space definitions
= Info
'OpenSSL for Ruby 2' project
Copyright (C) 2002 Michal Rokos <m.rokos@sh.cvut.cz>
All rights reserved.
= Licence
This program is licenced under the same licence as Ruby.
(See the file 'LICENCE'.)
= Version
$Id: openssl.rb 12496 2007-06-08 15:02:04Z technorama $
=end
# TODO: remove this chunk after 1.4 support is dropped
require 'digest'
unless defined?(::Digest::Class)
# restricted support for jruby <= 1.4 (1.8.6 Digest compat)
module Digest
class Class
def self.hexdigest(name, data)
digest(name, data).unpack('H*')[0]
end
def self.digest(data, name)
digester = const_get(name).new
digester.update(data)
digester.finish
end
def hexdigest
digest.unpack('H*')[0]
end
def digest
dup.finish
end
def ==(oth)
digest == oth.digest
end
def to_s
hexdigest
end
def size
digest_length
end
def length
digest_length
end
end
end
end
# end of compat chunk.
require 'jopenssl'
require 'openssl/bn'
require 'openssl/cipher'
require 'openssl/digest'
require 'openssl/pkcs7'
require 'openssl/ssl'
require 'openssl/x509'
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/lib/openssl/digest.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/lib/openssl/digest.rb | =begin
= $RCSfile$ -- Ruby-space predefined Digest subclasses
= Info
'OpenSSL for Ruby 2' project
Copyright (C) 2002 Michal Rokos <m.rokos@sh.cvut.cz>
All rights reserved.
= Licence
This program is licenced under the same licence as Ruby.
(See the file 'LICENCE'.)
= Version
$Id: digest.rb 15600 2008-02-25 08:48:57Z technorama $
=end
##
# Should we care what if somebody require this file directly?
#require 'openssl'
module OpenSSL
class Digest
alg = %w(DSS DSS1 MD2 MD4 MD5 MDC2 RIPEMD160 SHA SHA1)
if OPENSSL_VERSION_NUMBER > 0x00908000
alg += %w(SHA224 SHA256 SHA384 SHA512)
end
def self.digest(name, data)
super(data, name)
end
alg.each{|name|
klass = Class.new(Digest){
define_method(:initialize){|*data|
if data.length > 1
raise ArgumentError,
"wrong number of arguments (#{data.length} for 1)"
end
super(name, data.first)
}
}
singleton = (class <<klass; self; end)
singleton.class_eval{
define_method(:digest){|data| Digest.digest(name, data) }
define_method(:hexdigest){|data| Digest.hexdigest(name, data) }
}
const_set(name, klass)
}
# This class is only provided for backwards compatibility. Use OpenSSL::Digest in the future.
class Digest < Digest
def initialize(*args)
# add warning
super(*args)
end
end
end # Digest
end # OpenSSL
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/lib/openssl/ssl.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/lib/openssl/ssl.rb | =begin
= $RCSfile$ -- Ruby-space definitions that completes C-space funcs for SSL
= Info
'OpenSSL for Ruby 2' project
Copyright (C) 2001 GOTOU YUUZOU <gotoyuzo@notwork.org>
All rights reserved.
= Licence
This program is licenced under the same licence as Ruby.
(See the file 'LICENCE'.)
= Version
$Id: ssl.rb 16193 2008-04-25 06:51:21Z knu $
=end
require "openssl"
require "openssl/buffering"
require "fcntl"
module OpenSSL
module SSL
class SSLContext
DEFAULT_PARAMS = {
:ssl_version => "SSLv23",
:verify_mode => OpenSSL::SSL::VERIFY_PEER,
:ciphers => "ALL:!ADH:!EXPORT:!SSLv2:RC4+RSA:+HIGH:+MEDIUM:+LOW",
:options => OpenSSL::SSL::OP_ALL,
}
DEFAULT_CERT_STORE = OpenSSL::X509::Store.new
DEFAULT_CERT_STORE.set_default_paths
if defined?(OpenSSL::X509::V_FLAG_CRL_CHECK_ALL)
DEFAULT_CERT_STORE.flags = OpenSSL::X509::V_FLAG_CRL_CHECK_ALL
end
def set_params(params={})
params = DEFAULT_PARAMS.merge(params)
self.ssl_version = params.delete(:ssl_version)
params.each{|name, value| self.__send__("#{name}=", value) }
if self.verify_mode != OpenSSL::SSL::VERIFY_NONE
unless self.ca_file or self.ca_path or self.cert_store
self.cert_store = DEFAULT_CERT_STORE
end
end
return params
end
end
module SocketForwarder
def addr
to_io.addr
end
def peeraddr
to_io.peeraddr
end
def setsockopt(level, optname, optval)
to_io.setsockopt(level, optname, optval)
end
def getsockopt(level, optname)
to_io.getsockopt(level, optname)
end
def fcntl(*args)
to_io.fcntl(*args)
end
def closed?
to_io.closed?
end
def do_not_reverse_lookup=(flag)
to_io.do_not_reverse_lookup = flag
end
end
module Nonblock
def initialize(*args)
flag = File::NONBLOCK
flag |= @io.fcntl(Fcntl::F_GETFL) if defined?(Fcntl::F_GETFL)
@io.fcntl(Fcntl::F_SETFL, flag)
super
end
end
def verify_certificate_identity(cert, hostname)
should_verify_common_name = true
cert.extensions.each{|ext|
next if ext.oid != "subjectAltName"
ext.value.split(/,\s+/).each{|general_name|
if /\ADNS:(.*)/ =~ general_name
should_verify_common_name = false
reg = Regexp.escape($1).gsub(/\\\*/, "[^.]+")
return true if /\A#{reg}\z/i =~ hostname
elsif /\AIP Address:(.*)/ =~ general_name
should_verify_common_name = false
return true if $1 == hostname
end
}
}
if should_verify_common_name
cert.subject.to_a.each{|oid, value|
if oid == "CN"
reg = Regexp.escape(value).gsub(/\\\*/, "[^.]+")
return true if /\A#{reg}\z/i =~ hostname
end
}
end
return false
end
module_function :verify_certificate_identity
class SSLSocket
include Buffering
include SocketForwarder
include Nonblock
def post_connection_check(hostname)
unless OpenSSL::SSL.verify_certificate_identity(peer_cert, hostname)
raise SSLError, "hostname was not match with the server certificate"
end
return true
end
def session
SSL::Session.new(self)
rescue SSL::Session::SessionError
nil
end
end
class SSLServer
include SocketForwarder
attr_accessor :start_immediately
def initialize(svr, ctx)
@svr = svr
@ctx = ctx
unless ctx.session_id_context
session_id = OpenSSL::Digest::MD5.hexdigest($0)
@ctx.session_id_context = session_id
end
@start_immediately = true
end
def to_io
@svr
end
def listen(backlog=5)
@svr.listen(backlog)
end
def shutdown(how=Socket::SHUT_RDWR)
@svr.shutdown(how)
end
def accept
sock = @svr.accept
begin
ssl = OpenSSL::SSL::SSLSocket.new(sock, @ctx)
ssl.sync_close = true
ssl.accept if @start_immediately
ssl
rescue SSLError => ex
sock.close
raise ex
end
end
def close
@svr.close
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/lib/openssl/buffering.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/lib/openssl/buffering.rb | =begin
= $RCSfile$ -- Buffering mix-in module.
= Info
'OpenSSL for Ruby 2' project
Copyright (C) 2001 GOTOU YUUZOU <gotoyuzo@notwork.org>
All rights reserved.
= Licence
This program is licenced under the same licence as Ruby.
(See the file 'LICENCE'.)
= Version
$Id: buffering.rb 13706 2007-10-15 08:29:08Z usa $
=end
module Buffering
include Enumerable
attr_accessor :sync
BLOCK_SIZE = 1024*16
def initialize(*args)
@eof = false
@rbuffer = ""
@sync = @io.sync
end
#
# for reading.
#
private
def fill_rbuff
begin
@rbuffer << self.sysread(BLOCK_SIZE)
rescue Errno::EAGAIN
retry
rescue EOFError
@eof = true
end
end
def consume_rbuff(size=nil)
if @rbuffer.empty?
nil
else
size = @rbuffer.size unless size
ret = @rbuffer[0, size]
@rbuffer[0, size] = ""
ret
end
end
public
def read(size=nil, buf=nil)
if size == 0
if buf
buf.clear
else
buf = ""
end
return @eof ? nil : buf
end
until @eof
break if size && size <= @rbuffer.size
fill_rbuff
end
ret = consume_rbuff(size) || ""
if buf
buf.replace(ret)
ret = buf
end
(size && ret.empty?) ? nil : ret
end
def readpartial(maxlen, buf=nil)
if maxlen == 0
if buf
buf.clear
else
buf = ""
end
return @eof ? nil : buf
end
if @rbuffer.empty?
begin
return sysread(maxlen, buf)
rescue Errno::EAGAIN
retry
end
end
ret = consume_rbuff(maxlen)
if buf
buf.replace(ret)
ret = buf
end
raise EOFError if ret.empty?
ret
end
def gets(eol=$/)
idx = @rbuffer.index(eol)
until @eof
break if idx
fill_rbuff
idx = @rbuffer.index(eol)
end
if eol.is_a?(Regexp)
size = idx ? idx+$&.size : nil
else
size = idx ? idx+eol.size : nil
end
consume_rbuff(size)
end
def each(eol=$/)
while line = self.gets(eol)
yield line
end
end
alias each_line each
def readlines(eol=$/)
ary = []
while line = self.gets(eol)
ary << line
end
ary
end
def readline(eol=$/)
raise EOFError if eof?
gets(eol)
end
def getc
c = read(1)
c ? c[0] : nil
end
def each_byte
while c = getc
yield(c)
end
end
def readchar
raise EOFError if eof?
getc
end
def ungetc(c)
@rbuffer[0,0] = c.chr
end
def eof?
fill_rbuff if !@eof && @rbuffer.empty?
@eof && @rbuffer.empty?
end
alias eof eof?
#
# for writing.
#
private
def do_write(s)
@wbuffer = "" unless defined? @wbuffer
@wbuffer << s
@sync ||= false
if @sync or @wbuffer.size > BLOCK_SIZE or idx = @wbuffer.rindex($/)
remain = idx ? idx + $/.size : @wbuffer.length
nwritten = 0
while remain > 0
str = @wbuffer[nwritten,remain]
begin
nwrote = syswrite(str)
rescue Errno::EAGAIN
retry
end
remain -= nwrote
nwritten += nwrote
end
@wbuffer[0,nwritten] = ""
end
end
public
def write(s)
do_write(s)
s.length
end
def << (s)
do_write(s)
self
end
def puts(*args)
s = ""
if args.empty?
s << "\n"
end
args.each{|arg|
s << arg.to_s
if $/ && /\n\z/ !~ s
s << "\n"
end
}
do_write(s)
nil
end
def print(*args)
s = ""
args.each{ |arg| s << arg.to_s }
do_write(s)
nil
end
def printf(s, *args)
do_write(s % args)
nil
end
def flush
osync = @sync
@sync = true
do_write ""
@sync = osync
end
def close
flush rescue nil
sysclose
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/lib/openssl/x509.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/lib/openssl/x509.rb | =begin
= $RCSfile$ -- Ruby-space definitions that completes C-space funcs for X509 and subclasses
= Info
'OpenSSL for Ruby 2' project
Copyright (C) 2002 Michal Rokos <m.rokos@sh.cvut.cz>
All rights reserved.
= Licence
This program is licenced under the same licence as Ruby.
(See the file 'LICENCE'.)
= Version
$Id: x509.rb 11708 2007-02-12 23:01:19Z shyouhei $
=end
require "openssl"
module OpenSSL
module X509
class ExtensionFactory
def create_extension(*arg)
if arg.size > 1
create_ext(*arg)
else
send("create_ext_from_"+arg[0].class.name.downcase, arg[0])
end
end
def create_ext_from_array(ary)
raise ExtensionError, "unexpected array form" if ary.size > 3
create_ext(ary[0], ary[1], ary[2])
end
def create_ext_from_string(str) # "oid = critical, value"
oid, value = str.split(/=/, 2)
oid.strip!
value.strip!
create_ext(oid, value)
end
def create_ext_from_hash(hash)
create_ext(hash["oid"], hash["value"], hash["critical"])
end
end
class Extension
def to_s # "oid = critical, value"
str = self.oid
str << " = "
str << "critical, " if self.critical?
str << self.value.gsub(/\n/, ", ")
end
def to_h # {"oid"=>sn|ln, "value"=>value, "critical"=>true|false}
{"oid"=>self.oid,"value"=>self.value,"critical"=>self.critical?}
end
def to_a
[ self.oid, self.value, self.critical? ]
end
end
class Name
module RFC2253DN
Special = ',=+<>#;'
HexChar = /[0-9a-fA-F]/
HexPair = /#{HexChar}#{HexChar}/
HexString = /#{HexPair}+/
Pair = /\\(?:[#{Special}]|\\|"|#{HexPair})/
StringChar = /[^#{Special}\\"]/
QuoteChar = /[^\\"]/
AttributeType = /[a-zA-Z][0-9a-zA-Z]*|[0-9]+(?:\.[0-9]+)*/
AttributeValue = /
(?!["#])((?:#{StringChar}|#{Pair})*)|
\#(#{HexString})|
"((?:#{QuoteChar}|#{Pair})*)"
/x
TypeAndValue = /\A(#{AttributeType})=#{AttributeValue}/
module_function
def expand_pair(str)
return nil unless str
return str.gsub(Pair){|pair|
case pair.size
when 2 then pair[1,1]
when 3 then Integer("0x#{pair[1,2]}").chr
else raise OpenSSL::X509::NameError, "invalid pair: #{str}"
end
}
end
def expand_hexstring(str)
return nil unless str
der = str.gsub(HexPair){|hex| Integer("0x#{hex}").chr }
a1 = OpenSSL::ASN1.decode(der)
return a1.value, a1.tag
end
def expand_value(str1, str2, str3)
value = expand_pair(str1)
value, tag = expand_hexstring(str2) unless value
value = expand_pair(str3) unless value
return value, tag
end
def scan(dn)
str = dn
ary = []
while true
if md = TypeAndValue.match(str)
matched = md.to_s
remain = md.post_match
type = md[1]
value, tag = expand_value(md[2], md[3], md[4]) rescue nil
if value
type_and_value = [type, value]
type_and_value.push(tag) if tag
ary.unshift(type_and_value)
if remain.length > 2 && remain[0] == ?,
str = remain[1..-1]
next
elsif remain.length > 2 && remain[0] == ?+
raise OpenSSL::X509::NameError,
"multi-valued RDN is not supported: #{dn}"
elsif remain.empty?
break
end
end
end
msg_dn = dn[0, dn.length - str.length] + " =>" + str
raise OpenSSL::X509::NameError, "malformed RDN: #{msg_dn}"
end
return ary
end
end
class <<self
def parse_rfc2253(str, template=OBJECT_TYPE_TEMPLATE)
ary = OpenSSL::X509::Name::RFC2253DN.scan(str)
self.new(ary, template)
end
def parse_openssl(str, template=OBJECT_TYPE_TEMPLATE)
ary = str.scan(/\s*([^\/,]+)\s*/).collect{|i| i[0].split("=", 2) }
self.new(ary, template)
end
alias parse parse_openssl
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/lib/openssl/dummy.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/lib/openssl/dummy.rb | warn "Warning: OpenSSL ASN1/PKey/X509/Netscape/PKCS7 implementation unavailable"
warn "You need to download or install BouncyCastle jars (bc-prov-*.jar, bc-mail-*.jar)"
warn "to fix this."
module OpenSSL
module ASN1
class ASN1Error < OpenSSLError; end
class ASN1Data; end
class Primitive; end
class Constructive; end
end
module X509
class Name; end
class Certificate; end
class Extension; end
class CRL; end
class Revoked; end
class Store
def set_default_paths; end
end
class Request; end
class Attribute; end
end
module Netscape
class SPKI; end
end
class PKCS7
# this definition causes TypeError "superclass mismatch for class PKCS7"
# MRI also crashes following definition;
# class Foo; class Foo < Foo; end; end
# class Foo; class Foo < Foo; end; end
#
# class PKCS7 < PKCS7; end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/lib/openssl/pkcs7.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/lib/openssl/pkcs7.rb | =begin
= $RCSfile$ -- PKCS7
= Licence
This program is licenced under the same licence as Ruby.
(See the file 'LICENCE'.)
= Version
$Id: digest.rb 12148 2007-04-05 05:59:22Z technorama $
=end
module OpenSSL
class PKCS7
# This class is only provided for backwards compatibility. Use OpenSSL::PKCS7 in the future.
class PKCS7 < PKCS7
def initialize(*args)
super(*args)
warn("Warning: OpenSSL::PKCS7::PKCS7 is deprecated after Ruby 1.9; use OpenSSL::PKCS7 instead")
end
end
end # PKCS7
end # OpenSSL
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/lib/openssl/dummyssl.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/lib/openssl/dummyssl.rb | warn "Warning: OpenSSL SSL implementation unavailable"
warn "You must run on JDK 1.5 (Java 5) or higher to use SSL"
module OpenSSL
module SSL
class SSLError < OpenSSLError; end
class SSLContext; end
class SSLSocket; end
VERIFY_NONE = 0
VERIFY_PEER = 1
VERIFY_FAIL_IF_NO_PEER_CERT = 2
VERIFY_CLIENT_ONCE = 4
OP_ALL = 0x00000FFF
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/lib/openssl/bn.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/lib/openssl/bn.rb | =begin
= $RCSfile$ -- Ruby-space definitions that completes C-space funcs for BN
= Info
'OpenSSL for Ruby 2' project
Copyright (C) 2002 Michal Rokos <m.rokos@sh.cvut.cz>
All rights reserved.
= Licence
This program is licenced under the same licence as Ruby.
(See the file 'LICENCE'.)
= Version
$Id: bn.rb 11708 2007-02-12 23:01:19Z shyouhei $
=end
##
# Should we care what if somebody require this file directly?
#require 'openssl'
module OpenSSL
class BN
include Comparable
end # BN
end # OpenSSL
##
# Add double dispatch to Integer
#
class Integer
def to_bn
OpenSSL::BN::new(self)
end
end # Integer
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/lib/openssl/cipher.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/lib/openssl/cipher.rb | =begin
= $RCSfile$ -- Ruby-space predefined Cipher subclasses
= Info
'OpenSSL for Ruby 2' project
Copyright (C) 2002 Michal Rokos <m.rokos@sh.cvut.cz>
All rights reserved.
= Licence
This program is licenced under the same licence as Ruby.
(See the file 'LICENCE'.)
= Version
$Id: cipher.rb 12496 2007-06-08 15:02:04Z technorama $
=end
##
# Should we care what if somebody require this file directly?
#require 'openssl'
module OpenSSL
class Cipher
%w(AES CAST5 BF DES IDEA RC2 RC4 RC5).each{|name|
klass = Class.new(Cipher){
define_method(:initialize){|*args|
cipher_name = args.inject(name){|n, arg| "#{n}-#{arg}" }
super(cipher_name)
}
}
const_set(name, klass)
}
%w(128 192 256).each{|keylen|
klass = Class.new(Cipher){
define_method(:initialize){|mode|
mode ||= "CBC"
cipher_name = "AES-#{keylen}-#{mode}"
super(cipher_name)
}
}
const_set("AES#{keylen}", klass)
}
# Generate, set, and return a random key.
# You must call cipher.encrypt or cipher.decrypt before calling this method.
def random_key
str = OpenSSL::Random.random_bytes(self.key_len)
self.key = str
return str
end
# Generate, set, and return a random iv.
# You must call cipher.encrypt or cipher.decrypt before calling this method.
def random_iv
str = OpenSSL::Random.random_bytes(self.iv_len)
self.iv = str
return str
end
# This class is only provided for backwards compatibility. Use OpenSSL::Digest in the future.
class Cipher < Cipher
# add warning
end
end # Cipher
end # OpenSSL
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/lib/jopenssl/version.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/jruby-openssl-0.7/lib/jopenssl/version.rb | module Jopenssl
module Version
VERSION = "0.7"
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/activesupport.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/activesupport.rb | require 'active_support'
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support.rb | #--
# Copyright (c) 2005 David Heinemeier Hansson
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
module ActiveSupport
def self.load_all!
[Dependencies, Deprecation, Gzip, MessageVerifier, Multibyte, SecureRandom, TimeWithZone]
end
autoload :BacktraceCleaner, 'active_support/backtrace_cleaner'
autoload :Base64, 'active_support/base64'
autoload :BasicObject, 'active_support/basic_object'
autoload :BufferedLogger, 'active_support/buffered_logger'
autoload :Cache, 'active_support/cache'
autoload :Callbacks, 'active_support/callbacks'
autoload :Deprecation, 'active_support/deprecation'
autoload :Duration, 'active_support/duration'
autoload :Gzip, 'active_support/gzip'
autoload :Inflector, 'active_support/inflector'
autoload :Memoizable, 'active_support/memoizable'
autoload :MessageEncryptor, 'active_support/message_encryptor'
autoload :MessageVerifier, 'active_support/message_verifier'
autoload :Multibyte, 'active_support/multibyte'
autoload :OptionMerger, 'active_support/option_merger'
autoload :OrderedHash, 'active_support/ordered_hash'
autoload :OrderedOptions, 'active_support/ordered_options'
autoload :Rescuable, 'active_support/rescuable'
autoload :SecureRandom, 'active_support/secure_random'
autoload :StringInquirer, 'active_support/string_inquirer'
autoload :TimeWithZone, 'active_support/time_with_zone'
autoload :TimeZone, 'active_support/values/time_zone'
autoload :XmlMini, 'active_support/xml_mini'
end
require 'active_support/vendor'
require 'active_support/core_ext'
require 'active_support/dependencies'
require 'active_support/json'
I18n.load_path << "#{File.dirname(__FILE__)}/active_support/locale/en.yml"
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/ordered_hash.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/ordered_hash.rb | # OrderedHash is namespaced to prevent conflicts with other implementations
module ActiveSupport
# Hash is ordered in Ruby 1.9!
if RUBY_VERSION >= '1.9'
OrderedHash = ::Hash
else
class OrderedHash < Hash #:nodoc:
def initialize(*args, &block)
super
@keys = []
end
def self.[](*args)
ordered_hash = new
if (args.length == 1 && args.first.is_a?(Array))
args.first.each do |key_value_pair|
next unless (key_value_pair.is_a?(Array))
ordered_hash[key_value_pair[0]] = key_value_pair[1]
end
return ordered_hash
end
unless (args.size % 2 == 0)
raise ArgumentError.new("odd number of arguments for Hash")
end
args.each_with_index do |val, ind|
next if (ind % 2 != 0)
ordered_hash[val] = args[ind + 1]
end
ordered_hash
end
def initialize_copy(other)
super
# make a deep copy of keys
@keys = other.keys
end
def []=(key, value)
@keys << key if !has_key?(key)
super
end
def delete(key)
if has_key? key
index = @keys.index(key)
@keys.delete_at index
end
super
end
def delete_if
super
sync_keys!
self
end
def reject!
super
sync_keys!
self
end
def reject(&block)
dup.reject!(&block)
end
def keys
@keys.dup
end
def values
@keys.collect { |key| self[key] }
end
def to_hash
self
end
def to_a
@keys.map { |key| [ key, self[key] ] }
end
def each_key
@keys.each { |key| yield key }
end
def each_value
@keys.each { |key| yield self[key]}
end
def each
@keys.each {|key| yield [key, self[key]]}
end
alias_method :each_pair, :each
def clear
super
@keys.clear
self
end
def shift
k = @keys.first
v = delete(k)
[k, v]
end
def merge!(other_hash)
other_hash.each {|k,v| self[k] = v }
self
end
def merge(other_hash)
dup.merge!(other_hash)
end
def inspect
"#<OrderedHash #{super}>"
end
private
def sync_keys!
@keys.delete_if {|k| !has_key?(k)}
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/time_with_zone.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/time_with_zone.rb | require 'tzinfo'
module ActiveSupport
# A Time-like class that can represent a time in any time zone. Necessary because standard Ruby Time instances are
# limited to UTC and the system's <tt>ENV['TZ']</tt> zone.
#
# You shouldn't ever need to create a TimeWithZone instance directly via <tt>new</tt> -- instead, Rails provides the methods
# +local+, +parse+, +at+ and +now+ on TimeZone instances, and +in_time_zone+ on Time and DateTime instances, for a more
# user-friendly syntax. Examples:
#
# Time.zone = 'Eastern Time (US & Canada)' # => 'Eastern Time (US & Canada)'
# Time.zone.local(2007, 2, 10, 15, 30, 45) # => Sat, 10 Feb 2007 15:30:45 EST -05:00
# Time.zone.parse('2007-02-01 15:30:45') # => Sat, 10 Feb 2007 15:30:45 EST -05:00
# Time.zone.at(1170361845) # => Sat, 10 Feb 2007 15:30:45 EST -05:00
# Time.zone.now # => Sun, 18 May 2008 13:07:55 EDT -04:00
# Time.utc(2007, 2, 10, 20, 30, 45).in_time_zone # => Sat, 10 Feb 2007 15:30:45 EST -05:00
#
# See TimeZone and ActiveSupport::CoreExtensions::Time::Zones for further documentation for these methods.
#
# TimeWithZone instances implement the same API as Ruby Time instances, so that Time and TimeWithZone instances are interchangable. Examples:
#
# t = Time.zone.now # => Sun, 18 May 2008 13:27:25 EDT -04:00
# t.hour # => 13
# t.dst? # => true
# t.utc_offset # => -14400
# t.zone # => "EDT"
# t.to_s(:rfc822) # => "Sun, 18 May 2008 13:27:25 -0400"
# t + 1.day # => Mon, 19 May 2008 13:27:25 EDT -04:00
# t.beginning_of_year # => Tue, 01 Jan 2008 00:00:00 EST -05:00
# t > Time.utc(1999) # => true
# t.is_a?(Time) # => true
# t.is_a?(ActiveSupport::TimeWithZone) # => true
class TimeWithZone
include Comparable
attr_reader :time_zone
def initialize(utc_time, time_zone, local_time = nil, period = nil)
@utc, @time_zone, @time = utc_time, time_zone, local_time
@period = @utc ? period : get_period_and_ensure_valid_local_time
end
# Returns a Time or DateTime instance that represents the time in +time_zone+.
def time
@time ||= period.to_local(@utc)
end
# Returns a Time or DateTime instance that represents the time in UTC.
def utc
@utc ||= period.to_utc(@time)
end
alias_method :comparable_time, :utc
alias_method :getgm, :utc
alias_method :getutc, :utc
alias_method :gmtime, :utc
# Returns the underlying TZInfo::TimezonePeriod.
def period
@period ||= time_zone.period_for_utc(@utc)
end
# Returns the simultaneous time in <tt>Time.zone</tt>, or the specified zone.
def in_time_zone(new_zone = ::Time.zone)
return self if time_zone == new_zone
utc.in_time_zone(new_zone)
end
# Returns a <tt>Time.local()</tt> instance of the simultaneous time in your system's <tt>ENV['TZ']</tt> zone
def localtime
utc.getlocal
end
alias_method :getlocal, :localtime
def dst?
period.dst?
end
alias_method :isdst, :dst?
def utc?
time_zone.name == 'UTC'
end
alias_method :gmt?, :utc?
def utc_offset
period.utc_total_offset
end
alias_method :gmt_offset, :utc_offset
alias_method :gmtoff, :utc_offset
def formatted_offset(colon = true, alternate_utc_string = nil)
utc? && alternate_utc_string || utc_offset.to_utc_offset_s(colon)
end
# Time uses +zone+ to display the time zone abbreviation, so we're duck-typing it.
def zone
period.zone_identifier.to_s
end
def inspect
"#{time.strftime('%a, %d %b %Y %H:%M:%S')} #{zone} #{formatted_offset}"
end
def xmlschema(fraction_digits = 0)
fraction = if fraction_digits > 0
".%i" % time.usec.to_s[0, fraction_digits]
end
"#{time.strftime("%Y-%m-%dT%H:%M:%S")}#{fraction}#{formatted_offset(true, 'Z')}"
end
alias_method :iso8601, :xmlschema
# Coerces the date to a string for JSON encoding.
#
# ISO 8601 format is used if ActiveSupport::JSON::Encoding.use_standard_json_time_format is set.
#
# ==== Examples
#
# # With ActiveSupport::JSON::Encoding.use_standard_json_time_format = true
# Time.utc(2005,2,1,15,15,10).in_time_zone.to_json
# # => "2005-02-01T15:15:10Z"
#
# # With ActiveSupport::JSON::Encoding.use_standard_json_time_format = false
# Time.utc(2005,2,1,15,15,10).in_time_zone.to_json
# # => "2005/02/01 15:15:10 +0000"
def as_json(options = nil)
if ActiveSupport::JSON::Encoding.use_standard_json_time_format
xmlschema
else
%(#{time.strftime("%Y/%m/%d %H:%M:%S")} #{formatted_offset(false)})
end
end
def to_yaml(options = {})
if options.kind_of?(YAML::Emitter)
utc.to_yaml(options)
else
time.to_yaml(options).gsub('Z', formatted_offset(true, 'Z'))
end
end
def httpdate
utc.httpdate
end
def rfc2822
to_s(:rfc822)
end
alias_method :rfc822, :rfc2822
# <tt>:db</tt> format outputs time in UTC; all others output time in local.
# Uses TimeWithZone's +strftime+, so <tt>%Z</tt> and <tt>%z</tt> work correctly.
def to_s(format = :default)
return utc.to_s(format) if format == :db
if formatter = ::Time::DATE_FORMATS[format]
formatter.respond_to?(:call) ? formatter.call(self).to_s : strftime(formatter)
else
"#{time.strftime("%Y-%m-%d %H:%M:%S")} #{formatted_offset(false, 'UTC')}" # mimicking Ruby 1.9 Time#to_s format
end
end
alias_method :to_formatted_s, :to_s
# Replaces <tt>%Z</tt> and <tt>%z</tt> directives with +zone+ and +formatted_offset+, respectively, before passing to
# Time#strftime, so that zone information is correct
def strftime(format)
format = format.gsub('%Z', zone).gsub('%z', formatted_offset(false))
time.strftime(format)
end
# Use the time in UTC for comparisons.
def <=>(other)
utc <=> other
end
def between?(min, max)
utc.between?(min, max)
end
def past?
utc.past?
end
def today?
time.today?
end
def future?
utc.future?
end
def eql?(other)
utc == other
end
def +(other)
# If we're adding a Duration of variable length (i.e., years, months, days), move forward from #time,
# otherwise move forward from #utc, for accuracy when moving across DST boundaries
if duration_of_variable_length?(other)
method_missing(:+, other)
else
result = utc.acts_like?(:date) ? utc.since(other) : utc + other rescue utc.since(other)
result.in_time_zone(time_zone)
end
end
def -(other)
# If we're subtracting a Duration of variable length (i.e., years, months, days), move backwards from #time,
# otherwise move backwards #utc, for accuracy when moving across DST boundaries
if other.acts_like?(:time)
utc.to_f - other.to_f
elsif duration_of_variable_length?(other)
method_missing(:-, other)
else
result = utc.acts_like?(:date) ? utc.ago(other) : utc - other rescue utc.ago(other)
result.in_time_zone(time_zone)
end
end
def since(other)
# If we're adding a Duration of variable length (i.e., years, months, days), move forward from #time,
# otherwise move forward from #utc, for accuracy when moving across DST boundaries
if duration_of_variable_length?(other)
method_missing(:since, other)
else
utc.since(other).in_time_zone(time_zone)
end
end
def ago(other)
since(-other)
end
def advance(options)
# If we're advancing a value of variable length (i.e., years, weeks, months, days), advance from #time,
# otherwise advance from #utc, for accuracy when moving across DST boundaries
if options.values_at(:years, :weeks, :months, :days).any?
method_missing(:advance, options)
else
utc.advance(options).in_time_zone(time_zone)
end
end
%w(year mon month day mday wday yday hour min sec to_date).each do |method_name|
class_eval <<-EOV
def #{method_name} # def year
time.#{method_name} # time.year
end # end
EOV
end
def usec
time.respond_to?(:usec) ? time.usec : 0
end
def to_a
[time.sec, time.min, time.hour, time.day, time.mon, time.year, time.wday, time.yday, dst?, zone]
end
def to_f
utc.to_f
end
def to_i
utc.to_i
end
alias_method :hash, :to_i
alias_method :tv_sec, :to_i
# A TimeWithZone acts like a Time, so just return +self+.
def to_time
self
end
def to_datetime
utc.to_datetime.new_offset(Rational(utc_offset, 86_400))
end
# So that +self+ <tt>acts_like?(:time)</tt>.
def acts_like_time?
true
end
# Say we're a Time to thwart type checking.
def is_a?(klass)
klass == ::Time || super
end
alias_method :kind_of?, :is_a?
def freeze
period; utc; time # preload instance variables before freezing
super
end
def marshal_dump
[utc, time_zone.name, time]
end
def marshal_load(variables)
initialize(variables[0].utc, ::Time.__send__(:get_zone, variables[1]), variables[2].utc)
end
# Ensure proxy class responds to all methods that underlying time instance responds to.
def respond_to?(sym, include_priv = false)
# consistently respond false to acts_like?(:date), regardless of whether #time is a Time or DateTime
return false if sym.to_s == 'acts_like_date?'
super || time.respond_to?(sym, include_priv)
end
# Send the missing method to +time+ instance, and wrap result in a new TimeWithZone with the existing +time_zone+.
def method_missing(sym, *args, &block)
result = time.__send__(sym, *args, &block)
result.acts_like?(:time) ? self.class.new(nil, time_zone, result) : result
end
private
def get_period_and_ensure_valid_local_time
# we don't want a Time.local instance enforcing its own DST rules as well,
# so transfer time values to a utc constructor if necessary
@time = transfer_time_values_to_utc_constructor(@time) unless @time.utc?
begin
@time_zone.period_for_local(@time)
rescue ::TZInfo::PeriodNotFound
# time is in the "spring forward" hour gap, so we're moving the time forward one hour and trying again
@time += 1.hour
retry
end
end
def transfer_time_values_to_utc_constructor(time)
::Time.utc_time(time.year, time.month, time.day, time.hour, time.min, time.sec, time.respond_to?(:usec) ? time.usec : 0)
end
def duration_of_variable_length?(obj)
ActiveSupport::Duration === obj && obj.parts.any? {|p| [:years, :months, :days].include? p[0] }
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/ordered_options.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/ordered_options.rb | module ActiveSupport #:nodoc:
class OrderedOptions < OrderedHash #:nodoc:
def []=(key, value)
super(key.to_sym, value)
end
def [](key)
super(key.to_sym)
end
def method_missing(name, *args)
if name.to_s =~ /(.*)=$/
self[$1.to_sym] = args.first
else
self[name]
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/test_case.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/test_case.rb | require 'test/unit/testcase'
require 'active_support/testing/setup_and_teardown'
require 'active_support/testing/assertions'
require 'active_support/testing/deprecation'
require 'active_support/testing/declarative'
begin
gem 'mocha', ">= 0.9.7"
require 'mocha'
rescue LoadError
# Fake Mocha::ExpectationError so we can rescue it in #run. Bleh.
Object.const_set :Mocha, Module.new
Mocha.const_set :ExpectationError, Class.new(StandardError)
end
module ActiveSupport
class TestCase < ::Test::Unit::TestCase
if defined? MiniTest
Assertion = MiniTest::Assertion
alias_method :method_name, :name if method_defined? :name
alias_method :method_name, :__name__ if method_defined? :__name__
else
# TODO: Figure out how to get the Rails::BacktraceFilter into minitest/unit
if defined?(Rails) && ENV['BACKTRACE'].nil?
require 'rails/backtrace_cleaner'
Test::Unit::Util::BacktraceFilter.module_eval { include Rails::BacktraceFilterForTestUnit }
end
Assertion = Test::Unit::AssertionFailedError
require 'active_support/testing/default'
include ActiveSupport::Testing::Default
end
include ActiveSupport::Testing::SetupAndTeardown
include ActiveSupport::Testing::Assertions
include ActiveSupport::Testing::Deprecation
extend ActiveSupport::Testing::Declarative
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/deprecation.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/deprecation.rb | require 'yaml'
module ActiveSupport
module Deprecation #:nodoc:
mattr_accessor :debug
self.debug = false
# Choose the default warn behavior according to RAILS_ENV.
# Ignore deprecation warnings in production.
DEFAULT_BEHAVIORS = {
'test' => Proc.new { |message, callstack|
$stderr.puts(message)
$stderr.puts callstack.join("\n ") if debug
},
'development' => Proc.new { |message, callstack|
logger = defined?(Rails) ? Rails.logger : Logger.new($stderr)
logger.warn message
logger.debug callstack.join("\n ") if debug
}
}
class << self
def warn(message = nil, callstack = caller)
behavior.call(deprecation_message(callstack, message), callstack) if behavior && !silenced?
end
def default_behavior
if defined?(RAILS_ENV)
DEFAULT_BEHAVIORS[RAILS_ENV.to_s]
else
DEFAULT_BEHAVIORS['test']
end
end
# Have deprecations been silenced?
def silenced?
@silenced = false unless defined?(@silenced)
@silenced
end
# Silence deprecation warnings within the block.
def silence
old_silenced, @silenced = @silenced, true
yield
ensure
@silenced = old_silenced
end
attr_writer :silenced
private
def deprecation_message(callstack, message = nil)
message ||= "You are using deprecated behavior which will be removed from the next major or minor release."
"DEPRECATION WARNING: #{message}. #{deprecation_caller_message(callstack)}"
end
def deprecation_caller_message(callstack)
file, line, method = extract_callstack(callstack)
if file
if line && method
"(called from #{method} at #{file}:#{line})"
else
"(called from #{file}:#{line})"
end
end
end
def extract_callstack(callstack)
if md = callstack.first.match(/^(.+?):(\d+)(?::in `(.*?)')?/)
md.captures
else
callstack.first
end
end
end
# Behavior is a block that takes a message argument.
mattr_accessor :behavior
self.behavior = default_behavior
# Warnings are not silenced by default.
self.silenced = false
module ClassMethods #:nodoc:
# Declare that a method has been deprecated.
def deprecate(*method_names)
options = method_names.extract_options!
method_names = method_names + options.keys
method_names.each do |method_name|
alias_method_chain(method_name, :deprecation) do |target, punctuation|
class_eval(<<-EOS, __FILE__, __LINE__)
def #{target}_with_deprecation#{punctuation}(*args, &block) # def generate_secret_with_deprecation(*args, &block)
::ActiveSupport::Deprecation.warn( # ::ActiveSupport::Deprecation.warn(
self.class.deprecated_method_warning( # self.class.deprecated_method_warning(
:#{method_name}, # :generate_secret,
#{options[method_name].inspect}), # "You should use ActiveSupport::SecureRandom.hex(64)"),
caller # caller
) # )
send(:#{target}_without_deprecation#{punctuation}, *args, &block) # send(:generate_secret_without_deprecation, *args, &block)
end # end
EOS
end
end
end
def deprecated_method_warning(method_name, message=nil)
warning = "#{method_name} is deprecated and will be removed from Rails #{deprecation_horizon}"
case message
when Symbol then "#{warning} (use #{message} instead)"
when String then "#{warning} (#{message})"
else warning
end
end
def deprecation_horizon
'2.3'
end
end
class DeprecationProxy #:nodoc:
silence_warnings do
instance_methods.each { |m| undef_method m unless m =~ /^__/ }
end
# Don't give a deprecation warning on inspect since test/unit and error
# logs rely on it for diagnostics.
def inspect
target.inspect
end
private
def method_missing(called, *args, &block)
warn caller, called, args
target.__send__(called, *args, &block)
end
end
class DeprecatedObjectProxy < DeprecationProxy
def initialize(object, message)
@object = object
@message = message
end
private
def target
@object
end
def warn(callstack, called, args)
ActiveSupport::Deprecation.warn(@message, callstack)
end
end
# Stand-in for <tt>@request</tt>, <tt>@attributes</tt>, <tt>@params</tt>, etc.
# which emits deprecation warnings on any method call (except +inspect+).
class DeprecatedInstanceVariableProxy < DeprecationProxy #:nodoc:
def initialize(instance, method, var = "@#{method}")
@instance, @method, @var = instance, method, var
end
private
def target
@instance.__send__(@method)
end
def warn(callstack, called, args)
ActiveSupport::Deprecation.warn("#{@var} is deprecated! Call #{@method}.#{called} instead of #{@var}.#{called}. Args: #{args.inspect}", callstack)
end
end
class DeprecatedConstantProxy < DeprecationProxy #:nodoc:
def initialize(old_const, new_const)
@old_const = old_const
@new_const = new_const
end
def class
target.class
end
private
def target
@new_const.to_s.constantize
end
def warn(callstack, called, args)
ActiveSupport::Deprecation.warn("#{@old_const} is deprecated! Use #{@new_const} instead.", callstack)
end
end
end
end
class Module
include ActiveSupport::Deprecation::ClassMethods
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/vendor.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/vendor.rb | # Prefer gems to the bundled libs.
require 'rubygems'
begin
gem 'builder', '~> 2.1.2'
rescue Gem::LoadError
$:.unshift "#{File.dirname(__FILE__)}/vendor/builder-2.1.2"
end
require 'builder'
begin
gem 'memcache-client', '>= 1.7.4'
rescue Gem::LoadError
$:.unshift "#{File.dirname(__FILE__)}/vendor/memcache-client-1.7.4"
end
begin
gem 'tzinfo', '~> 0.3.12'
rescue Gem::LoadError
$:.unshift "#{File.dirname(__FILE__)}/vendor/tzinfo-0.3.12"
end
begin
gem 'i18n', '~> 0.1.3'
rescue Gem::LoadError
$:.unshift "#{File.dirname(__FILE__)}/vendor/i18n-0.1.3/lib"
require 'i18n'
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/version.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/version.rb | module ActiveSupport
module VERSION #:nodoc:
MAJOR = 2
MINOR = 3
TINY = 4
STRING = [MAJOR, MINOR, TINY].join('.')
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/rescuable.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/rescuable.rb | module ActiveSupport
# Rescuable module adds support for easier exception handling.
module Rescuable
def self.included(base) # :nodoc:
base.class_inheritable_accessor :rescue_handlers
base.rescue_handlers = []
base.extend(ClassMethods)
end
module ClassMethods
# Rescue exceptions raised in controller actions.
#
# <tt>rescue_from</tt> receives a series of exception classes or class
# names, and a trailing <tt>:with</tt> option with the name of a method
# or a Proc object to be called to handle them. Alternatively a block can
# be given.
#
# Handlers that take one argument will be called with the exception, so
# that the exception can be inspected when dealing with it.
#
# Handlers are inherited. They are searched from right to left, from
# bottom to top, and up the hierarchy. The handler of the first class for
# which <tt>exception.is_a?(klass)</tt> holds true is the one invoked, if
# any.
#
# class ApplicationController < ActionController::Base
# rescue_from User::NotAuthorized, :with => :deny_access # self defined exception
# rescue_from ActiveRecord::RecordInvalid, :with => :show_errors
#
# rescue_from 'MyAppError::Base' do |exception|
# render :xml => exception, :status => 500
# end
#
# protected
# def deny_access
# ...
# end
#
# def show_errors(exception)
# exception.record.new_record? ? ...
# end
# end
def rescue_from(*klasses, &block)
options = klasses.extract_options!
unless options.has_key?(:with)
if block_given?
options[:with] = block
else
raise ArgumentError, "Need a handler. Supply an options hash that has a :with key as the last argument."
end
end
klasses.each do |klass|
key = if klass.is_a?(Class) && klass <= Exception
klass.name
elsif klass.is_a?(String)
klass
else
raise ArgumentError, "#{klass} is neither an Exception nor a String"
end
# put the new handler at the end because the list is read in reverse
rescue_handlers << [key, options[:with]]
end
end
end
# Tries to rescue the exception by looking up and calling a registered handler.
def rescue_with_handler(exception)
if handler = handler_for_rescue(exception)
handler.arity != 0 ? handler.call(exception) : handler.call
true # don't rely on the return value of the handler
end
end
def handler_for_rescue(exception)
# We go from right to left because pairs are pushed onto rescue_handlers
# as rescue_from declarations are found.
_, rescuer = Array(rescue_handlers).reverse.detect do |klass_name, handler|
# The purpose of allowing strings in rescue_from is to support the
# declaration of handler associations for exception classes whose
# definition is yet unknown.
#
# Since this loop needs the constants it would be inconsistent to
# assume they should exist at this point. An early raised exception
# could trigger some other handler and the array could include
# precisely a string whose corresponding constant has not yet been
# seen. This is why we are tolerant to unknown constants.
#
# Note that this tolerance only matters if the exception was given as
# a string, otherwise a NameError will be raised by the interpreter
# itself when rescue_from CONSTANT is executed.
klass = self.class.const_get(klass_name) rescue nil
klass ||= klass_name.constantize rescue nil
exception.is_a?(klass) if klass
end
case rescuer
when Symbol
method(rescuer)
when Proc
rescuer.bind(self)
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/duration.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/duration.rb | require 'active_support/basic_object'
module ActiveSupport
# Provides accurate date and time measurements using Date#advance and
# Time#advance, respectively. It mainly supports the methods on Numeric,
# such as in this example:
#
# 1.month.ago # equivalent to Time.now.advance(:months => -1)
class Duration < BasicObject
attr_accessor :value, :parts
def initialize(value, parts) #:nodoc:
@value, @parts = value, parts
end
# Adds another Duration or a Numeric to this Duration. Numeric values
# are treated as seconds.
def +(other)
if Duration === other
Duration.new(value + other.value, @parts + other.parts)
else
Duration.new(value + other, @parts + [[:seconds, other]])
end
end
# Subtracts another Duration or a Numeric from this Duration. Numeric
# values are treated as seconds.
def -(other)
self + (-other)
end
def -@ #:nodoc:
Duration.new(-value, parts.map { |type,number| [type, -number] })
end
def is_a?(klass) #:nodoc:
klass == Duration || super
end
# Returns true if <tt>other</tt> is also a Duration instance with the
# same <tt>value</tt>, or if <tt>other == value</tt>.
def ==(other)
if Duration === other
other.value == value
else
other == value
end
end
def self.===(other) #:nodoc:
other.is_a?(Duration) rescue super
end
# Calculates a new Time or Date that is as far in the future
# as this Duration represents.
def since(time = ::Time.current)
sum(1, time)
end
alias :from_now :since
# Calculates a new Time or Date that is as far in the past
# as this Duration represents.
def ago(time = ::Time.current)
sum(-1, time)
end
alias :until :ago
def inspect #:nodoc:
consolidated = parts.inject(::Hash.new(0)) { |h,part| h[part.first] += part.last; h }
parts = [:years, :months, :days, :minutes, :seconds].map do |length|
n = consolidated[length]
"#{n} #{n == 1 ? length.to_s.singularize : length.to_s}" if n.nonzero?
end.compact
parts = ["0 seconds"] if parts.empty?
parts.to_sentence(:locale => :en)
end
protected
def sum(sign, time = ::Time.current) #:nodoc:
parts.inject(time) do |t,(type,number)|
if t.acts_like?(:time) || t.acts_like?(:date)
if type == :seconds
t.since(sign * number)
else
t.advance(type => sign * number)
end
else
raise ::ArgumentError, "expected a time or date, got #{time.inspect}"
end
end
end
private
def method_missing(method, *args, &block) #:nodoc:
value.send(method, *args)
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/core_ext.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/core_ext.rb | Dir[File.dirname(__FILE__) + "/core_ext/*.rb"].sort.each do |path|
filename = File.basename(path, '.rb')
require "active_support/core_ext/#{filename}"
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/xml_mini.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/xml_mini.rb | module ActiveSupport
# = XmlMini
#
# To use the much faster libxml parser:
# gem 'libxml-ruby', '=0.9.7'
# XmlMini.backend = 'LibXML'
module XmlMini
extend self
attr_reader :backend
delegate :parse, :to => :backend
def backend=(name)
if name.is_a?(Module)
@backend = name
else
require "active_support/xml_mini/#{name.to_s.downcase}.rb"
@backend = ActiveSupport.const_get("XmlMini_#{name}")
end
end
def with_backend(name)
old_backend, self.backend = backend, name
yield
ensure
self.backend = old_backend
end
end
XmlMini.backend = 'REXML'
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/message_verifier.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/message_verifier.rb | module ActiveSupport
# MessageVerifier makes it easy to generate and verify messages which are signed
# to prevent tampering.
#
# This is useful for cases like remember-me tokens and auto-unsubscribe links where the
# session store isn't suitable or available.
#
# Remember Me:
# cookies[:remember_me] = @verifier.generate([@user.id, 2.weeks.from_now])
#
# In the authentication filter:
#
# id, time = @verifier.verify(cookies[:remember_me])
# if time < Time.now
# self.current_user = User.find(id)
# end
#
class MessageVerifier
class InvalidSignature < StandardError; end
def initialize(secret, digest = 'SHA1')
@secret = secret
@digest = digest
end
def verify(signed_message)
data, digest = signed_message.split("--")
if secure_compare(digest, generate_digest(data))
Marshal.load(ActiveSupport::Base64.decode64(data))
else
raise InvalidSignature
end
end
def generate(value)
data = ActiveSupport::Base64.encode64s(Marshal.dump(value))
"#{data}--#{generate_digest(data)}"
end
private
# constant-time comparison algorithm to prevent timing attacks
def secure_compare(a, b)
if a.length == b.length
result = 0
for i in 0..(a.length - 1)
result |= a[i] ^ b[i]
end
result == 0
else
false
end
end
def generate_digest(data)
require 'openssl' unless defined?(OpenSSL)
OpenSSL::HMAC.hexdigest(OpenSSL::Digest::Digest.new(@digest), @secret, data)
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/inflector.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/inflector.rb | # encoding: utf-8
require 'singleton'
require 'iconv'
module ActiveSupport
# The Inflector transforms words from singular to plural, class names to table names, modularized class names to ones without,
# and class names to foreign keys. The default inflections for pluralization, singularization, and uncountable words are kept
# in inflections.rb.
#
# The Rails core team has stated patches for the inflections library will not be accepted
# in order to avoid breaking legacy applications which may be relying on errant inflections.
# If you discover an incorrect inflection and require it for your application, you'll need
# to correct it yourself (explained below).
module Inflector
extend self
# A singleton instance of this class is yielded by Inflector.inflections, which can then be used to specify additional
# inflection rules. Examples:
#
# ActiveSupport::Inflector.inflections do |inflect|
# inflect.plural /^(ox)$/i, '\1\2en'
# inflect.singular /^(ox)en/i, '\1'
#
# inflect.irregular 'octopus', 'octopi'
#
# inflect.uncountable "equipment"
# end
#
# New rules are added at the top. So in the example above, the irregular rule for octopus will now be the first of the
# pluralization and singularization rules that is runs. This guarantees that your rules run before any of the rules that may
# already have been loaded.
class Inflections
include Singleton
attr_reader :plurals, :singulars, :uncountables, :humans
def initialize
@plurals, @singulars, @uncountables, @humans = [], [], [], []
end
# Specifies a new pluralization rule and its replacement. The rule can either be a string or a regular expression.
# The replacement should always be a string that may include references to the matched data from the rule.
def plural(rule, replacement)
@uncountables.delete(rule) if rule.is_a?(String)
@uncountables.delete(replacement)
@plurals.insert(0, [rule, replacement])
end
# Specifies a new singularization rule and its replacement. The rule can either be a string or a regular expression.
# The replacement should always be a string that may include references to the matched data from the rule.
def singular(rule, replacement)
@uncountables.delete(rule) if rule.is_a?(String)
@uncountables.delete(replacement)
@singulars.insert(0, [rule, replacement])
end
# Specifies a new irregular that applies to both pluralization and singularization at the same time. This can only be used
# for strings, not regular expressions. You simply pass the irregular in singular and plural form.
#
# Examples:
# irregular 'octopus', 'octopi'
# irregular 'person', 'people'
def irregular(singular, plural)
@uncountables.delete(singular)
@uncountables.delete(plural)
if singular[0,1].upcase == plural[0,1].upcase
plural(Regexp.new("(#{singular[0,1]})#{singular[1..-1]}$", "i"), '\1' + plural[1..-1])
singular(Regexp.new("(#{plural[0,1]})#{plural[1..-1]}$", "i"), '\1' + singular[1..-1])
else
plural(Regexp.new("#{singular[0,1].upcase}(?i)#{singular[1..-1]}$"), plural[0,1].upcase + plural[1..-1])
plural(Regexp.new("#{singular[0,1].downcase}(?i)#{singular[1..-1]}$"), plural[0,1].downcase + plural[1..-1])
singular(Regexp.new("#{plural[0,1].upcase}(?i)#{plural[1..-1]}$"), singular[0,1].upcase + singular[1..-1])
singular(Regexp.new("#{plural[0,1].downcase}(?i)#{plural[1..-1]}$"), singular[0,1].downcase + singular[1..-1])
end
end
# Add uncountable words that shouldn't be attempted inflected.
#
# Examples:
# uncountable "money"
# uncountable "money", "information"
# uncountable %w( money information rice )
def uncountable(*words)
(@uncountables << words).flatten!
end
# Specifies a humanized form of a string by a regular expression rule or by a string mapping.
# When using a regular expression based replacement, the normal humanize formatting is called after the replacement.
# When a string is used, the human form should be specified as desired (example: 'The name', not 'the_name')
#
# Examples:
# human /_cnt$/i, '\1_count'
# human "legacy_col_person_name", "Name"
def human(rule, replacement)
@humans.insert(0, [rule, replacement])
end
# Clears the loaded inflections within a given scope (default is <tt>:all</tt>).
# Give the scope as a symbol of the inflection type, the options are: <tt>:plurals</tt>,
# <tt>:singulars</tt>, <tt>:uncountables</tt>, <tt>:humans</tt>.
#
# Examples:
# clear :all
# clear :plurals
def clear(scope = :all)
case scope
when :all
@plurals, @singulars, @uncountables = [], [], []
else
instance_variable_set "@#{scope}", []
end
end
end
# Yields a singleton instance of Inflector::Inflections so you can specify additional
# inflector rules.
#
# Example:
# ActiveSupport::Inflector.inflections do |inflect|
# inflect.uncountable "rails"
# end
def inflections
if block_given?
yield Inflections.instance
else
Inflections.instance
end
end
# Returns the plural form of the word in the string.
#
# Examples:
# "post".pluralize # => "posts"
# "octopus".pluralize # => "octopi"
# "sheep".pluralize # => "sheep"
# "words".pluralize # => "words"
# "CamelOctopus".pluralize # => "CamelOctopi"
def pluralize(word)
result = word.to_s.dup
if word.empty? || inflections.uncountables.include?(result.downcase)
result
else
inflections.plurals.each { |(rule, replacement)| break if result.gsub!(rule, replacement) }
result
end
end
# The reverse of +pluralize+, returns the singular form of a word in a string.
#
# Examples:
# "posts".singularize # => "post"
# "octopi".singularize # => "octopus"
# "sheep".singluarize # => "sheep"
# "word".singularize # => "word"
# "CamelOctopi".singularize # => "CamelOctopus"
def singularize(word)
result = word.to_s.dup
if inflections.uncountables.include?(result.downcase)
result
else
inflections.singulars.each { |(rule, replacement)| break if result.gsub!(rule, replacement) }
result
end
end
# By default, +camelize+ converts strings to UpperCamelCase. If the argument to +camelize+
# is set to <tt>:lower</tt> then +camelize+ produces lowerCamelCase.
#
# +camelize+ will also convert '/' to '::' which is useful for converting paths to namespaces.
#
# Examples:
# "active_record".camelize # => "ActiveRecord"
# "active_record".camelize(:lower) # => "activeRecord"
# "active_record/errors".camelize # => "ActiveRecord::Errors"
# "active_record/errors".camelize(:lower) # => "activeRecord::Errors"
def camelize(lower_case_and_underscored_word, first_letter_in_uppercase = true)
if first_letter_in_uppercase
lower_case_and_underscored_word.to_s.gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase }
else
lower_case_and_underscored_word.first.downcase + camelize(lower_case_and_underscored_word)[1..-1]
end
end
# Capitalizes all the words and replaces some characters in the string to create
# a nicer looking title. +titleize+ is meant for creating pretty output. It is not
# used in the Rails internals.
#
# +titleize+ is also aliased as as +titlecase+.
#
# Examples:
# "man from the boondocks".titleize # => "Man From The Boondocks"
# "x-men: the last stand".titleize # => "X Men: The Last Stand"
def titleize(word)
humanize(underscore(word)).gsub(/\b('?[a-z])/) { $1.capitalize }
end
# The reverse of +camelize+. Makes an underscored, lowercase form from the expression in the string.
#
# Changes '::' to '/' to convert namespaces to paths.
#
# Examples:
# "ActiveRecord".underscore # => "active_record"
# "ActiveRecord::Errors".underscore # => active_record/errors
def underscore(camel_cased_word)
camel_cased_word.to_s.gsub(/::/, '/').
gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
gsub(/([a-z\d])([A-Z])/,'\1_\2').
tr("-", "_").
downcase
end
# Replaces underscores with dashes in the string.
#
# Example:
# "puni_puni" # => "puni-puni"
def dasherize(underscored_word)
underscored_word.gsub(/_/, '-')
end
# Capitalizes the first word and turns underscores into spaces and strips a
# trailing "_id", if any. Like +titleize+, this is meant for creating pretty output.
#
# Examples:
# "employee_salary" # => "Employee salary"
# "author_id" # => "Author"
def humanize(lower_case_and_underscored_word)
result = lower_case_and_underscored_word.to_s.dup
inflections.humans.each { |(rule, replacement)| break if result.gsub!(rule, replacement) }
result.gsub(/_id$/, "").gsub(/_/, " ").capitalize
end
# Removes the module part from the expression in the string.
#
# Examples:
# "ActiveRecord::CoreExtensions::String::Inflections".demodulize # => "Inflections"
# "Inflections".demodulize # => "Inflections"
def demodulize(class_name_in_module)
class_name_in_module.to_s.gsub(/^.*::/, '')
end
# Replaces special characters in a string so that it may be used as part of a 'pretty' URL.
#
# ==== Examples
#
# class Person
# def to_param
# "#{id}-#{name.parameterize}"
# end
# end
#
# @person = Person.find(1)
# # => #<Person id: 1, name: "Donald E. Knuth">
#
# <%= link_to(@person.name, person_path(@person)) %>
# # => <a href="/person/1-donald-e-knuth">Donald E. Knuth</a>
def parameterize(string, sep = '-')
# replace accented chars with ther ascii equivalents
parameterized_string = transliterate(string)
# Turn unwanted chars into the seperator
parameterized_string.gsub!(/[^a-z0-9\-_\+]+/i, sep)
unless sep.blank?
re_sep = Regexp.escape(sep)
# No more than one of the separator in a row.
parameterized_string.gsub!(/#{re_sep}{2,}/, sep)
# Remove leading/trailing separator.
parameterized_string.gsub!(/^#{re_sep}|#{re_sep}$/i, '')
end
parameterized_string.downcase
end
# Replaces accented characters with their ascii equivalents.
def transliterate(string)
Iconv.iconv('ascii//ignore//translit', 'utf-8', string).to_s
end
if RUBY_VERSION >= '1.9'
undef_method :transliterate
def transliterate(string)
warn "Ruby 1.9 doesn't support Unicode normalization yet"
string.dup
end
# The iconv transliteration code doesn't function correctly
# on some platforms, but it's very fast where it does function.
elsif "foo" != (Inflector.transliterate("föö") rescue nil)
undef_method :transliterate
def transliterate(string)
string.mb_chars.normalize(:kd). # Decompose accented characters
gsub(/[^\x00-\x7F]+/, '') # Remove anything non-ASCII entirely (e.g. diacritics).
end
end
# Create the name of a table like Rails does for models to table names. This method
# uses the +pluralize+ method on the last word in the string.
#
# Examples
# "RawScaledScorer".tableize # => "raw_scaled_scorers"
# "egg_and_ham".tableize # => "egg_and_hams"
# "fancyCategory".tableize # => "fancy_categories"
def tableize(class_name)
pluralize(underscore(class_name))
end
# Create a class name from a plural table name like Rails does for table names to models.
# Note that this returns a string and not a Class. (To convert to an actual class
# follow +classify+ with +constantize+.)
#
# Examples:
# "egg_and_hams".classify # => "EggAndHam"
# "posts".classify # => "Post"
#
# Singular names are not handled correctly:
# "business".classify # => "Busines"
def classify(table_name)
# strip out any leading schema name
camelize(singularize(table_name.to_s.sub(/.*\./, '')))
end
# Creates a foreign key name from a class name.
# +separate_class_name_and_id_with_underscore+ sets whether
# the method should put '_' between the name and 'id'.
#
# Examples:
# "Message".foreign_key # => "message_id"
# "Message".foreign_key(false) # => "messageid"
# "Admin::Post".foreign_key # => "post_id"
def foreign_key(class_name, separate_class_name_and_id_with_underscore = true)
underscore(demodulize(class_name)) + (separate_class_name_and_id_with_underscore ? "_id" : "id")
end
# Ruby 1.9 introduces an inherit argument for Module#const_get and
# #const_defined? and changes their default behavior.
if Module.method(:const_get).arity == 1
# Tries to find a constant with the name specified in the argument string:
#
# "Module".constantize # => Module
# "Test::Unit".constantize # => Test::Unit
#
# The name is assumed to be the one of a top-level constant, no matter whether
# it starts with "::" or not. No lexical context is taken into account:
#
# C = 'outside'
# module M
# C = 'inside'
# C # => 'inside'
# "C".constantize # => 'outside', same as ::C
# end
#
# NameError is raised when the name is not in CamelCase or the constant is
# unknown.
def constantize(camel_cased_word)
names = camel_cased_word.split('::')
names.shift if names.empty? || names.first.empty?
constant = Object
names.each do |name|
constant = constant.const_defined?(name) ? constant.const_get(name) : constant.const_missing(name)
end
constant
end
else
def constantize(camel_cased_word) #:nodoc:
names = camel_cased_word.split('::')
names.shift if names.empty? || names.first.empty?
constant = Object
names.each do |name|
constant = constant.const_get(name, false) || constant.const_missing(name)
end
constant
end
end
# Turns a number into an ordinal string used to denote the position in an
# ordered sequence such as 1st, 2nd, 3rd, 4th.
#
# Examples:
# ordinalize(1) # => "1st"
# ordinalize(2) # => "2nd"
# ordinalize(1002) # => "1002nd"
# ordinalize(1003) # => "1003rd"
def ordinalize(number)
if (11..13).include?(number.to_i % 100)
"#{number}th"
else
case number.to_i % 10
when 1; "#{number}st"
when 2; "#{number}nd"
when 3; "#{number}rd"
else "#{number}th"
end
end
end
end
end
# in case active_support/inflector is required without the rest of active_support
require 'active_support/inflections'
require 'active_support/core_ext/string/inflections'
unless String.included_modules.include?(ActiveSupport::CoreExtensions::String::Inflections)
String.send :include, ActiveSupport::CoreExtensions::String::Inflections
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/callbacks.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/callbacks.rb | module ActiveSupport
# Callbacks are hooks into the lifecycle of an object that allow you to trigger logic
# before or after an alteration of the object state.
#
# Mixing in this module allows you to define callbacks in your class.
#
# Example:
# class Storage
# include ActiveSupport::Callbacks
#
# define_callbacks :before_save, :after_save
# end
#
# class ConfigStorage < Storage
# before_save :saving_message
# def saving_message
# puts "saving..."
# end
#
# after_save do |object|
# puts "saved"
# end
#
# def save
# run_callbacks(:before_save)
# puts "- save"
# run_callbacks(:after_save)
# end
# end
#
# config = ConfigStorage.new
# config.save
#
# Output:
# saving...
# - save
# saved
#
# Callbacks from parent classes are inherited.
#
# Example:
# class Storage
# include ActiveSupport::Callbacks
#
# define_callbacks :before_save, :after_save
#
# before_save :prepare
# def prepare
# puts "preparing save"
# end
# end
#
# class ConfigStorage < Storage
# before_save :saving_message
# def saving_message
# puts "saving..."
# end
#
# after_save do |object|
# puts "saved"
# end
#
# def save
# run_callbacks(:before_save)
# puts "- save"
# run_callbacks(:after_save)
# end
# end
#
# config = ConfigStorage.new
# config.save
#
# Output:
# preparing save
# saving...
# - save
# saved
module Callbacks
class CallbackChain < Array
def self.build(kind, *methods, &block)
methods, options = extract_options(*methods, &block)
methods.map! { |method| Callback.new(kind, method, options) }
new(methods)
end
def run(object, options = {}, &terminator)
enumerator = options[:enumerator] || :each
unless block_given?
send(enumerator) { |callback| callback.call(object) }
else
send(enumerator) do |callback|
result = callback.call(object)
break result if terminator.call(result, object)
end
end
end
# TODO: Decompose into more Array like behavior
def replace_or_append!(chain)
if index = index(chain)
self[index] = chain
else
self << chain
end
self
end
def find(callback, &block)
select { |c| c == callback && (!block_given? || yield(c)) }.first
end
def delete(callback)
super(callback.is_a?(Callback) ? callback : find(callback))
end
private
def self.extract_options(*methods, &block)
methods.flatten!
options = methods.extract_options!
methods << block if block_given?
return methods, options
end
def extract_options(*methods, &block)
self.class.extract_options(*methods, &block)
end
end
class Callback
attr_reader :kind, :method, :identifier, :options
def initialize(kind, method, options = {})
@kind = kind
@method = method
@identifier = options[:identifier]
@options = options
end
def ==(other)
case other
when Callback
(self.identifier && self.identifier == other.identifier) || self.method == other.method
else
(self.identifier && self.identifier == other) || self.method == other
end
end
def eql?(other)
self == other
end
def dup
self.class.new(@kind, @method, @options.dup)
end
def hash
if @identifier
@identifier.hash
else
@method.hash
end
end
def call(*args, &block)
evaluate_method(method, *args, &block) if should_run_callback?(*args)
rescue LocalJumpError
raise ArgumentError,
"Cannot yield from a Proc type filter. The Proc must take two " +
"arguments and execute #call on the second argument."
end
private
def evaluate_method(method, *args, &block)
case method
when Symbol
object = args.shift
object.send(method, *args, &block)
when String
eval(method, args.first.instance_eval { binding })
when Proc, Method
method.call(*args, &block)
else
if method.respond_to?(kind)
method.send(kind, *args, &block)
else
raise ArgumentError,
"Callbacks must be a symbol denoting the method to call, a string to be evaluated, " +
"a block to be invoked, or an object responding to the callback method."
end
end
end
def should_run_callback?(*args)
[options[:if]].flatten.compact.all? { |a| evaluate_method(a, *args) } &&
![options[:unless]].flatten.compact.any? { |a| evaluate_method(a, *args) }
end
end
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def define_callbacks(*callbacks)
callbacks.each do |callback|
class_eval <<-"end_eval"
def self.#{callback}(*methods, &block) # def self.before_save(*methods, &block)
callbacks = CallbackChain.build(:#{callback}, *methods, &block) # callbacks = CallbackChain.build(:before_save, *methods, &block)
@#{callback}_callbacks ||= CallbackChain.new # @before_save_callbacks ||= CallbackChain.new
@#{callback}_callbacks.concat callbacks # @before_save_callbacks.concat callbacks
end # end
#
def self.#{callback}_callback_chain # def self.before_save_callback_chain
@#{callback}_callbacks ||= CallbackChain.new # @before_save_callbacks ||= CallbackChain.new
#
if superclass.respond_to?(:#{callback}_callback_chain) # if superclass.respond_to?(:before_save_callback_chain)
CallbackChain.new( # CallbackChain.new(
superclass.#{callback}_callback_chain + # superclass.before_save_callback_chain +
@#{callback}_callbacks # @before_save_callbacks
) # )
else # else
@#{callback}_callbacks # @before_save_callbacks
end # end
end # end
end_eval
end
end
end
# Runs all the callbacks defined for the given options.
#
# If a block is given it will be called after each callback receiving as arguments:
#
# * the result from the callback
# * the object which has the callback
#
# If the result from the block evaluates to false, the callback chain is stopped.
#
# Example:
# class Storage
# include ActiveSupport::Callbacks
#
# define_callbacks :before_save, :after_save
# end
#
# class ConfigStorage < Storage
# before_save :pass
# before_save :pass
# before_save :stop
# before_save :pass
#
# def pass
# puts "pass"
# end
#
# def stop
# puts "stop"
# return false
# end
#
# def save
# result = run_callbacks(:before_save) { |result, object| result == false }
# puts "- save" if result
# end
# end
#
# config = ConfigStorage.new
# config.save
#
# Output:
# pass
# pass
# stop
def run_callbacks(kind, options = {}, &block)
self.class.send("#{kind}_callback_chain").run(self, options, &block)
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/message_encryptor.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/message_encryptor.rb | require 'openssl'
module ActiveSupport
# MessageEncryptor is a simple way to encrypt values which get stored somewhere
# you don't trust.
#
# The cipher text and initialization vector are base64 encoded and returned to you.
#
# This can be used in situations similar to the MessageVerifier, but where you don't
# want users to be able to determine the value of the payload.
class MessageEncryptor
class InvalidMessage < StandardError; end
OpenSSLCipherError = OpenSSL::Cipher.const_defined?(:CipherError) ? OpenSSL::Cipher::CipherError : OpenSSL::CipherError
def initialize(secret, cipher = 'aes-256-cbc')
@secret = secret
@cipher = cipher
end
def encrypt(value)
cipher = new_cipher
# Rely on OpenSSL for the initialization vector
iv = cipher.random_iv
cipher.encrypt
cipher.key = @secret
cipher.iv = iv
encrypted_data = cipher.update(Marshal.dump(value))
encrypted_data << cipher.final
[encrypted_data, iv].map {|v| ActiveSupport::Base64.encode64s(v)}.join("--")
end
def decrypt(encrypted_message)
cipher = new_cipher
encrypted_data, iv = encrypted_message.split("--").map {|v| ActiveSupport::Base64.decode64(v)}
cipher.decrypt
cipher.key = @secret
cipher.iv = iv
decrypted_data = cipher.update(encrypted_data)
decrypted_data << cipher.final
Marshal.load(decrypted_data)
rescue OpenSSLCipherError, TypeError
raise InvalidMessage
end
def encrypt_and_sign(value)
verifier.generate(encrypt(value))
end
def decrypt_and_verify(value)
decrypt(verifier.verify(value))
end
private
def new_cipher
OpenSSL::Cipher::Cipher.new(@cipher)
end
def verifier
MessageVerifier.new(@secret)
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/json.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/json.rb | require 'active_support/json/decoding'
require 'active_support/json/encoding'
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/base64.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/base64.rb | begin
require 'base64'
rescue LoadError
end
module ActiveSupport
if defined? ::Base64
Base64 = ::Base64
else
# Base64 provides utility methods for encoding and de-coding binary data
# using a base 64 representation. A base 64 representation of binary data
# consists entirely of printable US-ASCII characters. The Base64 module
# is included in Ruby 1.8, but has been removed in Ruby 1.9.
module Base64
# Encodes a string to its base 64 representation. Each 60 characters of
# output is separated by a newline character.
#
# ActiveSupport::Base64.encode64("Original unencoded string")
# # => "T3JpZ2luYWwgdW5lbmNvZGVkIHN0cmluZw==\n"
def self.encode64(data)
[data].pack("m")
end
# Decodes a base 64 encoded string to its original representation.
#
# ActiveSupport::Base64.decode64("T3JpZ2luYWwgdW5lbmNvZGVkIHN0cmluZw==")
# # => "Original unencoded string"
def self.decode64(data)
data.unpack("m").first
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/buffered_logger.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/buffered_logger.rb | module ActiveSupport
# Inspired by the buffered logger idea by Ezra
class BufferedLogger
module Severity
DEBUG = 0
INFO = 1
WARN = 2
ERROR = 3
FATAL = 4
UNKNOWN = 5
end
include Severity
MAX_BUFFER_SIZE = 1000
##
# :singleton-method:
# Set to false to disable the silencer
cattr_accessor :silencer
self.silencer = true
# Silences the logger for the duration of the block.
def silence(temporary_level = ERROR)
if silencer
begin
old_logger_level, self.level = level, temporary_level
yield self
ensure
self.level = old_logger_level
end
else
yield self
end
end
attr_accessor :level
attr_reader :auto_flushing
def initialize(log, level = DEBUG)
@level = level
@buffer = {}
@auto_flushing = 1
@guard = Mutex.new
if log.respond_to?(:write)
@log = log
elsif File.exist?(log)
@log = open(log, (File::WRONLY | File::APPEND))
@log.sync = true
else
FileUtils.mkdir_p(File.dirname(log))
@log = open(log, (File::WRONLY | File::APPEND | File::CREAT))
@log.sync = true
@log.write("# Logfile created on %s" % [Time.now.to_s])
end
end
def add(severity, message = nil, progname = nil, &block)
return if @level > severity
message = (message || (block && block.call) || progname).to_s
# If a newline is necessary then create a new message ending with a newline.
# Ensures that the original message is not mutated.
message = "#{message}\n" unless message[-1] == ?\n
buffer << message
auto_flush
message
end
for severity in Severity.constants
class_eval <<-EOT, __FILE__, __LINE__
def #{severity.downcase}(message = nil, progname = nil, &block) # def debug(message = nil, progname = nil, &block)
add(#{severity}, message, progname, &block) # add(DEBUG, message, progname, &block)
end # end
#
def #{severity.downcase}? # def debug?
#{severity} >= @level # DEBUG >= @level
end # end
EOT
end
# Set the auto-flush period. Set to true to flush after every log message,
# to an integer to flush every N messages, or to false, nil, or zero to
# never auto-flush. If you turn auto-flushing off, be sure to regularly
# flush the log yourself -- it will eat up memory until you do.
def auto_flushing=(period)
@auto_flushing =
case period
when true; 1
when false, nil, 0; MAX_BUFFER_SIZE
when Integer; period
else raise ArgumentError, "Unrecognized auto_flushing period: #{period.inspect}"
end
end
def flush
@guard.synchronize do
unless buffer.empty?
old_buffer = buffer
@log.write(old_buffer.join)
end
# Important to do this even if buffer was empty or else @buffer will
# accumulate empty arrays for each request where nothing was logged.
clear_buffer
end
end
def close
flush
@log.close if @log.respond_to?(:close)
@log = nil
end
protected
def auto_flush
flush if buffer.size >= @auto_flushing
end
def buffer
@buffer[Thread.current] ||= []
end
def clear_buffer
@buffer.delete(Thread.current)
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/inflections.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/inflections.rb | module ActiveSupport
Inflector.inflections do |inflect|
inflect.plural(/$/, 's')
inflect.plural(/s$/i, 's')
inflect.plural(/(ax|test)is$/i, '\1es')
inflect.plural(/(octop|vir)us$/i, '\1i')
inflect.plural(/(alias|status)$/i, '\1es')
inflect.plural(/(bu)s$/i, '\1ses')
inflect.plural(/(buffal|tomat)o$/i, '\1oes')
inflect.plural(/([ti])um$/i, '\1a')
inflect.plural(/sis$/i, 'ses')
inflect.plural(/(?:([^f])fe|([lr])f)$/i, '\1\2ves')
inflect.plural(/(hive)$/i, '\1s')
inflect.plural(/([^aeiouy]|qu)y$/i, '\1ies')
inflect.plural(/(x|ch|ss|sh)$/i, '\1es')
inflect.plural(/(matr|vert|ind)(?:ix|ex)$/i, '\1ices')
inflect.plural(/([m|l])ouse$/i, '\1ice')
inflect.plural(/^(ox)$/i, '\1en')
inflect.plural(/(quiz)$/i, '\1zes')
inflect.singular(/s$/i, '')
inflect.singular(/(n)ews$/i, '\1ews')
inflect.singular(/([ti])a$/i, '\1um')
inflect.singular(/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$/i, '\1\2sis')
inflect.singular(/(^analy)ses$/i, '\1sis')
inflect.singular(/([^f])ves$/i, '\1fe')
inflect.singular(/(hive)s$/i, '\1')
inflect.singular(/(tive)s$/i, '\1')
inflect.singular(/([lr])ves$/i, '\1f')
inflect.singular(/([^aeiouy]|qu)ies$/i, '\1y')
inflect.singular(/(s)eries$/i, '\1eries')
inflect.singular(/(m)ovies$/i, '\1ovie')
inflect.singular(/(x|ch|ss|sh)es$/i, '\1')
inflect.singular(/([m|l])ice$/i, '\1ouse')
inflect.singular(/(bus)es$/i, '\1')
inflect.singular(/(o)es$/i, '\1')
inflect.singular(/(shoe)s$/i, '\1')
inflect.singular(/(cris|ax|test)es$/i, '\1is')
inflect.singular(/(octop|vir)i$/i, '\1us')
inflect.singular(/(alias|status)es$/i, '\1')
inflect.singular(/^(ox)en/i, '\1')
inflect.singular(/(vert|ind)ices$/i, '\1ex')
inflect.singular(/(matr)ices$/i, '\1ix')
inflect.singular(/(quiz)zes$/i, '\1')
inflect.singular(/(database)s$/i, '\1')
inflect.irregular('person', 'people')
inflect.irregular('man', 'men')
inflect.irregular('child', 'children')
inflect.irregular('sex', 'sexes')
inflect.irregular('move', 'moves')
inflect.irregular('cow', 'kine')
inflect.uncountable(%w(equipment information rice money species series fish sheep))
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/gzip.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/gzip.rb | require 'zlib'
require 'stringio'
module ActiveSupport
# A convenient wrapper for the zlib standard library that allows compression/decompression of strings with gzip.
module Gzip
class Stream < StringIO
def close; rewind; end
end
# Decompresses a gzipped string.
def self.decompress(source)
Zlib::GzipReader.new(StringIO.new(source)).read
end
# Compresses a string using gzip.
def self.compress(source)
output = Stream.new
gz = Zlib::GzipWriter.new(output)
gz.write(source)
gz.close
output.string
end
end
end | ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/memoizable.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/memoizable.rb | module ActiveSupport
module Memoizable
def self.memoized_ivar_for(symbol)
"@_memoized_#{symbol.to_s.sub(/\?\Z/, '_query').sub(/!\Z/, '_bang')}".to_sym
end
module InstanceMethods
def self.included(base)
base.class_eval do
unless base.method_defined?(:freeze_without_memoizable)
alias_method_chain :freeze, :memoizable
end
end
end
def freeze_with_memoizable
memoize_all unless frozen?
freeze_without_memoizable
end
def memoize_all
prime_cache ".*"
end
def unmemoize_all
flush_cache ".*"
end
def prime_cache(*syms)
syms.each do |sym|
methods.each do |m|
if m.to_s =~ /^_unmemoized_(#{sym})/
if method(m).arity == 0
__send__($1)
else
ivar = ActiveSupport::Memoizable.memoized_ivar_for($1)
instance_variable_set(ivar, {})
end
end
end
end
end
def flush_cache(*syms, &block)
syms.each do |sym|
(methods + private_methods + protected_methods).each do |m|
if m.to_s =~ /^_unmemoized_(#{sym})/
ivar = ActiveSupport::Memoizable.memoized_ivar_for($1)
instance_variable_get(ivar).clear if instance_variable_defined?(ivar)
end
end
end
end
end
def memoize(*symbols)
symbols.each do |symbol|
original_method = :"_unmemoized_#{symbol}"
memoized_ivar = ActiveSupport::Memoizable.memoized_ivar_for(symbol)
class_eval <<-EOS, __FILE__, __LINE__
include InstanceMethods # include InstanceMethods
#
if method_defined?(:#{original_method}) # if method_defined?(:_unmemoized_mime_type)
raise "Already memoized #{symbol}" # raise "Already memoized mime_type"
end # end
alias #{original_method} #{symbol} # alias _unmemoized_mime_type mime_type
#
if instance_method(:#{symbol}).arity == 0 # if instance_method(:mime_type).arity == 0
def #{symbol}(reload = false) # def mime_type(reload = false)
if reload || !defined?(#{memoized_ivar}) || #{memoized_ivar}.empty? # if reload || !defined?(@_memoized_mime_type) || @_memoized_mime_type.empty?
#{memoized_ivar} = [#{original_method}.freeze] # @_memoized_mime_type = [_unmemoized_mime_type.freeze]
end # end
#{memoized_ivar}[0] # @_memoized_mime_type[0]
end # end
else # else
def #{symbol}(*args) # def mime_type(*args)
#{memoized_ivar} ||= {} unless frozen? # @_memoized_mime_type ||= {} unless frozen?
reload = args.pop if args.last == true || args.last == :reload # reload = args.pop if args.last == true || args.last == :reload
#
if defined?(#{memoized_ivar}) && #{memoized_ivar} # if defined?(@_memoized_mime_type) && @_memoized_mime_type
if !reload && #{memoized_ivar}.has_key?(args) # if !reload && @_memoized_mime_type.has_key?(args)
#{memoized_ivar}[args] # @_memoized_mime_type[args]
elsif #{memoized_ivar} # elsif @_memoized_mime_type
#{memoized_ivar}[args] = #{original_method}(*args).freeze # @_memoized_mime_type[args] = _unmemoized_mime_type(*args).freeze
end # end
else # else
#{original_method}(*args) # _unmemoized_mime_type(*args)
end # end
end # end
end # end
#
if private_method_defined?(#{original_method.inspect}) # if private_method_defined?(:_unmemoized_mime_type)
private #{symbol.inspect} # private :mime_type
end # end
EOS
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/backtrace_cleaner.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/backtrace_cleaner.rb | module ActiveSupport
# Many backtraces include too much information that's not relevant for the context. This makes it hard to find the signal
# in the backtrace and adds debugging time. With a BacktraceCleaner, you can setup filters and silencers for your particular
# context, so only the relevant lines are included.
#
# If you need to reconfigure an existing BacktraceCleaner, like the one in Rails, to show as much as possible, you can always
# call BacktraceCleaner#remove_silencers!
#
# Example:
#
# bc = BacktraceCleaner.new
# bc.add_filter { |line| line.gsub(Rails.root, '') }
# bc.add_silencer { |line| line =~ /mongrel|rubygems/ }
# bc.clean(exception.backtrace) # will strip the Rails.root prefix and skip any lines from mongrel or rubygems
#
# Inspired by the Quiet Backtrace gem by Thoughtbot.
class BacktraceCleaner
def initialize
@filters, @silencers = [], []
end
# Returns the backtrace after all filters and silencers has been run against it. Filters run first, then silencers.
def clean(backtrace)
silence(filter(backtrace))
end
# Adds a filter from the block provided. Each line in the backtrace will be mapped against this filter.
#
# Example:
#
# # Will turn "/my/rails/root/app/models/person.rb" into "/app/models/person.rb"
# backtrace_cleaner.add_filter { |line| line.gsub(Rails.root, '') }
def add_filter(&block)
@filters << block
end
# Adds a silencer from the block provided. If the silencer returns true for a given line, it'll be excluded from the
# clean backtrace.
#
# Example:
#
# # Will reject all lines that include the word "mongrel", like "/gems/mongrel/server.rb" or "/app/my_mongrel_server/rb"
# backtrace_cleaner.add_silencer { |line| line =~ /mongrel/ }
def add_silencer(&block)
@silencers << block
end
# Will remove all silencers, but leave in the filters. This is useful if your context of debugging suddenly expands as
# you suspect a bug in the libraries you use.
def remove_silencers!
@silencers = []
end
private
def filter(backtrace)
@filters.each do |f|
backtrace = backtrace.map { |line| f.call(line) }
end
backtrace
end
def silence(backtrace)
@silencers.each do |s|
backtrace = backtrace.reject { |line| s.call(line) }
end
backtrace
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/option_merger.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/option_merger.rb | module ActiveSupport
class OptionMerger #:nodoc:
instance_methods.each do |method|
undef_method(method) if method !~ /^(__|instance_eval|class|object_id)/
end
def initialize(context, options)
@context, @options = context, options
end
private
def method_missing(method, *arguments, &block)
if arguments.last.is_a?(Proc)
proc = arguments.pop
arguments << lambda { |*args| @options.deep_merge(proc.call(*args)) }
else
arguments << (arguments.last.respond_to?(:to_hash) ? @options.deep_merge(arguments.pop) : @options.dup)
end
@context.__send__(method, *arguments, &block)
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/dependencies.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/dependencies.rb | module ActiveSupport #:nodoc:
module Dependencies #:nodoc:
extend self
# Should we turn on Ruby warnings on the first load of dependent files?
mattr_accessor :warnings_on_first_load
self.warnings_on_first_load = false
# All files ever loaded.
mattr_accessor :history
self.history = Set.new
# All files currently loaded.
mattr_accessor :loaded
self.loaded = Set.new
# Should we load files or require them?
mattr_accessor :mechanism
self.mechanism = :load
# The set of directories from which we may automatically load files. Files
# under these directories will be reloaded on each request in development mode,
# unless the directory also appears in load_once_paths.
mattr_accessor :load_paths
self.load_paths = []
# The set of directories from which automatically loaded constants are loaded
# only once. All directories in this set must also be present in +load_paths+.
mattr_accessor :load_once_paths
self.load_once_paths = []
# An array of qualified constant names that have been loaded. Adding a name to
# this array will cause it to be unloaded the next time Dependencies are cleared.
mattr_accessor :autoloaded_constants
self.autoloaded_constants = []
# An array of constant names that need to be unloaded on every request. Used
# to allow arbitrary constants to be marked for unloading.
mattr_accessor :explicitly_unloadable_constants
self.explicitly_unloadable_constants = []
# The logger is used for generating information on the action run-time (including benchmarking) if available.
# Can be set to nil for no logging. Compatible with both Ruby's own Logger and Log4r loggers.
mattr_accessor :logger
# Set to true to enable logging of const_missing and file loads
mattr_accessor :log_activity
self.log_activity = false
# An internal stack used to record which constants are loaded by any block.
mattr_accessor :constant_watch_stack
self.constant_watch_stack = []
mattr_accessor :constant_watch_stack_mutex
self.constant_watch_stack_mutex = Mutex.new
# Module includes this module
module ModuleConstMissing #:nodoc:
def self.included(base) #:nodoc:
base.class_eval do
unless defined? const_missing_without_dependencies
alias_method_chain :const_missing, :dependencies
end
end
end
def self.excluded(base) #:nodoc:
base.class_eval do
if defined? const_missing_without_dependencies
undef_method :const_missing
alias_method :const_missing, :const_missing_without_dependencies
undef_method :const_missing_without_dependencies
end
end
end
# Use const_missing to autoload associations so we don't have to
# require_association when using single-table inheritance.
def const_missing_with_dependencies(class_id)
ActiveSupport::Dependencies.load_missing_constant self, class_id
end
def unloadable(const_desc = self)
super(const_desc)
end
end
# Class includes this module
module ClassConstMissing #:nodoc:
def const_missing(const_name)
if [Object, Kernel].include?(self) || parent == self
super
else
begin
begin
Dependencies.load_missing_constant self, const_name
rescue NameError
parent.send :const_missing, const_name
end
rescue NameError => e
# Make sure that the name we are missing is the one that caused the error
parent_qualified_name = Dependencies.qualified_name_for parent, const_name
raise unless e.missing_name? parent_qualified_name
qualified_name = Dependencies.qualified_name_for self, const_name
raise NameError.new("uninitialized constant #{qualified_name}").copy_blame!(e)
end
end
end
end
# Object includes this module
module Loadable #:nodoc:
def self.included(base) #:nodoc:
base.class_eval do
unless defined? load_without_new_constant_marking
alias_method_chain :load, :new_constant_marking
end
end
end
def self.excluded(base) #:nodoc:
base.class_eval do
if defined? load_without_new_constant_marking
undef_method :load
alias_method :load, :load_without_new_constant_marking
undef_method :load_without_new_constant_marking
end
end
end
def require_or_load(file_name)
Dependencies.require_or_load(file_name)
end
def require_dependency(file_name)
Dependencies.depend_on(file_name)
end
def require_association(file_name)
Dependencies.associate_with(file_name)
end
def load_with_new_constant_marking(file, *extras) #:nodoc:
if Dependencies.load?
Dependencies.new_constants_in(Object) { load_without_new_constant_marking(file, *extras) }
else
load_without_new_constant_marking(file, *extras)
end
rescue Exception => exception # errors from loading file
exception.blame_file! file
raise
end
def require(file, *extras) #:nodoc:
if Dependencies.load?
Dependencies.new_constants_in(Object) { super }
else
super
end
rescue Exception => exception # errors from required file
exception.blame_file! file
raise
end
# Mark the given constant as unloadable. Unloadable constants are removed each
# time dependencies are cleared.
#
# Note that marking a constant for unloading need only be done once. Setup
# or init scripts may list each unloadable constant that may need unloading;
# each constant will be removed for every subsequent clear, as opposed to for
# the first clear.
#
# The provided constant descriptor may be a (non-anonymous) module or class,
# or a qualified constant name as a string or symbol.
#
# Returns true if the constant was not previously marked for unloading, false
# otherwise.
def unloadable(const_desc)
Dependencies.mark_for_unload const_desc
end
end
# Exception file-blaming
module Blamable #:nodoc:
def blame_file!(file)
(@blamed_files ||= []).unshift file
end
def blamed_files
@blamed_files ||= []
end
def describe_blame
return nil if blamed_files.empty?
"This error occurred while loading the following files:\n #{blamed_files.join "\n "}"
end
def copy_blame!(exc)
@blamed_files = exc.blamed_files.clone
self
end
end
def hook!
Object.instance_eval { include Loadable }
Module.instance_eval { include ModuleConstMissing }
Class.instance_eval { include ClassConstMissing }
Exception.instance_eval { include Blamable }
true
end
def unhook!
ModuleConstMissing.excluded(Module)
Loadable.excluded(Object)
true
end
def load?
mechanism == :load
end
def depend_on(file_name, swallow_load_errors = false)
path = search_for_file(file_name)
require_or_load(path || file_name)
rescue LoadError
raise unless swallow_load_errors
end
def associate_with(file_name)
depend_on(file_name, true)
end
def clear
log_call
loaded.clear
remove_unloadable_constants!
end
def require_or_load(file_name, const_path = nil)
log_call file_name, const_path
file_name = $1 if file_name =~ /^(.*)\.rb$/
expanded = File.expand_path(file_name)
return if loaded.include?(expanded)
# Record that we've seen this file *before* loading it to avoid an
# infinite loop with mutual dependencies.
loaded << expanded
begin
if load?
log "loading #{file_name}"
# Enable warnings iff this file has not been loaded before and
# warnings_on_first_load is set.
load_args = ["#{file_name}.rb"]
load_args << const_path unless const_path.nil?
if !warnings_on_first_load or history.include?(expanded)
result = load_file(*load_args)
else
enable_warnings { result = load_file(*load_args) }
end
else
log "requiring #{file_name}"
result = require file_name
end
rescue Exception
loaded.delete expanded
raise
end
# Record history *after* loading so first load gets warnings.
history << expanded
return result
end
# Is the provided constant path defined?
def qualified_const_defined?(path)
raise NameError, "#{path.inspect} is not a valid constant name!" unless
/^(::)?([A-Z]\w*)(::[A-Z]\w*)*$/ =~ path
names = path.to_s.split('::')
names.shift if names.first.empty?
# We can't use defined? because it will invoke const_missing for the parent
# of the name we are checking.
names.inject(Object) do |mod, name|
return false unless uninherited_const_defined?(mod, name)
mod.const_get name
end
return true
end
if Module.method(:const_defined?).arity == 1
# Does this module define this constant?
# Wrapper to accomodate changing Module#const_defined? in Ruby 1.9
def uninherited_const_defined?(mod, const)
mod.const_defined?(const)
end
else
def uninherited_const_defined?(mod, const) #:nodoc:
mod.const_defined?(const, false)
end
end
# Given +path+, a filesystem path to a ruby file, return an array of constant
# paths which would cause Dependencies to attempt to load this file.
def loadable_constants_for_path(path, bases = load_paths)
path = $1 if path =~ /\A(.*)\.rb\Z/
expanded_path = File.expand_path(path)
bases.collect do |root|
expanded_root = File.expand_path(root)
next unless %r{\A#{Regexp.escape(expanded_root)}(/|\\)} =~ expanded_path
nesting = expanded_path[(expanded_root.size)..-1]
nesting = nesting[1..-1] if nesting && nesting[0] == ?/
next if nesting.blank?
nesting_camel = nesting.camelize
begin
qualified_const_defined?(nesting_camel)
rescue NameError
next
end
[ nesting_camel ]
end.flatten.compact.uniq
end
# Search for a file in load_paths matching the provided suffix.
def search_for_file(path_suffix)
path_suffix = path_suffix + '.rb' unless path_suffix.ends_with? '.rb'
load_paths.each do |root|
path = File.join(root, path_suffix)
return path if File.file? path
end
nil # Gee, I sure wish we had first_match ;-)
end
# Does the provided path_suffix correspond to an autoloadable module?
# Instead of returning a boolean, the autoload base for this module is returned.
def autoloadable_module?(path_suffix)
load_paths.each do |load_path|
return load_path if File.directory? File.join(load_path, path_suffix)
end
nil
end
def load_once_path?(path)
load_once_paths.any? { |base| path.starts_with? base }
end
# Attempt to autoload the provided module name by searching for a directory
# matching the expect path suffix. If found, the module is created and assigned
# to +into+'s constants with the name +const_name+. Provided that the directory
# was loaded from a reloadable base path, it is added to the set of constants
# that are to be unloaded.
def autoload_module!(into, const_name, qualified_name, path_suffix)
return nil unless base_path = autoloadable_module?(path_suffix)
mod = Module.new
into.const_set const_name, mod
autoloaded_constants << qualified_name unless load_once_paths.include?(base_path)
return mod
end
# Load the file at the provided path. +const_paths+ is a set of qualified
# constant names. When loading the file, Dependencies will watch for the
# addition of these constants. Each that is defined will be marked as
# autoloaded, and will be removed when Dependencies.clear is next called.
#
# If the second parameter is left off, then Dependencies will construct a set
# of names that the file at +path+ may define. See
# +loadable_constants_for_path+ for more details.
def load_file(path, const_paths = loadable_constants_for_path(path))
log_call path, const_paths
const_paths = [const_paths].compact unless const_paths.is_a? Array
parent_paths = const_paths.collect { |const_path| /(.*)::[^:]+\Z/ =~ const_path ? $1 : :Object }
result = nil
newly_defined_paths = new_constants_in(*parent_paths) do
result = load_without_new_constant_marking path
end
autoloaded_constants.concat newly_defined_paths unless load_once_path?(path)
autoloaded_constants.uniq!
log "loading #{path} defined #{newly_defined_paths * ', '}" unless newly_defined_paths.empty?
return result
end
# Return the constant path for the provided parent and constant name.
def qualified_name_for(mod, name)
mod_name = to_constant_name mod
(%w(Object Kernel).include? mod_name) ? name.to_s : "#{mod_name}::#{name}"
end
# Load the constant named +const_name+ which is missing from +from_mod+. If
# it is not possible to load the constant into from_mod, try its parent module
# using const_missing.
def load_missing_constant(from_mod, const_name)
log_call from_mod, const_name
if from_mod == Kernel
if ::Object.const_defined?(const_name)
log "Returning Object::#{const_name} for Kernel::#{const_name}"
return ::Object.const_get(const_name)
else
log "Substituting Object for Kernel"
from_mod = Object
end
end
# If we have an anonymous module, all we can do is attempt to load from Object.
from_mod = Object if from_mod.name.blank?
unless qualified_const_defined?(from_mod.name) && from_mod.name.constantize.object_id == from_mod.object_id
raise ArgumentError, "A copy of #{from_mod} has been removed from the module tree but is still active!"
end
raise ArgumentError, "#{from_mod} is not missing constant #{const_name}!" if uninherited_const_defined?(from_mod, const_name)
qualified_name = qualified_name_for from_mod, const_name
path_suffix = qualified_name.underscore
name_error = NameError.new("uninitialized constant #{qualified_name}")
file_path = search_for_file(path_suffix)
if file_path && ! loaded.include?(File.expand_path(file_path)) # We found a matching file to load
require_or_load file_path
raise LoadError, "Expected #{file_path} to define #{qualified_name}" unless uninherited_const_defined?(from_mod, const_name)
return from_mod.const_get(const_name)
elsif mod = autoload_module!(from_mod, const_name, qualified_name, path_suffix)
return mod
elsif (parent = from_mod.parent) && parent != from_mod &&
! from_mod.parents.any? { |p| uninherited_const_defined?(p, const_name) }
# If our parents do not have a constant named +const_name+ then we are free
# to attempt to load upwards. If they do have such a constant, then this
# const_missing must be due to from_mod::const_name, which should not
# return constants from from_mod's parents.
begin
return parent.const_missing(const_name)
rescue NameError => e
raise unless e.missing_name? qualified_name_for(parent, const_name)
raise name_error
end
else
raise name_error
end
end
# Remove the constants that have been autoloaded, and those that have been
# marked for unloading.
def remove_unloadable_constants!
autoloaded_constants.each { |const| remove_constant const }
autoloaded_constants.clear
explicitly_unloadable_constants.each { |const| remove_constant const }
end
# Determine if the given constant has been automatically loaded.
def autoloaded?(desc)
# No name => anonymous module.
return false if desc.is_a?(Module) && desc.name.blank?
name = to_constant_name desc
return false unless qualified_const_defined? name
return autoloaded_constants.include?(name)
end
# Will the provided constant descriptor be unloaded?
def will_unload?(const_desc)
autoloaded?(const_desc) ||
explicitly_unloadable_constants.include?(to_constant_name(const_desc))
end
# Mark the provided constant name for unloading. This constant will be
# unloaded on each request, not just the next one.
def mark_for_unload(const_desc)
name = to_constant_name const_desc
if explicitly_unloadable_constants.include? name
return false
else
explicitly_unloadable_constants << name
return true
end
end
# Run the provided block and detect the new constants that were loaded during
# its execution. Constants may only be regarded as 'new' once -- so if the
# block calls +new_constants_in+ again, then the constants defined within the
# inner call will not be reported in this one.
#
# If the provided block does not run to completion, and instead raises an
# exception, any new constants are regarded as being only partially defined
# and will be removed immediately.
def new_constants_in(*descs)
log_call(*descs)
# Build the watch frames. Each frame is a tuple of
# [module_name_as_string, constants_defined_elsewhere]
watch_frames = descs.collect do |desc|
if desc.is_a? Module
mod_name = desc.name
initial_constants = desc.local_constant_names
elsif desc.is_a?(String) || desc.is_a?(Symbol)
mod_name = desc.to_s
# Handle the case where the module has yet to be defined.
initial_constants = if qualified_const_defined?(mod_name)
mod_name.constantize.local_constant_names
else
[]
end
else
raise Argument, "#{desc.inspect} does not describe a module!"
end
[mod_name, initial_constants]
end
constant_watch_stack_mutex.synchronize do
constant_watch_stack.concat watch_frames
end
aborting = true
begin
yield # Now yield to the code that is to define new constants.
aborting = false
ensure
# Find the new constants.
new_constants = watch_frames.collect do |mod_name, prior_constants|
# Module still doesn't exist? Treat it as if it has no constants.
next [] unless qualified_const_defined?(mod_name)
mod = mod_name.constantize
next [] unless mod.is_a? Module
new_constants = mod.local_constant_names - prior_constants
# Make sure no other frames takes credit for these constants.
constant_watch_stack_mutex.synchronize do
constant_watch_stack.each do |frame_name, constants|
constants.concat new_constants if frame_name == mod_name
end
end
new_constants.collect do |suffix|
mod_name == "Object" ? suffix : "#{mod_name}::#{suffix}"
end
end.flatten
log "New constants: #{new_constants * ', '}"
if aborting
log "Error during loading, removing partially loaded constants "
new_constants.each { |name| remove_constant name }
new_constants.clear
end
end
return new_constants
ensure
# Remove the stack frames that we added.
if defined?(watch_frames) && ! watch_frames.blank?
frame_ids = watch_frames.collect { |frame| frame.object_id }
constant_watch_stack_mutex.synchronize do
constant_watch_stack.delete_if do |watch_frame|
frame_ids.include? watch_frame.object_id
end
end
end
end
class LoadingModule #:nodoc:
# Old style environment.rb referenced this method directly. Please note, it doesn't
# actually *do* anything any more.
def self.root(*args)
if defined?(Rails) && Rails.logger
Rails.logger.warn "Your environment.rb uses the old syntax, it may not continue to work in future releases."
Rails.logger.warn "For upgrade instructions please see: http://manuals.rubyonrails.com/read/book/19"
end
end
end
# Convert the provided const desc to a qualified constant name (as a string).
# A module, class, symbol, or string may be provided.
def to_constant_name(desc) #:nodoc:
name = case desc
when String then desc.starts_with?('::') ? desc[2..-1] : desc
when Symbol then desc.to_s
when Module
raise ArgumentError, "Anonymous modules have no name to be referenced by" if desc.name.blank?
desc.name
else raise TypeError, "Not a valid constant descriptor: #{desc.inspect}"
end
end
def remove_constant(const) #:nodoc:
return false unless qualified_const_defined? const
const = $1 if /\A::(.*)\Z/ =~ const.to_s
names = const.to_s.split('::')
if names.size == 1 # It's under Object
parent = Object
else
parent = (names[0..-2] * '::').constantize
end
log "removing constant #{const}"
parent.instance_eval { remove_const names.last }
return true
end
protected
def log_call(*args)
if logger && log_activity
arg_str = args.collect { |arg| arg.inspect } * ', '
/in `([a-z_\?\!]+)'/ =~ caller(1).first
selector = $1 || '<unknown>'
log "called #{selector}(#{arg_str})"
end
end
def log(msg)
if logger && log_activity
logger.debug "Dependencies: #{msg}"
end
end
end
end
ActiveSupport::Dependencies.hook!
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/basic_object.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/basic_object.rb | # A base class with no predefined methods that tries to behave like Builder's
# BlankSlate in Ruby 1.9. In Ruby pre-1.9, this is actually the
# Builder::BlankSlate class.
#
# Ruby 1.9 introduces BasicObject which differs slightly from Builder's
# BlankSlate that has been used so far. ActiveSupport::BasicObject provides a
# barebones base class that emulates Builder::BlankSlate while still relying on
# Ruby 1.9's BasicObject in Ruby 1.9.
module ActiveSupport
if defined? ::BasicObject
class BasicObject < ::BasicObject
undef_method :==
undef_method :equal?
# Let ActiveSupport::BasicObject at least raise exceptions.
def raise(*args)
::Object.send(:raise, *args)
end
end
else
require 'blankslate'
BasicObject = BlankSlate
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/whiny_nil.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/whiny_nil.rb | # Extensions to +nil+ which allow for more helpful error messages for people who
# are new to Rails.
#
# Ruby raises NoMethodError if you invoke a method on an object that does not
# respond to it:
#
# $ ruby -e nil.destroy
# -e:1: undefined method `destroy' for nil:NilClass (NoMethodError)
#
# With these extensions, if the method belongs to the public interface of the
# classes in NilClass::WHINERS the error message suggests which could be the
# actual intended class:
#
# $ script/runner nil.destroy
# ...
# You might have expected an instance of ActiveRecord::Base.
# ...
#
# NilClass#id exists in Ruby 1.8 (though it is deprecated). Since +id+ is a fundamental
# method of Active Record models NilClass#id is redefined as well to raise a RuntimeError
# and warn the user. She probably wanted a model database identifier and the 4
# returned by the original method could result in obscure bugs.
#
# The flag <tt>config.whiny_nils</tt> determines whether this feature is enabled.
# By default it is on in development and test modes, and it is off in production
# mode.
class NilClass
WHINERS = [::Array]
WHINERS << ::ActiveRecord::Base if defined? ::ActiveRecord
METHOD_CLASS_MAP = Hash.new
WHINERS.each do |klass|
methods = klass.public_instance_methods - public_instance_methods
class_name = klass.name
methods.each { |method| METHOD_CLASS_MAP[method.to_sym] = class_name }
end
# Raises a RuntimeError when you attempt to call +id+ on +nil+.
def id
raise RuntimeError, "Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id", caller
end
private
def method_missing(method, *args, &block)
raise_nil_warning_for METHOD_CLASS_MAP[method], method, caller
end
# Raises a NoMethodError when you attempt to call a method on +nil+.
def raise_nil_warning_for(class_name = nil, selector = nil, with_caller = nil)
message = "You have a nil object when you didn't expect it!"
message << "\nYou might have expected an instance of #{class_name}." if class_name
message << "\nThe error occurred while evaluating nil.#{selector}" if selector
raise NoMethodError, message, with_caller || caller
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/multibyte.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/multibyte.rb | # encoding: utf-8
module ActiveSupport #:nodoc:
module Multibyte
# A list of all available normalization forms. See http://www.unicode.org/reports/tr15/tr15-29.html for more
# information about normalization.
NORMALIZATION_FORMS = [:c, :kc, :d, :kd]
# The Unicode version that is supported by the implementation
UNICODE_VERSION = '5.1.0'
# The default normalization used for operations that require normalization. It can be set to any of the
# normalizations in NORMALIZATION_FORMS.
#
# Example:
# ActiveSupport::Multibyte.default_normalization_form = :c
mattr_accessor :default_normalization_form
self.default_normalization_form = :kc
# The proxy class returned when calling mb_chars. You can use this accessor to configure your own proxy
# class so you can support other encodings. See the ActiveSupport::Multibyte::Chars implementation for
# an example how to do this.
#
# Example:
# ActiveSupport::Multibyte.proxy_class = CharsForUTF32
def self.proxy_class=(klass)
@proxy_class = klass
end
# Returns the currect proxy class
def self.proxy_class
@proxy_class ||= ActiveSupport::Multibyte::Chars
end
# Regular expressions that describe valid byte sequences for a character
VALID_CHARACTER = {
# Borrowed from the Kconv library by Shinji KONO - (also as seen on the W3C site)
'UTF-8' => /\A(?:
[\x00-\x7f] |
[\xc2-\xdf] [\x80-\xbf] |
\xe0 [\xa0-\xbf] [\x80-\xbf] |
[\xe1-\xef] [\x80-\xbf] [\x80-\xbf] |
\xf0 [\x90-\xbf] [\x80-\xbf] [\x80-\xbf] |
[\xf1-\xf3] [\x80-\xbf] [\x80-\xbf] [\x80-\xbf] |
\xf4 [\x80-\x8f] [\x80-\xbf] [\x80-\xbf])\z /xn,
# Quick check for valid Shift-JIS characters, disregards the odd-even pairing
'Shift_JIS' => /\A(?:
[\x00-\x7e \xa1-\xdf] |
[\x81-\x9f \xe0-\xef] [\x40-\x7e \x80-\x9e \x9f-\xfc])\z /xn
}
end
end
require 'active_support/multibyte/chars'
require 'active_support/multibyte/exceptions'
require 'active_support/multibyte/unicode_database'
require 'active_support/multibyte/utils'
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/secure_random.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/secure_random.rb | begin
require 'securerandom'
rescue LoadError
end
module ActiveSupport
if defined?(::SecureRandom)
# Use Ruby's SecureRandom library if available.
SecureRandom = ::SecureRandom # :nodoc:
else
# = Secure random number generator interface.
#
# This library is an interface for secure random number generator which is
# suitable for generating session key in HTTP cookies, etc.
#
# It supports following secure random number generators.
#
# * openssl
# * /dev/urandom
# * Win32
#
# *Note*: This module is based on the SecureRandom library from Ruby 1.9,
# revision 18786, August 23 2008. It's 100% interface-compatible with Ruby 1.9's
# SecureRandom library.
#
# == Example
#
# # random hexadecimal string.
# p SecureRandom.hex(10) #=> "52750b30ffbc7de3b362"
# p SecureRandom.hex(10) #=> "92b15d6c8dc4beb5f559"
# p SecureRandom.hex(11) #=> "6aca1b5c58e4863e6b81b8"
# p SecureRandom.hex(12) #=> "94b2fff3e7fd9b9c391a2306"
# p SecureRandom.hex(13) #=> "39b290146bea6ce975c37cfc23"
# ...
#
# # random base64 string.
# p SecureRandom.base64(10) #=> "EcmTPZwWRAozdA=="
# p SecureRandom.base64(10) #=> "9b0nsevdwNuM/w=="
# p SecureRandom.base64(10) #=> "KO1nIU+p9DKxGg=="
# p SecureRandom.base64(11) #=> "l7XEiFja+8EKEtY="
# p SecureRandom.base64(12) #=> "7kJSM/MzBJI+75j8"
# p SecureRandom.base64(13) #=> "vKLJ0tXBHqQOuIcSIg=="
# ...
#
# # random binary string.
# p SecureRandom.random_bytes(10) #=> "\016\t{\370g\310pbr\301"
# p SecureRandom.random_bytes(10) #=> "\323U\030TO\234\357\020\a\337"
# ...
module SecureRandom
# SecureRandom.random_bytes generates a random binary string.
#
# The argument n specifies the length of the result string.
#
# If n is not specified, 16 is assumed.
# It may be larger in future.
#
# If secure random number generator is not available,
# NotImplementedError is raised.
def self.random_bytes(n=nil)
n ||= 16
unless defined? OpenSSL
begin
require 'openssl'
rescue LoadError
end
end
if defined? OpenSSL::Random
return OpenSSL::Random.random_bytes(n)
end
if !defined?(@has_urandom) || @has_urandom
flags = File::RDONLY
flags |= File::NONBLOCK if defined? File::NONBLOCK
flags |= File::NOCTTY if defined? File::NOCTTY
flags |= File::NOFOLLOW if defined? File::NOFOLLOW
begin
File.open("/dev/urandom", flags) {|f|
unless f.stat.chardev?
raise Errno::ENOENT
end
@has_urandom = true
ret = f.readpartial(n)
if ret.length != n
raise NotImplementedError, "Unexpected partial read from random device"
end
return ret
}
rescue Errno::ENOENT
@has_urandom = false
end
end
if !defined?(@has_win32)
begin
require 'Win32API'
crypt_acquire_context = Win32API.new("advapi32", "CryptAcquireContext", 'PPPII', 'L')
@crypt_gen_random = Win32API.new("advapi32", "CryptGenRandom", 'LIP', 'L')
hProvStr = " " * 4
prov_rsa_full = 1
crypt_verifycontext = 0xF0000000
if crypt_acquire_context.call(hProvStr, nil, nil, prov_rsa_full, crypt_verifycontext) == 0
raise SystemCallError, "CryptAcquireContext failed: #{lastWin32ErrorMessage}"
end
@hProv, = hProvStr.unpack('L')
@has_win32 = true
rescue LoadError
@has_win32 = false
end
end
if @has_win32
bytes = " " * n
if @crypt_gen_random.call(@hProv, bytes.size, bytes) == 0
raise SystemCallError, "CryptGenRandom failed: #{lastWin32ErrorMessage}"
end
return bytes
end
raise NotImplementedError, "No random device"
end
# SecureRandom.hex generates a random hex string.
#
# The argument n specifies the length of the random length.
# The length of the result string is twice of n.
#
# If n is not specified, 16 is assumed.
# It may be larger in future.
#
# If secure random number generator is not available,
# NotImplementedError is raised.
def self.hex(n=nil)
random_bytes(n).unpack("H*")[0]
end
# SecureRandom.base64 generates a random base64 string.
#
# The argument n specifies the length of the random length.
# The length of the result string is about 4/3 of n.
#
# If n is not specified, 16 is assumed.
# It may be larger in future.
#
# If secure random number generator is not available,
# NotImplementedError is raised.
def self.base64(n=nil)
[random_bytes(n)].pack("m*").delete("\n")
end
# SecureRandom.random_number generates a random number.
#
# If an positive integer is given as n,
# SecureRandom.random_number returns an integer:
# 0 <= SecureRandom.random_number(n) < n.
#
# If 0 is given or an argument is not given,
# SecureRandom.random_number returns an float:
# 0.0 <= SecureRandom.random_number() < 1.0.
def self.random_number(n=0)
if 0 < n
hex = n.to_s(16)
hex = '0' + hex if (hex.length & 1) == 1
bin = [hex].pack("H*")
mask = bin[0]
mask |= mask >> 1
mask |= mask >> 2
mask |= mask >> 4
begin
rnd = SecureRandom.random_bytes(bin.length)
rnd[0] = rnd[0] & mask
end until rnd < bin
rnd.unpack("H*")[0].hex
else
# assumption: Float::MANT_DIG <= 64
i64 = SecureRandom.random_bytes(8).unpack("Q")[0]
Math.ldexp(i64 >> (64-Float::MANT_DIG), -Float::MANT_DIG)
end
end
# Following code is based on David Garamond's GUID library for Ruby.
def self.lastWin32ErrorMessage # :nodoc:
get_last_error = Win32API.new("kernel32", "GetLastError", '', 'L')
format_message = Win32API.new("kernel32", "FormatMessageA", 'LPLLPLPPPPPPPP', 'L')
format_message_ignore_inserts = 0x00000200
format_message_from_system = 0x00001000
code = get_last_error.call
msg = "\0" * 1024
len = format_message.call(format_message_ignore_inserts + format_message_from_system, 0, code, 0, msg, 1024, nil, nil, nil, nil, nil, nil, nil, nil)
msg[0, len].tr("\r", '').chomp
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/cache.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/cache.rb | require 'benchmark'
module ActiveSupport
# See ActiveSupport::Cache::Store for documentation.
module Cache
autoload :FileStore, 'active_support/cache/file_store'
autoload :MemoryStore, 'active_support/cache/memory_store'
autoload :SynchronizedMemoryStore, 'active_support/cache/synchronized_memory_store'
autoload :DRbStore, 'active_support/cache/drb_store'
autoload :MemCacheStore, 'active_support/cache/mem_cache_store'
autoload :CompressedMemCacheStore, 'active_support/cache/compressed_mem_cache_store'
module Strategy
autoload :LocalCache, 'active_support/cache/strategy/local_cache'
end
# Creates a new CacheStore object according to the given options.
#
# If no arguments are passed to this method, then a new
# ActiveSupport::Cache::MemoryStore object will be returned.
#
# If you pass a Symbol as the first argument, then a corresponding cache
# store class under the ActiveSupport::Cache namespace will be created.
# For example:
#
# ActiveSupport::Cache.lookup_store(:memory_store)
# # => returns a new ActiveSupport::Cache::MemoryStore object
#
# ActiveSupport::Cache.lookup_store(:drb_store)
# # => returns a new ActiveSupport::Cache::DRbStore object
#
# Any additional arguments will be passed to the corresponding cache store
# class's constructor:
#
# ActiveSupport::Cache.lookup_store(:file_store, "/tmp/cache")
# # => same as: ActiveSupport::Cache::FileStore.new("/tmp/cache")
#
# If the first argument is not a Symbol, then it will simply be returned:
#
# ActiveSupport::Cache.lookup_store(MyOwnCacheStore.new)
# # => returns MyOwnCacheStore.new
def self.lookup_store(*store_option)
store, *parameters = *([ store_option ].flatten)
case store
when Symbol
store_class_name = (store == :drb_store ? "DRbStore" : store.to_s.camelize)
store_class = ActiveSupport::Cache.const_get(store_class_name)
store_class.new(*parameters)
when nil
ActiveSupport::Cache::MemoryStore.new
else
store
end
end
def self.expand_cache_key(key, namespace = nil)
expanded_cache_key = namespace ? "#{namespace}/" : ""
if ENV["RAILS_CACHE_ID"] || ENV["RAILS_APP_VERSION"]
expanded_cache_key << "#{ENV["RAILS_CACHE_ID"] || ENV["RAILS_APP_VERSION"]}/"
end
expanded_cache_key << case
when key.respond_to?(:cache_key)
key.cache_key
when key.is_a?(Array)
key.collect { |element| expand_cache_key(element) }.to_param
when key
key.to_param
end.to_s
expanded_cache_key
end
# An abstract cache store class. There are multiple cache store
# implementations, each having its own additional features. See the classes
# under the ActiveSupport::Cache module, e.g.
# ActiveSupport::Cache::MemCacheStore. MemCacheStore is currently the most
# popular cache store for large production websites.
#
# ActiveSupport::Cache::Store is meant for caching strings. Some cache
# store implementations, like MemoryStore, are able to cache arbitrary
# Ruby objects, but don't count on every cache store to be able to do that.
#
# cache = ActiveSupport::Cache::MemoryStore.new
#
# cache.read("city") # => nil
# cache.write("city", "Duckburgh")
# cache.read("city") # => "Duckburgh"
class Store
cattr_accessor :logger
attr_reader :silence, :logger_off
def silence!
@silence = true
self
end
alias silence? silence
alias logger_off? logger_off
# Fetches data from the cache, using the given key. If there is data in
# the cache with the given key, then that data is returned.
#
# If there is no such data in the cache (a cache miss occurred), then
# then nil will be returned. However, if a block has been passed, then
# that block will be run in the event of a cache miss. The return value
# of the block will be written to the cache under the given cache key,
# and that return value will be returned.
#
# cache.write("today", "Monday")
# cache.fetch("today") # => "Monday"
#
# cache.fetch("city") # => nil
# cache.fetch("city") do
# "Duckburgh"
# end
# cache.fetch("city") # => "Duckburgh"
#
# You may also specify additional options via the +options+ argument.
# Setting <tt>:force => true</tt> will force a cache miss:
#
# cache.write("today", "Monday")
# cache.fetch("today", :force => true) # => nil
#
# Other options will be handled by the specific cache store implementation.
# Internally, #fetch calls #read, and calls #write on a cache miss.
# +options+ will be passed to the #read and #write calls.
#
# For example, MemCacheStore's #write method supports the +:expires_in+
# option, which tells the memcached server to automatically expire the
# cache item after a certain period. We can use this option with #fetch
# too:
#
# cache = ActiveSupport::Cache::MemCacheStore.new
# cache.fetch("foo", :force => true, :expires_in => 5.seconds) do
# "bar"
# end
# cache.fetch("foo") # => "bar"
# sleep(6)
# cache.fetch("foo") # => nil
def fetch(key, options = {})
@logger_off = true
if !options[:force] && value = read(key, options)
@logger_off = false
log("hit", key, options)
value
elsif block_given?
@logger_off = false
log("miss", key, options)
value = nil
ms = Benchmark.ms { value = yield }
@logger_off = true
write(key, value, options)
@logger_off = false
log('write (will save %.2fms)' % ms, key, nil)
value
end
end
# Fetches data from the cache, using the given key. If there is data in
# the cache with the given key, then that data is returned. Otherwise,
# nil is returned.
#
# You may also specify additional options via the +options+ argument.
# The specific cache store implementation will decide what to do with
# +options+.
def read(key, options = nil)
log("read", key, options)
end
# Writes the given value to the cache, with the given key.
#
# You may also specify additional options via the +options+ argument.
# The specific cache store implementation will decide what to do with
# +options+.
#
# For example, MemCacheStore supports the +:expires_in+ option, which
# tells the memcached server to automatically expire the cache item after
# a certain period:
#
# cache = ActiveSupport::Cache::MemCacheStore.new
# cache.write("foo", "bar", :expires_in => 5.seconds)
# cache.read("foo") # => "bar"
# sleep(6)
# cache.read("foo") # => nil
def write(key, value, options = nil)
log("write", key, options)
end
def delete(key, options = nil)
log("delete", key, options)
end
def delete_matched(matcher, options = nil)
log("delete matched", matcher.inspect, options)
end
def exist?(key, options = nil)
log("exist?", key, options)
end
def increment(key, amount = 1)
log("incrementing", key, amount)
if num = read(key)
write(key, num + amount)
else
nil
end
end
def decrement(key, amount = 1)
log("decrementing", key, amount)
if num = read(key)
write(key, num - amount)
else
nil
end
end
private
def expires_in(options)
expires_in = options && options[:expires_in]
raise ":expires_in must be a number" if expires_in && !expires_in.is_a?(Numeric)
expires_in || 0
end
def log(operation, key, options)
logger.debug("Cache #{operation}: #{key}#{options ? " (#{options.inspect})" : ""}") if logger && !silence? && !logger_off?
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/string_inquirer.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/string_inquirer.rb | module ActiveSupport
# Wrapping a string in this class gives you a prettier way to test
# for equality. The value returned by <tt>Rails.env</tt> is wrapped
# in a StringInquirer object so instead of calling this:
#
# Rails.env == "production"
#
# you can call this:
#
# Rails.env.production?
#
class StringInquirer < String
def method_missing(method_name, *arguments)
if method_name.to_s[-1,1] == "?"
self == method_name.to_s[0..-2]
else
super
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/all.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/all.rb | # For forward compatibility with Rails 3.
#
# require 'active_support' loads a very bare minumum in Rails 3.
# require 'active_support/all' loads the whole suite like Rails 2 did.
#
# To prepare for Rails 3, switch to require 'active_support/all' now.
require 'active_support'
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/multibyte/chars.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/multibyte/chars.rb | # encoding: utf-8
module ActiveSupport #:nodoc:
module Multibyte #:nodoc:
# Chars enables you to work transparently with UTF-8 encoding in the Ruby String class without having extensive
# knowledge about the encoding. A Chars object accepts a string upon initialization and proxies String methods in an
# encoding safe manner. All the normal String methods are also implemented on the proxy.
#
# String methods are proxied through the Chars object, and can be accessed through the +mb_chars+ method. Methods
# which would normally return a String object now return a Chars object so methods can be chained.
#
# "The Perfect String ".mb_chars.downcase.strip.normalize #=> "the perfect string"
#
# Chars objects are perfectly interchangeable with String objects as long as no explicit class checks are made.
# If certain methods do explicitly check the class, call +to_s+ before you pass chars objects to them.
#
# bad.explicit_checking_method "T".mb_chars.downcase.to_s
#
# The default Chars implementation assumes that the encoding of the string is UTF-8, if you want to handle different
# encodings you can write your own multibyte string handler and configure it through
# ActiveSupport::Multibyte.proxy_class.
#
# class CharsForUTF32
# def size
# @wrapped_string.size / 4
# end
#
# def self.accepts?(string)
# string.length % 4 == 0
# end
# end
#
# ActiveSupport::Multibyte.proxy_class = CharsForUTF32
class Chars
# Hangul character boundaries and properties
HANGUL_SBASE = 0xAC00
HANGUL_LBASE = 0x1100
HANGUL_VBASE = 0x1161
HANGUL_TBASE = 0x11A7
HANGUL_LCOUNT = 19
HANGUL_VCOUNT = 21
HANGUL_TCOUNT = 28
HANGUL_NCOUNT = HANGUL_VCOUNT * HANGUL_TCOUNT
HANGUL_SCOUNT = 11172
HANGUL_SLAST = HANGUL_SBASE + HANGUL_SCOUNT
HANGUL_JAMO_FIRST = 0x1100
HANGUL_JAMO_LAST = 0x11FF
# All the unicode whitespace
UNICODE_WHITESPACE = [
(0x0009..0x000D).to_a, # White_Space # Cc [5] <control-0009>..<control-000D>
0x0020, # White_Space # Zs SPACE
0x0085, # White_Space # Cc <control-0085>
0x00A0, # White_Space # Zs NO-BREAK SPACE
0x1680, # White_Space # Zs OGHAM SPACE MARK
0x180E, # White_Space # Zs MONGOLIAN VOWEL SEPARATOR
(0x2000..0x200A).to_a, # White_Space # Zs [11] EN QUAD..HAIR SPACE
0x2028, # White_Space # Zl LINE SEPARATOR
0x2029, # White_Space # Zp PARAGRAPH SEPARATOR
0x202F, # White_Space # Zs NARROW NO-BREAK SPACE
0x205F, # White_Space # Zs MEDIUM MATHEMATICAL SPACE
0x3000, # White_Space # Zs IDEOGRAPHIC SPACE
].flatten.freeze
# BOM (byte order mark) can also be seen as whitespace, it's a non-rendering character used to distinguish
# between little and big endian. This is not an issue in utf-8, so it must be ignored.
UNICODE_LEADERS_AND_TRAILERS = UNICODE_WHITESPACE + [65279] # ZERO-WIDTH NO-BREAK SPACE aka BOM
# Returns a regular expression pattern that matches the passed Unicode codepoints
def self.codepoints_to_pattern(array_of_codepoints) #:nodoc:
array_of_codepoints.collect{ |e| [e].pack 'U*' }.join('|')
end
UNICODE_TRAILERS_PAT = /(#{codepoints_to_pattern(UNICODE_LEADERS_AND_TRAILERS)})+\Z/
UNICODE_LEADERS_PAT = /\A(#{codepoints_to_pattern(UNICODE_LEADERS_AND_TRAILERS)})+/
UTF8_PAT = ActiveSupport::Multibyte::VALID_CHARACTER['UTF-8']
attr_reader :wrapped_string
alias to_s wrapped_string
alias to_str wrapped_string
if '1.9'.respond_to?(:force_encoding)
# Creates a new Chars instance by wrapping _string_.
def initialize(string)
@wrapped_string = string
@wrapped_string.force_encoding(Encoding::UTF_8) unless @wrapped_string.frozen?
end
else
def initialize(string) #:nodoc:
@wrapped_string = string
end
end
# Forward all undefined methods to the wrapped string.
def method_missing(method, *args, &block)
if method.to_s =~ /!$/
@wrapped_string.__send__(method, *args, &block)
self
else
result = @wrapped_string.__send__(method, *args, &block)
result.kind_of?(String) ? chars(result) : result
end
end
# Returns +true+ if _obj_ responds to the given method. Private methods are included in the search
# only if the optional second parameter evaluates to +true+.
def respond_to?(method, include_private=false)
super || @wrapped_string.respond_to?(method, include_private) || false
end
# Enable more predictable duck-typing on String-like classes. See Object#acts_like?.
def acts_like_string?
true
end
# Returns +true+ if the Chars class can and should act as a proxy for the string _string_. Returns
# +false+ otherwise.
def self.wants?(string)
$KCODE == 'UTF8' && consumes?(string)
end
# Returns +true+ when the proxy class can handle the string. Returns +false+ otherwise.
def self.consumes?(string)
# Unpack is a little bit faster than regular expressions.
string.unpack('U*')
true
rescue ArgumentError
false
end
include Comparable
# Returns <tt>-1</tt>, <tt>0</tt> or <tt>+1</tt> depending on whether the Chars object is to be sorted before,
# equal or after the object on the right side of the operation. It accepts any object that implements +to_s+.
# See <tt>String#<=></tt> for more details.
#
# Example:
# 'é'.mb_chars <=> 'ü'.mb_chars #=> -1
def <=>(other)
@wrapped_string <=> other.to_s
end
# Returns a new Chars object containing the _other_ object concatenated to the string.
#
# Example:
# ('Café'.mb_chars + ' périferôl').to_s #=> "Café périferôl"
def +(other)
self << other
end
# Like <tt>String#=~</tt> only it returns the character offset (in codepoints) instead of the byte offset.
#
# Example:
# 'Café périferôl'.mb_chars =~ /ô/ #=> 12
def =~(other)
translate_offset(@wrapped_string =~ other)
end
# Works just like <tt>String#split</tt>, with the exception that the items in the resulting list are Chars
# instances instead of String. This makes chaining methods easier.
#
# Example:
# 'Café périferôl'.mb_chars.split(/é/).map { |part| part.upcase.to_s } #=> ["CAF", " P", "RIFERÔL"]
def split(*args)
@wrapped_string.split(*args).map { |i| i.mb_chars }
end
# Inserts the passed string at specified codepoint offsets.
#
# Example:
# 'Café'.mb_chars.insert(4, ' périferôl').to_s #=> "Café périferôl"
def insert(offset, fragment)
unpacked = self.class.u_unpack(@wrapped_string)
unless offset > unpacked.length
@wrapped_string.replace(
self.class.u_unpack(@wrapped_string).insert(offset, *self.class.u_unpack(fragment)).pack('U*')
)
else
raise IndexError, "index #{offset} out of string"
end
self
end
# Returns +true+ if contained string contains _other_. Returns +false+ otherwise.
#
# Example:
# 'Café'.mb_chars.include?('é') #=> true
def include?(other)
# We have to redefine this method because Enumerable defines it.
@wrapped_string.include?(other)
end
# Returns the position _needle_ in the string, counting in codepoints. Returns +nil+ if _needle_ isn't found.
#
# Example:
# 'Café périferôl'.mb_chars.index('ô') #=> 12
# 'Café périferôl'.mb_chars.index(/\w/u) #=> 0
def index(needle, offset=0)
wrapped_offset = self.first(offset).wrapped_string.length
index = @wrapped_string.index(needle, wrapped_offset)
index ? (self.class.u_unpack(@wrapped_string.slice(0...index)).size) : nil
end
# Returns the position _needle_ in the string, counting in
# codepoints, searching backward from _offset_ or the end of the
# string. Returns +nil+ if _needle_ isn't found.
#
# Example:
# 'Café périferôl'.mb_chars.rindex('é') #=> 6
# 'Café périferôl'.mb_chars.rindex(/\w/u) #=> 13
def rindex(needle, offset=nil)
offset ||= length
wrapped_offset = self.first(offset).wrapped_string.length
index = @wrapped_string.rindex(needle, wrapped_offset)
index ? (self.class.u_unpack(@wrapped_string.slice(0...index)).size) : nil
end
# Like <tt>String#[]=</tt>, except instead of byte offsets you specify character offsets.
#
# Example:
#
# s = "Müller"
# s.mb_chars[2] = "e" # Replace character with offset 2
# s
# #=> "Müeler"
#
# s = "Müller"
# s.mb_chars[1, 2] = "ö" # Replace 2 characters at character offset 1
# s
# #=> "Möler"
def []=(*args)
replace_by = args.pop
# Indexed replace with regular expressions already works
if args.first.is_a?(Regexp)
@wrapped_string[*args] = replace_by
else
result = self.class.u_unpack(@wrapped_string)
if args[0].is_a?(Fixnum)
raise IndexError, "index #{args[0]} out of string" if args[0] >= result.length
min = args[0]
max = args[1].nil? ? min : (min + args[1] - 1)
range = Range.new(min, max)
replace_by = [replace_by].pack('U') if replace_by.is_a?(Fixnum)
elsif args.first.is_a?(Range)
raise RangeError, "#{args[0]} out of range" if args[0].min >= result.length
range = args[0]
else
needle = args[0].to_s
min = index(needle)
max = min + self.class.u_unpack(needle).length - 1
range = Range.new(min, max)
end
result[range] = self.class.u_unpack(replace_by)
@wrapped_string.replace(result.pack('U*'))
end
end
# Works just like <tt>String#rjust</tt>, only integer specifies characters instead of bytes.
#
# Example:
#
# "¾ cup".mb_chars.rjust(8).to_s
# #=> " ¾ cup"
#
# "¾ cup".mb_chars.rjust(8, " ").to_s # Use non-breaking whitespace
# #=> " ¾ cup"
def rjust(integer, padstr=' ')
justify(integer, :right, padstr)
end
# Works just like <tt>String#ljust</tt>, only integer specifies characters instead of bytes.
#
# Example:
#
# "¾ cup".mb_chars.rjust(8).to_s
# #=> "¾ cup "
#
# "¾ cup".mb_chars.rjust(8, " ").to_s # Use non-breaking whitespace
# #=> "¾ cup "
def ljust(integer, padstr=' ')
justify(integer, :left, padstr)
end
# Works just like <tt>String#center</tt>, only integer specifies characters instead of bytes.
#
# Example:
#
# "¾ cup".mb_chars.center(8).to_s
# #=> " ¾ cup "
#
# "¾ cup".mb_chars.center(8, " ").to_s # Use non-breaking whitespace
# #=> " ¾ cup "
def center(integer, padstr=' ')
justify(integer, :center, padstr)
end
# Strips entire range of Unicode whitespace from the right of the string.
def rstrip
chars(@wrapped_string.gsub(UNICODE_TRAILERS_PAT, ''))
end
# Strips entire range of Unicode whitespace from the left of the string.
def lstrip
chars(@wrapped_string.gsub(UNICODE_LEADERS_PAT, ''))
end
# Strips entire range of Unicode whitespace from the right and left of the string.
def strip
rstrip.lstrip
end
# Returns the number of codepoints in the string
def size
self.class.u_unpack(@wrapped_string).size
end
alias_method :length, :size
# Reverses all characters in the string.
#
# Example:
# 'Café'.mb_chars.reverse.to_s #=> 'éfaC'
def reverse
chars(self.class.u_unpack(@wrapped_string).reverse.pack('U*'))
end
# Implements Unicode-aware slice with codepoints. Slicing on one point returns the codepoints for that
# character.
#
# Example:
# 'こんにちは'.mb_chars.slice(2..3).to_s #=> "にち"
def slice(*args)
if args.size > 2
raise ArgumentError, "wrong number of arguments (#{args.size} for 1)" # Do as if we were native
elsif (args.size == 2 && !(args.first.is_a?(Numeric) || args.first.is_a?(Regexp)))
raise TypeError, "cannot convert #{args.first.class} into Integer" # Do as if we were native
elsif (args.size == 2 && !args[1].is_a?(Numeric))
raise TypeError, "cannot convert #{args[1].class} into Integer" # Do as if we were native
elsif args[0].kind_of? Range
cps = self.class.u_unpack(@wrapped_string).slice(*args)
result = cps.nil? ? nil : cps.pack('U*')
elsif args[0].kind_of? Regexp
result = @wrapped_string.slice(*args)
elsif args.size == 1 && args[0].kind_of?(Numeric)
character = self.class.u_unpack(@wrapped_string)[args[0]]
result = character.nil? ? nil : [character].pack('U')
else
result = self.class.u_unpack(@wrapped_string).slice(*args).pack('U*')
end
result.nil? ? nil : chars(result)
end
alias_method :[], :slice
# Like <tt>String#slice!</tt>, except instead of byte offsets you specify character offsets.
#
# Example:
# s = 'こんにちは'
# s.mb_chars.slice!(2..3).to_s #=> "にち"
# s #=> "こんは"
def slice!(*args)
slice = self[*args]
self[*args] = ''
slice
end
# Returns the codepoint of the first character in the string.
#
# Example:
# 'こんにちは'.mb_chars.ord #=> 12371
def ord
self.class.u_unpack(@wrapped_string)[0]
end
# Convert characters in the string to uppercase.
#
# Example:
# 'Laurent, òu sont les tests?'.mb_chars.upcase.to_s #=> "LAURENT, ÒU SONT LES TESTS?"
def upcase
apply_mapping :uppercase_mapping
end
# Convert characters in the string to lowercase.
#
# Example:
# 'VĚDA A VÝZKUM'.mb_chars.downcase.to_s #=> "věda a výzkum"
def downcase
apply_mapping :lowercase_mapping
end
# Converts the first character to uppercase and the remainder to lowercase.
#
# Example:
# 'über'.mb_chars.capitalize.to_s #=> "Über"
def capitalize
(slice(0) || chars('')).upcase + (slice(1..-1) || chars('')).downcase
end
# Returns the KC normalization of the string by default. NFKC is considered the best normalization form for
# passing strings to databases and validations.
#
# * <tt>str</tt> - The string to perform normalization on.
# * <tt>form</tt> - The form you want to normalize in. Should be one of the following:
# <tt>:c</tt>, <tt>:kc</tt>, <tt>:d</tt>, or <tt>:kd</tt>. Default is
# ActiveSupport::Multibyte.default_normalization_form
def normalize(form=ActiveSupport::Multibyte.default_normalization_form)
# See http://www.unicode.org/reports/tr15, Table 1
codepoints = self.class.u_unpack(@wrapped_string)
chars(case form
when :d
self.class.reorder_characters(self.class.decompose_codepoints(:canonical, codepoints))
when :c
self.class.compose_codepoints(self.class.reorder_characters(self.class.decompose_codepoints(:canonical, codepoints)))
when :kd
self.class.reorder_characters(self.class.decompose_codepoints(:compatability, codepoints))
when :kc
self.class.compose_codepoints(self.class.reorder_characters(self.class.decompose_codepoints(:compatability, codepoints)))
else
raise ArgumentError, "#{form} is not a valid normalization variant", caller
end.pack('U*'))
end
# Performs canonical decomposition on all the characters.
#
# Example:
# 'é'.length #=> 2
# 'é'.mb_chars.decompose.to_s.length #=> 3
def decompose
chars(self.class.decompose_codepoints(:canonical, self.class.u_unpack(@wrapped_string)).pack('U*'))
end
# Performs composition on all the characters.
#
# Example:
# 'é'.length #=> 3
# 'é'.mb_chars.compose.to_s.length #=> 2
def compose
chars(self.class.compose_codepoints(self.class.u_unpack(@wrapped_string)).pack('U*'))
end
# Returns the number of grapheme clusters in the string.
#
# Example:
# 'क्षि'.mb_chars.length #=> 4
# 'क्षि'.mb_chars.g_length #=> 3
def g_length
self.class.g_unpack(@wrapped_string).length
end
# Replaces all ISO-8859-1 or CP1252 characters by their UTF-8 equivalent resulting in a valid UTF-8 string.
def tidy_bytes
chars(self.class.tidy_bytes(@wrapped_string))
end
%w(lstrip rstrip strip reverse upcase downcase tidy_bytes capitalize).each do |method|
define_method("#{method}!") do |*args|
unless args.nil?
@wrapped_string = send(method, *args).to_s
else
@wrapped_string = send(method).to_s
end
self
end
end
class << self
# Unpack the string at codepoints boundaries. Raises an EncodingError when the encoding of the string isn't
# valid UTF-8.
#
# Example:
# Chars.u_unpack('Café') #=> [67, 97, 102, 233]
def u_unpack(string)
begin
string.unpack 'U*'
rescue ArgumentError
raise EncodingError, 'malformed UTF-8 character'
end
end
# Detect whether the codepoint is in a certain character class. Returns +true+ when it's in the specified
# character class and +false+ otherwise. Valid character classes are: <tt>:cr</tt>, <tt>:lf</tt>, <tt>:l</tt>,
# <tt>:v</tt>, <tt>:lv</tt>, <tt>:lvt</tt> and <tt>:t</tt>.
#
# Primarily used by the grapheme cluster support.
def in_char_class?(codepoint, classes)
classes.detect { |c| UCD.boundary[c] === codepoint } ? true : false
end
# Unpack the string at grapheme boundaries. Returns a list of character lists.
#
# Example:
# Chars.g_unpack('क्षि') #=> [[2325, 2381], [2359], [2367]]
# Chars.g_unpack('Café') #=> [[67], [97], [102], [233]]
def g_unpack(string)
codepoints = u_unpack(string)
unpacked = []
pos = 0
marker = 0
eoc = codepoints.length
while(pos < eoc)
pos += 1
previous = codepoints[pos-1]
current = codepoints[pos]
if (
# CR X LF
one = ( previous == UCD.boundary[:cr] and current == UCD.boundary[:lf] ) or
# L X (L|V|LV|LVT)
two = ( UCD.boundary[:l] === previous and in_char_class?(current, [:l,:v,:lv,:lvt]) ) or
# (LV|V) X (V|T)
three = ( in_char_class?(previous, [:lv,:v]) and in_char_class?(current, [:v,:t]) ) or
# (LVT|T) X (T)
four = ( in_char_class?(previous, [:lvt,:t]) and UCD.boundary[:t] === current ) or
# X Extend
five = (UCD.boundary[:extend] === current)
)
else
unpacked << codepoints[marker..pos-1]
marker = pos
end
end
unpacked
end
# Reverse operation of g_unpack.
#
# Example:
# Chars.g_pack(Chars.g_unpack('क्षि')) #=> 'क्षि'
def g_pack(unpacked)
(unpacked.flatten).pack('U*')
end
def padding(padsize, padstr=' ') #:nodoc:
if padsize != 0
new(padstr * ((padsize / u_unpack(padstr).size) + 1)).slice(0, padsize)
else
''
end
end
# Re-order codepoints so the string becomes canonical.
def reorder_characters(codepoints)
length = codepoints.length- 1
pos = 0
while pos < length do
cp1, cp2 = UCD.codepoints[codepoints[pos]], UCD.codepoints[codepoints[pos+1]]
if (cp1.combining_class > cp2.combining_class) && (cp2.combining_class > 0)
codepoints[pos..pos+1] = cp2.code, cp1.code
pos += (pos > 0 ? -1 : 1)
else
pos += 1
end
end
codepoints
end
# Decompose composed characters to the decomposed form.
def decompose_codepoints(type, codepoints)
codepoints.inject([]) do |decomposed, cp|
# if it's a hangul syllable starter character
if HANGUL_SBASE <= cp and cp < HANGUL_SLAST
sindex = cp - HANGUL_SBASE
ncp = [] # new codepoints
ncp << HANGUL_LBASE + sindex / HANGUL_NCOUNT
ncp << HANGUL_VBASE + (sindex % HANGUL_NCOUNT) / HANGUL_TCOUNT
tindex = sindex % HANGUL_TCOUNT
ncp << (HANGUL_TBASE + tindex) unless tindex == 0
decomposed.concat ncp
# if the codepoint is decomposable in with the current decomposition type
elsif (ncp = UCD.codepoints[cp].decomp_mapping) and (!UCD.codepoints[cp].decomp_type || type == :compatability)
decomposed.concat decompose_codepoints(type, ncp.dup)
else
decomposed << cp
end
end
end
# Compose decomposed characters to the composed form.
def compose_codepoints(codepoints)
pos = 0
eoa = codepoints.length - 1
starter_pos = 0
starter_char = codepoints[0]
previous_combining_class = -1
while pos < eoa
pos += 1
lindex = starter_char - HANGUL_LBASE
# -- Hangul
if 0 <= lindex and lindex < HANGUL_LCOUNT
vindex = codepoints[starter_pos+1] - HANGUL_VBASE rescue vindex = -1
if 0 <= vindex and vindex < HANGUL_VCOUNT
tindex = codepoints[starter_pos+2] - HANGUL_TBASE rescue tindex = -1
if 0 <= tindex and tindex < HANGUL_TCOUNT
j = starter_pos + 2
eoa -= 2
else
tindex = 0
j = starter_pos + 1
eoa -= 1
end
codepoints[starter_pos..j] = (lindex * HANGUL_VCOUNT + vindex) * HANGUL_TCOUNT + tindex + HANGUL_SBASE
end
starter_pos += 1
starter_char = codepoints[starter_pos]
# -- Other characters
else
current_char = codepoints[pos]
current = UCD.codepoints[current_char]
if current.combining_class > previous_combining_class
if ref = UCD.composition_map[starter_char]
composition = ref[current_char]
else
composition = nil
end
unless composition.nil?
codepoints[starter_pos] = composition
starter_char = composition
codepoints.delete_at pos
eoa -= 1
pos -= 1
previous_combining_class = -1
else
previous_combining_class = current.combining_class
end
else
previous_combining_class = current.combining_class
end
if current.combining_class == 0
starter_pos = pos
starter_char = codepoints[pos]
end
end
end
codepoints
end
# Replaces all ISO-8859-1 or CP1252 characters by their UTF-8 equivalent resulting in a valid UTF-8 string.
def tidy_bytes(string)
string.split(//u).map do |c|
c.force_encoding(Encoding::ASCII) if c.respond_to?(:force_encoding)
if !ActiveSupport::Multibyte::VALID_CHARACTER['UTF-8'].match(c)
n = c.unpack('C')[0]
n < 128 ? n.chr :
n < 160 ? [UCD.cp1252[n] || n].pack('U') :
n < 192 ? "\xC2" + n.chr : "\xC3" + (n-64).chr
else
c
end
end.join
end
end
protected
def translate_offset(byte_offset) #:nodoc:
return nil if byte_offset.nil?
return 0 if @wrapped_string == ''
chunk = @wrapped_string[0..byte_offset]
begin
begin
chunk.unpack('U*').length - 1
rescue ArgumentError => e
chunk = @wrapped_string[0..(byte_offset+=1)]
# Stop retrying at the end of the string
raise e unless byte_offset < chunk.length
# We damaged a character, retry
retry
end
# Catch the ArgumentError so we can throw our own
rescue ArgumentError
raise EncodingError, 'malformed UTF-8 character'
end
end
def justify(integer, way, padstr=' ') #:nodoc:
raise ArgumentError, "zero width padding" if padstr.length == 0
padsize = integer - size
padsize = padsize > 0 ? padsize : 0
case way
when :right
result = @wrapped_string.dup.insert(0, self.class.padding(padsize, padstr))
when :left
result = @wrapped_string.dup.insert(-1, self.class.padding(padsize, padstr))
when :center
lpad = self.class.padding((padsize / 2.0).floor, padstr)
rpad = self.class.padding((padsize / 2.0).ceil, padstr)
result = @wrapped_string.dup.insert(0, lpad).insert(-1, rpad)
end
chars(result)
end
def apply_mapping(mapping) #:nodoc:
chars(self.class.u_unpack(@wrapped_string).map do |codepoint|
cp = UCD.codepoints[codepoint]
if cp and (ncp = cp.send(mapping)) and ncp > 0
ncp
else
codepoint
end
end.pack('U*'))
end
def chars(string) #:nodoc:
self.class.new(string)
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/multibyte/exceptions.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/multibyte/exceptions.rb | # encoding: utf-8
module ActiveSupport #:nodoc:
module Multibyte #:nodoc:
# Raised when a problem with the encoding was found.
class EncodingError < StandardError; end
end
end | ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/multibyte/utils.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/multibyte/utils.rb | # encoding: utf-8
module ActiveSupport #:nodoc:
module Multibyte #:nodoc:
if Kernel.const_defined?(:Encoding)
# Returns a regular expression that matches valid characters in the current encoding
def self.valid_character
VALID_CHARACTER[Encoding.default_internal.to_s]
end
else
def self.valid_character
case $KCODE
when 'UTF8'
VALID_CHARACTER['UTF-8']
when 'SJIS'
VALID_CHARACTER['Shift_JIS']
end
end
end
if 'string'.respond_to?(:valid_encoding?)
# Verifies the encoding of a string
def self.verify(string)
string.valid_encoding?
end
else
def self.verify(string)
if expression = valid_character
for c in string.split(//)
return false unless valid_character.match(c)
end
end
true
end
end
# Verifies the encoding of the string and raises an exception when it's not valid
def self.verify!(string)
raise EncodingError.new("Found characters with invalid encoding") unless verify(string)
end
if 'string'.respond_to?(:force_encoding)
# Removes all invalid characters from the string.
#
# Note: this method is a no-op in Ruby 1.9
def self.clean(string)
string
end
else
def self.clean(string)
if expression = valid_character
stripped = []; for c in string.split(//)
stripped << c if valid_character.match(c)
end; stripped.join
else
string
end
end
end
end
end | ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/multibyte/unicode_database.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/multibyte/unicode_database.rb | # encoding: utf-8
module ActiveSupport #:nodoc:
module Multibyte #:nodoc:
# Holds data about a codepoint in the Unicode database
class Codepoint
attr_accessor :code, :combining_class, :decomp_type, :decomp_mapping, :uppercase_mapping, :lowercase_mapping
end
# Holds static data from the Unicode database
class UnicodeDatabase
ATTRIBUTES = :codepoints, :composition_exclusion, :composition_map, :boundary, :cp1252
attr_writer(*ATTRIBUTES)
def initialize
@codepoints = Hash.new(Codepoint.new)
@composition_exclusion = []
@composition_map = {}
@boundary = {}
@cp1252 = {}
end
# Lazy load the Unicode database so it's only loaded when it's actually used
ATTRIBUTES.each do |attr_name|
class_eval(<<-EOS, __FILE__, __LINE__)
def #{attr_name} # def codepoints
load # load
@#{attr_name} # @codepoints
end # end
EOS
end
# Loads the Unicode database and returns all the internal objects of UnicodeDatabase.
def load
begin
@codepoints, @composition_exclusion, @composition_map, @boundary, @cp1252 = File.open(self.class.filename, 'rb') { |f| Marshal.load f.read }
rescue Exception => e
raise IOError.new("Couldn't load the Unicode tables for UTF8Handler (#{e.message}), ActiveSupport::Multibyte is unusable")
end
# Redefine the === method so we can write shorter rules for grapheme cluster breaks
@boundary.each do |k,_|
@boundary[k].instance_eval do
def ===(other)
detect { |i| i === other } ? true : false
end
end if @boundary[k].kind_of?(Array)
end
# define attr_reader methods for the instance variables
class << self
attr_reader(*ATTRIBUTES)
end
end
# Returns the directory in which the data files are stored
def self.dirname
File.dirname(__FILE__) + '/../values/'
end
# Returns the filename for the data file for this version
def self.filename
File.expand_path File.join(dirname, "unicode_tables.dat")
end
end
# UniCode Database
UCD = UnicodeDatabase.new
end
end | ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.