private byte[] getPublicKeyBytes(PublicKey publicKey) throws IOException, InvalidKeySpecException, NoSuchAlgorithmException { byte[] enc = publicKey.getEncoded(); ASN1InputStream ap = new ASN1InputStream(enc); DERSequence der = (DERSequence) ap.readObject(); DERBitString key = (DERBitString) der.getObjectAt(1); byte[] k = key.getBytes(); ap.close(); return k; }
private EncodedKeySpec getSpec(byte[] encodedKey, PublicKey pub) throws IOException, InvalidKeySpecException, NoSuchAlgorithmException { byte[] encc = pub.getEncoded(); ASN1InputStream ap = new ASN1InputStream(encc); DERSequence der = (DERSequence) ap.readObject(); DERSequence s1 = (DERSequence) der.getObjectAt(0); DERBitString bit = new DERBitString(encodedKey); DERSequence s2 = new DERSequence(new DERObject[] {s1, bit}); byte[] enc = s2.getEncoded(); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(enc); ap.close(); return keySpec; }