Search in sources :

Example 1 with XDHKey

use of org.bouncycastle.jcajce.interfaces.XDHKey in project xipki by xipki.

the class KeypairWithCert method fromKeystore.

public static KeypairWithCert fromKeystore(KeyStore keystore, String keyname, char[] keyPassword, X509Cert[] certchain) throws XiSecurityException {
    notNull(keyPassword, "keyPassword");
    try {
        String tmpKeyname = keyname;
        if (tmpKeyname == null) {
            Enumeration<String> aliases = keystore.aliases();
            while (aliases.hasMoreElements()) {
                String alias = aliases.nextElement();
                if (keystore.isKeyEntry(alias)) {
                    tmpKeyname = alias;
                    break;
                }
            }
        } else {
            if (!keystore.isKeyEntry(tmpKeyname)) {
                throw new XiSecurityException("unknown key named " + tmpKeyname);
            }
        }
        PrivateKey key = (PrivateKey) keystore.getKey(tmpKeyname, keyPassword);
        if (!(key instanceof RSAPrivateKey || key instanceof DSAPrivateKey || key instanceof ECPrivateKey || key instanceof EdDSAKey || key instanceof XDHKey)) {
            throw new XiSecurityException("unsupported key " + key.getClass().getName());
        }
        Set<X509Cert> caCerts = new HashSet<>();
        X509Cert cert;
        if (certchain != null && certchain.length > 0) {
            cert = certchain[0];
            final int n = certchain.length;
            if (n > 1) {
                caCerts.addAll(Arrays.asList(certchain).subList(1, n));
            }
        } else {
            cert = new X509Cert((X509Certificate) keystore.getCertificate(tmpKeyname));
        }
        Certificate[] certsInKeystore = keystore.getCertificateChain(tmpKeyname);
        if (certsInKeystore.length > 1) {
            for (int i = 1; i < certsInKeystore.length; i++) {
                caCerts.add(new X509Cert((X509Certificate) certsInKeystore[i]));
            }
        }
        X509Cert[] certificateChain = X509Util.buildCertPath(cert, caCerts);
        return new KeypairWithCert(key, certificateChain);
    } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException | ClassCastException | CertPathBuilderException ex) {
        throw new XiSecurityException(ex.getMessage(), ex);
    }
}
Also used : ECPrivateKey(java.security.interfaces.ECPrivateKey) DSAPrivateKey(java.security.interfaces.DSAPrivateKey) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) ECPrivateKey(java.security.interfaces.ECPrivateKey) XDHKey(org.bouncycastle.jcajce.interfaces.XDHKey) X509Certificate(java.security.cert.X509Certificate) XiSecurityException(org.xipki.security.XiSecurityException) EdDSAKey(org.bouncycastle.jcajce.interfaces.EdDSAKey) CertPathBuilderException(java.security.cert.CertPathBuilderException) X509Cert(org.xipki.security.X509Cert) DSAPrivateKey(java.security.interfaces.DSAPrivateKey) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) HashSet(java.util.HashSet) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 2 with XDHKey

use of org.bouncycastle.jcajce.interfaces.XDHKey in project xipki by xipki.

the class P12KeyGenerator method getContentSigner.

// method generateIdentity
private static ContentSigner getContentSigner(PrivateKey key, PublicKey publicKey) throws Exception {
    if (key instanceof XDHKey) {
        String algorithm = key.getAlgorithm();
        ASN1ObjectIdentifier curveOid = EdECConstants.getCurveOid(algorithm);
        if (curveOid == null || !EdECConstants.isMontgomeryCurve(curveOid)) {
            throw new InvalidKeyException("unknown XDH key algorithm " + algorithm);
        }
        Signature signer = Signature.getInstance("EdDSA", "BC");
        // Just dummy: signature created by the signKey cannot be verified by the public key.
        PrivateKey signKey = KeyUtil.convertXDHToDummyEdDSAPrivateKey(key);
        return new SignatureSigner(new AlgorithmIdentifier(curveOid), signer, signKey);
    }
    P12ContentSignerBuilder builder = new P12ContentSignerBuilder(key, publicKey);
    SignAlgo algo;
    if (key instanceof RSAPrivateKey) {
        algo = SignAlgo.RSA_SHA256;
    } else if (key instanceof DSAPrivateKey) {
        algo = SignAlgo.DSA_SHA256;
    } else if (key instanceof ECPrivateKey) {
        if (GMUtil.isSm2primev2Curve(((ECPublicKey) publicKey).getParams().getCurve())) {
            algo = SignAlgo.SM2_SM3;
        } else {
            int keysize = ((ECPrivateKey) key).getParams().getOrder().bitLength();
            if (keysize > 384) {
                algo = SignAlgo.ECDSA_SHA512;
            } else if (keysize > 256) {
                algo = SignAlgo.ECDSA_SHA384;
            } else if (keysize > 160) {
                algo = SignAlgo.ECDSA_SHA256;
            } else {
                algo = SignAlgo.ECDSA_SHA1;
            }
        }
    } else if (key instanceof EdDSAKey) {
        String algorithm = key.getAlgorithm();
        ASN1ObjectIdentifier curveOid = EdECConstants.getCurveOid(algorithm);
        if (EdECConstants.id_ED25519.equals(curveOid)) {
            algo = SignAlgo.ED25519;
        } else if (EdECConstants.id_ED448.equals(curveOid)) {
            algo = SignAlgo.ED448;
        } else {
            throw new IllegalArgumentException("unknown EdDSA key algorithm " + algorithm);
        }
    } else {
        throw new IllegalArgumentException("unknown type of key " + key.getClass().getName());
    }
    return builder.createSigner(algo, 1, null).borrowSigner().value();
}
Also used : ECPrivateKey(java.security.interfaces.ECPrivateKey) DSAPrivateKey(java.security.interfaces.DSAPrivateKey) ECPrivateKey(java.security.interfaces.ECPrivateKey) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) XDHKey(org.bouncycastle.jcajce.interfaces.XDHKey) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) ECPublicKey(java.security.interfaces.ECPublicKey) EdDSAKey(org.bouncycastle.jcajce.interfaces.EdDSAKey) DSAPrivateKey(java.security.interfaces.DSAPrivateKey) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 3 with XDHKey

use of org.bouncycastle.jcajce.interfaces.XDHKey in project xipki by xipki.

the class KeyUtil method createSubjectPublicKeyInfo.

// method generatePublicKeyParameter
public static SubjectPublicKeyInfo createSubjectPublicKeyInfo(PublicKey publicKey) throws InvalidKeyException {
    notNull(publicKey, "publicKey");
    if (publicKey instanceof DSAPublicKey) {
        DSAPublicKey dsaPubKey = (DSAPublicKey) publicKey;
        ASN1EncodableVector vec = new ASN1EncodableVector();
        vec.add(new ASN1Integer(dsaPubKey.getParams().getP()));
        vec.add(new ASN1Integer(dsaPubKey.getParams().getQ()));
        vec.add(new ASN1Integer(dsaPubKey.getParams().getG()));
        ASN1Sequence dssParams = new DERSequence(vec);
        try {
            return new SubjectPublicKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.id_dsa, dssParams), new ASN1Integer(dsaPubKey.getY()));
        } catch (IOException ex) {
            throw new InvalidKeyException(ex.getMessage(), ex);
        }
    } else if (publicKey instanceof RSAPublicKey) {
        RSAPublicKey rsaPubKey = (RSAPublicKey) publicKey;
        try {
            return new SubjectPublicKeyInfo(new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption, DERNull.INSTANCE), new org.bouncycastle.asn1.pkcs.RSAPublicKey(rsaPubKey.getModulus(), rsaPubKey.getPublicExponent()));
        } catch (IOException ex) {
            throw new InvalidKeyException(ex.getMessage(), ex);
        }
    } else if (publicKey instanceof ECPublicKey) {
        ECPublicKey ecPubKey = (ECPublicKey) publicKey;
        ECParameterSpec paramSpec = ecPubKey.getParams();
        ASN1ObjectIdentifier curveOid = detectCurveOid(paramSpec);
        if (curveOid == null) {
            throw new InvalidKeyException("Cannot find namedCurve of the given private key");
        }
        java.security.spec.ECPoint pointW = ecPubKey.getW();
        BigInteger wx = pointW.getAffineX();
        if (wx.signum() != 1) {
            throw new InvalidKeyException("Wx is not positive");
        }
        BigInteger wy = pointW.getAffineY();
        if (wy.signum() != 1) {
            throw new InvalidKeyException("Wy is not positive");
        }
        int keysize = (paramSpec.getOrder().bitLength() + 7) / 8;
        byte[] wxBytes = BigIntegers.asUnsignedByteArray(keysize, wx);
        byte[] wyBytes = BigIntegers.asUnsignedByteArray(keysize, wy);
        byte[] pubKey = new byte[1 + keysize * 2];
        // uncompressed
        pubKey[0] = 4;
        System.arraycopy(wxBytes, 0, pubKey, 1, keysize);
        System.arraycopy(wyBytes, 0, pubKey, 1 + keysize, keysize);
        AlgorithmIdentifier algId = new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, curveOid);
        return new SubjectPublicKeyInfo(algId, pubKey);
    } else if (publicKey instanceof XDHKey || publicKey instanceof EdDSAKey) {
        String algorithm = publicKey.getAlgorithm().toUpperCase();
        byte[] encoded = publicKey.getEncoded();
        int keysize;
        byte[] prefix;
        ASN1ObjectIdentifier algOid;
        switch(algorithm) {
            case EdECConstants.ED25519:
                algOid = EdECConstants.id_ED25519;
                keysize = 32;
                prefix = Ed25519Prefix;
                break;
            case EdECConstants.X25519:
                algOid = EdECConstants.id_X25519;
                keysize = 32;
                prefix = x25519Prefix;
                break;
            case EdECConstants.ED448:
                algOid = EdECConstants.id_ED448;
                keysize = 57;
                prefix = Ed448Prefix;
                break;
            case EdECConstants.X448:
                algOid = EdECConstants.id_X448;
                keysize = 56;
                prefix = x448Prefix;
                break;
            default:
                throw new IllegalArgumentException("invalid algorithm " + algorithm);
        }
        if (encoded.length != prefix.length + keysize) {
            throw new IllegalArgumentException("invalid encoded PublicKey");
        }
        if (!CompareUtil.areEqual(encoded, 0, prefix, 0, prefix.length)) {
            throw new IllegalArgumentException("invalid encoded PublicKey");
        }
        byte[] keyData = Arrays.copyOfRange(encoded, prefix.length, prefix.length + keysize);
        AlgorithmIdentifier algId = new AlgorithmIdentifier(algOid);
        return new SubjectPublicKeyInfo(algId, keyData);
    } else {
        throw new InvalidKeyException("unknown publicKey class " + publicKey.getClass().getName());
    }
}
Also used : SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) java.security.spec(java.security.spec) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) org.bouncycastle.asn1(org.bouncycastle.asn1) XDHKey(org.bouncycastle.jcajce.interfaces.XDHKey) IOException(java.io.IOException) EdDSAKey(org.bouncycastle.jcajce.interfaces.EdDSAKey) BigInteger(java.math.BigInteger)

Example 4 with XDHKey

use of org.bouncycastle.jcajce.interfaces.XDHKey in project xipki by xipki.

the class KeyUtil method convertXDHToDummyEdDSAPrivateKey.

/**
 * Convert XDH edwards private key to EdDSA private key. As the name indicates,
 * the converted key is dummy, you cannot verify the signature signed with
 * the converted private key against the correspond public key.
 * @param key XDH private key
 * @return the corresponding EdDSA private key (dummy)
 * @throws InvalidKeySpecException
 *           If key is invalid.
 */
public static PrivateKey convertXDHToDummyEdDSAPrivateKey(PrivateKey key) throws InvalidKeySpecException {
    if (key instanceof XDHKey) {
        PrivateKeyInfo xdhPki = PrivateKeyInfo.getInstance(key.getEncoded());
        String xdhAlgo = key.getAlgorithm();
        try {
            PrivateKeyInfo edPki;
            if (xdhAlgo.equalsIgnoreCase(EdECConstants.X25519)) {
                edPki = new PrivateKeyInfo(new AlgorithmIdentifier(EdECConstants.id_ED25519), xdhPki.parsePrivateKey());
            } else if (xdhAlgo.equalsIgnoreCase(EdECConstants.X448)) {
                byte[] x448Octets = ASN1OctetString.getInstance(xdhPki.parsePrivateKey()).getOctets();
                byte[] ed448Octets = new byte[57];
                System.arraycopy(x448Octets, 0, ed448Octets, 0, 56);
                edPki = new PrivateKeyInfo(new AlgorithmIdentifier(EdECConstants.id_ED448), new DEROctetString(ed448Octets));
            } else {
                throw new IllegalArgumentException("unknown key algorithm " + xdhAlgo);
            }
            byte[] encoded = edPki.getEncoded();
            return getKeyFactory("EDDSA").generatePrivate(new PKCS8EncodedKeySpec(encoded));
        } catch (IOException ex) {
            throw new InvalidKeySpecException("could not convert XDH to EdDSA private key", ex);
        }
    } else {
        throw new IllegalArgumentException("key is not an XDH private key");
    }
}
Also used : XDHKey(org.bouncycastle.jcajce.interfaces.XDHKey) IOException(java.io.IOException) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier)

Example 5 with XDHKey

use of org.bouncycastle.jcajce.interfaces.XDHKey in project xipki by xipki.

the class EmulatorP11Identity method init.

private synchronized void init() throws P11TokenException {
    if (initialized) {
        return;
    }
    try {
        if (this.publicKey instanceof RSAPublicKey) {
            String providerName = "BC";
            LOG.info("use provider {}", providerName);
            for (int i = 0; i < maxSessions; i++) {
                Cipher rsaCipher;
                try {
                    final String algo = "RSA/ECB/NoPadding";
                    rsaCipher = Cipher.getInstance(algo, providerName);
                    LOG.info("use cipher algorithm {}", algo);
                } catch (NoSuchPaddingException ex) {
                    throw new P11TokenException("NoSuchPadding", ex);
                } catch (NoSuchAlgorithmException ex) {
                    final String algo = "RSA/NONE/NoPadding";
                    try {
                        rsaCipher = Cipher.getInstance(algo, providerName);
                        LOG.info("use cipher algorithm {}", algo);
                    } catch (NoSuchPaddingException e1) {
                        throw new P11TokenException("NoSuchPadding", ex);
                    }
                }
                rsaCipher.init(Cipher.ENCRYPT_MODE, signingKey);
                rsaCiphers.add(new ConcurrentBagEntry<>(rsaCipher));
            }
        } else {
            String algorithm;
            if (this.publicKey instanceof ECPublicKey) {
                boolean sm2curve = GMUtil.isSm2primev2Curve(((ECPublicKey) this.publicKey).getParams().getCurve());
                algorithm = sm2curve ? null : "NONEwithECDSA";
            } else if (this.publicKey instanceof DSAPublicKey) {
                algorithm = "NONEwithDSA";
            } else if (this.publicKey instanceof EdDSAKey) {
                algorithm = null;
            } else if (this.publicKey instanceof XDHKey) {
                algorithm = null;
            } else {
                throw new P11TokenException("Currently only RSA, DSA, EC, EC Edwards and EC " + "Montgomery public key are supported, but not " + this.publicKey.getAlgorithm() + " (class: " + this.publicKey.getClass().getName() + ")");
            }
            if (algorithm != null) {
                for (int i = 0; i < maxSessions; i++) {
                    Signature dsaSignature = Signature.getInstance(algorithm, "BC");
                    dsaSignature.initSign((PrivateKey) signingKey, random);
                    dsaSignatures.add(new ConcurrentBagEntry<>(dsaSignature));
                }
            } else if (this.publicKey instanceof EdDSAKey) {
                algorithm = this.publicKey.getAlgorithm();
                for (int i = 0; i < maxSessions; i++) {
                    Signature signature = Signature.getInstance(algorithm, "BC");
                    signature.initSign((PrivateKey) signingKey);
                    eddsaSignatures.add(new ConcurrentBagEntry<>(signature));
                }
            } else if (this.publicKey instanceof XDHKey) {
            // do nothing. not suitable for sign.
            } else {
                for (int i = 0; i < maxSessions; i++) {
                    SM2Signer sm2signer = new SM2Signer(ECUtil.generatePrivateKeyParameter((PrivateKey) signingKey));
                    sm2Signers.add(new ConcurrentBagEntry<>(sm2signer));
                }
            }
        }
    } catch (GeneralSecurityException ex) {
        throw new P11TokenException(ex);
    } finally {
        initialized = true;
    }
}
Also used : ConcurrentBagEntry(org.xipki.util.concurrent.ConcurrentBagEntry) XDHKey(org.bouncycastle.jcajce.interfaces.XDHKey) DSAPublicKey(java.security.interfaces.DSAPublicKey) RSAPublicKey(java.security.interfaces.RSAPublicKey) ECPublicKey(java.security.interfaces.ECPublicKey) EdDSAKey(org.bouncycastle.jcajce.interfaces.EdDSAKey) GCMBlockCipher(org.bouncycastle.crypto.modes.GCMBlockCipher)

Aggregations

XDHKey (org.bouncycastle.jcajce.interfaces.XDHKey)6 EdDSAKey (org.bouncycastle.jcajce.interfaces.EdDSAKey)5 IOException (java.io.IOException)3 AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)3 DSAPrivateKey (java.security.interfaces.DSAPrivateKey)2 ECPrivateKey (java.security.interfaces.ECPrivateKey)2 ECPublicKey (java.security.interfaces.ECPublicKey)2 RSAPrivateKey (java.security.interfaces.RSAPrivateKey)2 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)2 SubjectPublicKeyInfo (org.bouncycastle.asn1.x509.SubjectPublicKeyInfo)2 File (java.io.File)1 BigInteger (java.math.BigInteger)1 CertPathBuilderException (java.security.cert.CertPathBuilderException)1 Certificate (java.security.cert.Certificate)1 X509Certificate (java.security.cert.X509Certificate)1 DSAPublicKey (java.security.interfaces.DSAPublicKey)1 RSAPublicKey (java.security.interfaces.RSAPublicKey)1 java.security.spec (java.security.spec)1 ECParameterSpec (java.security.spec.ECParameterSpec)1 HashSet (java.util.HashSet)1