Question

Do java.security.Key.getEncoded() returns data in DER encoded format?

If not, is there a method that do?

UPDATE: A Key interface holding an RSA private key implementation

Was it helpful?

Solution

Depending on the type of key. Most symmetric keys return raw bytes with no encoding. Most public keys uses ASN.1/DER encoding.

You shouldn't care about how the key is encoded. Treat getEncoded as serialization function. It returns byte-stream representation of the key, which can be saved and converted back into the key later.

For RSA private keys, it's may be encoded as PKCS#1 or PKCS#8. PKCS#1 is the preferred encoding because it contains extra CRT parameters which speed up private key operations.

Sun JCE always generates key pairs in PKCS#1 encoding so the private key is always encoded in this format defined in 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
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top