0

我显然在这里遗漏了一些基本的东西。我有以下 Scala 代码:

package org.carlskii

import java.io._
import java.security.cert.CertificateFactory
import java.security.Security
import org.bouncycastle.jce.provider._

object Main extends App {

  Security.addProvider(new BouncyCastleProvider)
  val provider = new BouncyCastleProvider
  val in = new FileInputStream("cert.cer")
  val certificateFactory = CertificateFactory.getInstance("X509", provider)
  val certificate = certificateFactory.generateCertificate(file)
  println(certificate.getClass)

} 

产生这个:

class org.bouncycastle.jce.provider.X509CertificateObject

所以我有一个充气城堡X509CertificateObject对象。如果我调用该certificate.getPublicKey方法,它会正确返回证书的公钥。

但是,如果我调用certificate.getSerialNumber它会引发以下错误:

error: value getSerialNumber is not a member of java.security.cert.Certificate
println(certificate.getSerialNumber)

有趣的是,Scala 认为它是一个对象java.security.cert.Certificate,而不是一个org.bouncycastle.jce.provider.X509CertificateObject对象。为什么会这样?

4

2 回答 2

3

generateCertificate方法返回一个Certificate对象,如果你确定你会得到一个org.bouncycastle.jce.provider.X509CertificateObject刚刚转换的结果:

package org.carlskii

import java.io._
import java.security.cert.CertificateFactory
import java.security.Security
import org.bouncycastle.jce.provider._

object Main extends App {

  Security.addProvider(new BouncyCastleProvider)
  val provider = new BouncyCastleProvider
  val in = new FileInputStream("cert.cer")
  val certificateFactory = CertificateFactory.getInstance("X509", provider)
  val certificate = certificateFactory.generateCertificate(file).asInstanceOf[X509CertificateObject]
  println(certificate.getClass)

} 
于 2012-11-04T15:23:06.597 回答
1

方法 generateCertificate 返回类型证书,因此推断 val 证书具有类型证书。方法 generateCertificate 具有以下方法签名:

Certificate generateCertificate(InputStream inStream)

当您将此调用的结果分配给 val scala 编译器将推断证书的类型,即方法 generateCertificate 返回的证书类型。

因此,如果您想调用在 X509CertificateObject 类型上定义的方法,您必须首先将其转换为正确的类型:

certificate.asInstanceOf[X509CertificateObject]

你从 getClass 得到的是一个对象的运行时类。

于 2012-11-04T15:07:06.733 回答