我显然缺少一些基本的东西。我有以下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
所以我有一个Bouncy Castle 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
对象。为什么会这样?
答案 0 :(得分: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)
}
答案 1 :(得分:1)
方法generateCertificate返回类型证书,因此推断val证书具有类型证书。 方法generateCertificate有一个方法签名:
Certificate generateCertificate(InputStream inStream)
当您将此调用的结果分配给val scala编译器时,将推断证书的类型,并且类型为Certificate,即generateCertificate返回的类型。
因此,如果要调用在X509CertificateObject类型上定义的方法,则必须先将其转换为正确的类型:
certificate.asInstanceOf[X509CertificateObject]
从getClass获得的是对象的运行时类。