java.security.Key.getEncoded() 是否以 DER 编码格式返回数据?

Tom*_*ito 7 java encoding rsa der

java.security.Key.getEncoded() 是否以DER编码格式返回数据?

如果没有,是否有方法可以做到?

更新:持有 RSA 私钥实现的密钥接口

ZZ *_*der 4

取决于密钥的类型。大多数对称密钥返回没有编码的原始字节。大多数公钥使用 ASN.1/DER 编码。

您不应该关心密钥是如何编码的。将 getEncoded 视为序列化函数。它返回密钥的字节流表示形式,可以保存该字节流并稍后将其转换回密钥。

对于 RSA 私钥,它可能被编码为 PKCS#1 或 PKCS#8。PKCS#1 是首选编码,因为它包含额外的 CRT 参数,可以加速私钥操作。

Sun JCE 始终以 PKCS#1 编码生成密钥对,因此私钥始终以 PKCS#1 中定义的格式进行编码,

-- 
-- Representation of RSA private key with information for the CRT algorithm.
--
RSAPrivateKey ::= SEQUENCE {
    version           Version, 
    modulus           INTEGER,  -- n
    publicExponent    INTEGER,  -- e
    privateExponent   INTEGER,  -- d
    prime1            INTEGER,  -- p
    prime2            INTEGER,  -- q
    exponent1         INTEGER,  -- d mod (p-1)
    exponent2         INTEGER,  -- d mod (q-1) 
    coefficient       INTEGER,  -- (inverse of q) mod p
    otherPrimeInfos   OtherPrimeInfos OPTIONAL 
}

Version ::= INTEGER { two-prime(0), multi(1) }
    (CONSTRAINED BY {-- version must be multi if otherPrimeInfos present --})

OtherPrimeInfos ::= SEQUENCE SIZE(1..MAX) OF OtherPrimeInfo


OtherPrimeInfo ::= SEQUENCE {
    prime             INTEGER,  -- ri
    exponent          INTEGER,  -- di
    coefficient       INTEGER   -- ti
}
Run Code Online (Sandbox Code Playgroud)

  • “*你不应该关心密钥是如何编码的。将 getEncoded 视为序列化函数。*” > 我不同意这一点。[文档](http://docs.oracle.com/javase/7/docs/api/java/security/Key.html)建议它“**是标准表示时使用的密钥的外部编码形式Java 虚拟机外部需要密钥的信息,就像将密钥传输给其他方时一样。**”。因此,格式在很多情况下都很重要。 (7认同)
  • 使用 RSAPrivateCrtKey.getEncoded() 进行测试,对我来说看起来像 PKCS#8。 (4认同)