Class: SecureConf::OpenSSH::Keytype::RSA

Inherits:
Object
  • Object
show all
Includes:
Base, Singleton
Defined in:
lib/secure_conf/openssh.rb

Instance Method Summary collapse

Instance Method Details

#parse_der_private_key_contents(h, bio) ⇒ Object



221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
# File 'lib/secure_conf/openssh.rb', line 221

def parse_der_private_key_contents(h, bio)
  # n pub0
  length = bio.read(4).unpack("N")[0]
  h[:n] = bio.read(length)

  # e pub1
  length = bio.read(4).unpack("N")[0]
  h[:e] = bio.read(length)

  # d pri0
  length = bio.read(4).unpack("N")[0]
  h[:d] = bio.read(length)

  # iqmp
  length = bio.read(4).unpack("N")[0]
  h[:iqmp] = bio.read(length)

  # p
  length = bio.read(4).unpack("N")[0]
  h[:p] = bio.read(length)

  # q
  length = bio.read(4).unpack("N")[0]
  h[:q] = bio.read(length)
end

#parse_der_public_key_contents(h, bio) ⇒ Object



211
212
213
214
215
216
217
218
219
# File 'lib/secure_conf/openssh.rb', line 211

def parse_der_public_key_contents(h, bio)
  # e pub0
  length = bio.read(4).unpack("N")[0]
  h[:e] = bio.read(length)

  # n pub1
  length = bio.read(4).unpack("N")[0]
  h[:n] = bio.read(length)
end

#support?(keytype) ⇒ Boolean

Returns:

  • (Boolean)


207
208
209
# File 'lib/secure_conf/openssh.rb', line 207

def support?(keytype)
  keytype=="ssh-rsa"
end

#to_openssl(h) ⇒ Object



247
248
249
250
# File 'lib/secure_conf/openssh.rb', line 247

def to_openssl(h)
  pem = to_openssl_pem(h)
  OpenSSL::PKey::RSA.new(pem)
end

#to_openssl_der(h) ⇒ Object



264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
# File 'lib/secure_conf/openssh.rb', line 264

def to_openssl_der(h)
  d = h[:privatekey][:d].unpack("H*")[0].to_i(16)
  p = h[:privatekey][:p].unpack("H*")[0].to_i(16)
  q = h[:privatekey][:q].unpack("H*")[0].to_i(16)

  exponent1 = d % (p - 1)
  exponent2 = d % (q - 1)

  OpenSSL::ASN1::Sequence.new([
    OpenSSL::ASN1::Integer.new(0),
    OpenSSL::ASN1::Integer.new(h[:privatekey][:n].unpack("H*")[0].to_i(16)),
    OpenSSL::ASN1::Integer.new(h[:privatekey][:e].unpack("H*")[0].to_i(16)),
    OpenSSL::ASN1::Integer.new(h[:privatekey][:d].unpack("H*")[0].to_i(16)),
    OpenSSL::ASN1::Integer.new(p),
    OpenSSL::ASN1::Integer.new(q),
    OpenSSL::ASN1::Integer.new(exponent1),
    OpenSSL::ASN1::Integer.new(exponent2),
    OpenSSL::ASN1::Integer.new(h[:privatekey][:iqmp].unpack("H*")[0].to_i(16)),
  ]).to_der
end

#to_openssl_pem(h) ⇒ Object



252
253
254
255
256
257
258
259
260
261
262
# File 'lib/secure_conf/openssh.rb', line 252

def to_openssl_pem(h)
  der = to_openssl_der(h)
  b64 = Base64::strict_encode64(der)
  lines = b64.scan(/.{1,64}/)

  [
    "-----BEGIN RSA PRIVATE KEY-----",
    lines,
    "-----END RSA PRIVATE KEY-----",
  ].flatten.join("\n")
end