Search in sources :

Example 36 with DSAPrivateKey

use of java.security.interfaces.DSAPrivateKey in project robovm by robovm.

the class OpenSSLDSAKeyFactory method engineTranslateKey.

@Override
protected Key engineTranslateKey(Key key) throws InvalidKeyException {
    if (key == null) {
        throw new InvalidKeyException("key == null");
    }
    if ((key instanceof OpenSSLDSAPublicKey) || (key instanceof OpenSSLDSAPrivateKey)) {
        return key;
    } else if (key instanceof DSAPublicKey) {
        DSAPublicKey dsaKey = (DSAPublicKey) key;
        BigInteger y = dsaKey.getY();
        DSAParams params = dsaKey.getParams();
        BigInteger p = params.getP();
        BigInteger q = params.getQ();
        BigInteger g = params.getG();
        try {
            return engineGeneratePublic(new DSAPublicKeySpec(y, p, q, g));
        } catch (InvalidKeySpecException e) {
            throw new InvalidKeyException(e);
        }
    } else if (key instanceof DSAPrivateKey) {
        DSAPrivateKey dsaKey = (DSAPrivateKey) key;
        BigInteger x = dsaKey.getX();
        DSAParams params = dsaKey.getParams();
        BigInteger p = params.getP();
        BigInteger q = params.getQ();
        BigInteger g = params.getG();
        try {
            return engineGeneratePrivate(new DSAPrivateKeySpec(x, p, q, g));
        } catch (InvalidKeySpecException e) {
            throw new InvalidKeyException(e);
        }
    } else if ((key instanceof PrivateKey) && ("PKCS#8".equals(key.getFormat()))) {
        byte[] encoded = key.getEncoded();
        if (encoded == null) {
            throw new InvalidKeyException("Key does not support encoding");
        }
        try {
            return engineGeneratePrivate(new PKCS8EncodedKeySpec(encoded));
        } catch (InvalidKeySpecException e) {
            throw new InvalidKeyException(e);
        }
    } else if ((key instanceof PublicKey) && ("X.509".equals(key.getFormat()))) {
        byte[] encoded = key.getEncoded();
        if (encoded == null) {
            throw new InvalidKeyException("Key does not support encoding");
        }
        try {
            return engineGeneratePublic(new X509EncodedKeySpec(encoded));
        } catch (InvalidKeySpecException e) {
            throw new InvalidKeyException(e);
        }
    } else {
        throw new InvalidKeyException("Key must be DSA public or private key; was " + key.getClass().getName());
    }
}
Also used : DSAPrivateKey(java.security.interfaces.DSAPrivateKey) PrivateKey(java.security.PrivateKey) PublicKey(java.security.PublicKey) DSAPublicKey(java.security.interfaces.DSAPublicKey) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) DSAParams(java.security.interfaces.DSAParams) InvalidKeyException(java.security.InvalidKeyException) DSAPublicKey(java.security.interfaces.DSAPublicKey) DSAPrivateKeySpec(java.security.spec.DSAPrivateKeySpec) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) BigInteger(java.math.BigInteger) DSAPrivateKey(java.security.interfaces.DSAPrivateKey) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) DSAPublicKeySpec(java.security.spec.DSAPublicKeySpec)

Example 37 with DSAPrivateKey

use of java.security.interfaces.DSAPrivateKey in project BiglyBT by BiglySoftware.

the class PEMWriter method writeObject.

public void writeObject(Object o) throws IOException {
    String type;
    byte[] encoding;
    if (o instanceof X509Certificate) {
        type = "CERTIFICATE";
        try {
            encoding = ((X509Certificate) o).getEncoded();
        } catch (CertificateEncodingException e) {
            throw new IOException("Cannot encode object: " + e.toString());
        }
    } else if (o instanceof X509CRL) {
        type = "X509 CRL";
        try {
            encoding = ((X509CRL) o).getEncoded();
        } catch (CRLException e) {
            throw new IOException("Cannot encode object: " + e.toString());
        }
    } else if (o instanceof KeyPair) {
        writeObject(((KeyPair) o).getPrivate());
        return;
    } else if (o instanceof PrivateKey) {
        PrivateKeyInfo info = new PrivateKeyInfo((ASN1Sequence) ASN1Object.fromByteArray(((Key) o).getEncoded()));
        if (o instanceof RSAPrivateKey) {
            type = "RSA PRIVATE KEY";
            encoding = info.getPrivateKey().getEncoded();
        } else if (o instanceof DSAPrivateKey) {
            type = "DSA PRIVATE KEY";
            DSAParameter p = DSAParameter.getInstance(info.getAlgorithmId().getParameters());
            ASN1EncodableVector v = new ASN1EncodableVector();
            v.add(new DERInteger(0));
            v.add(new DERInteger(p.getP()));
            v.add(new DERInteger(p.getQ()));
            v.add(new DERInteger(p.getG()));
            BigInteger x = ((DSAPrivateKey) o).getX();
            BigInteger y = p.getG().modPow(x, p.getP());
            v.add(new DERInteger(y));
            v.add(new DERInteger(x));
            encoding = new DERSequence(v).getEncoded();
        } else {
            throw new IOException("Cannot identify private key");
        }
    } else if (o instanceof PublicKey) {
        type = "PUBLIC KEY";
        encoding = ((PublicKey) o).getEncoded();
    } else if (o instanceof X509AttributeCertificate) {
        type = "ATTRIBUTE CERTIFICATE";
        encoding = ((X509V2AttributeCertificate) o).getEncoded();
    } else if (o instanceof PKCS10CertificationRequest) {
        type = "CERTIFICATE REQUEST";
        encoding = ((PKCS10CertificationRequest) o).getEncoded();
    } else if (o instanceof ContentInfo) {
        type = "PKCS7";
        encoding = ((ContentInfo) o).getEncoded();
    } else {
        throw new IOException("unknown object passed - can't encode.");
    }
    writeHeader(type);
    writeEncoded(encoding);
    writeFooter(type);
}
Also used : PKCS10CertificationRequest(org.gudy.bouncycastle.jce.PKCS10CertificationRequest) X509CRL(java.security.cert.X509CRL) DSAPrivateKey(java.security.interfaces.DSAPrivateKey) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) X509AttributeCertificate(org.gudy.bouncycastle.x509.X509AttributeCertificate) CertificateEncodingException(java.security.cert.CertificateEncodingException) IOException(java.io.IOException) X509V2AttributeCertificate(org.gudy.bouncycastle.x509.X509V2AttributeCertificate) X509Certificate(java.security.cert.X509Certificate) ContentInfo(org.gudy.bouncycastle.asn1.cms.ContentInfo) DSAPrivateKey(java.security.interfaces.DSAPrivateKey) BigInteger(java.math.BigInteger) DSAParameter(org.gudy.bouncycastle.asn1.x509.DSAParameter) CRLException(java.security.cert.CRLException) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PrivateKeyInfo(org.gudy.bouncycastle.asn1.pkcs.PrivateKeyInfo) DSAPrivateKey(java.security.interfaces.DSAPrivateKey) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) RSAPrivateCrtKey(java.security.interfaces.RSAPrivateCrtKey)

Example 38 with DSAPrivateKey

use of java.security.interfaces.DSAPrivateKey in project BiglyBT by BiglySoftware.

the class PEMWriter method writeObject.

public void writeObject(Object obj, String algorithm, char[] password, SecureRandom random) throws IOException {
    if (obj instanceof KeyPair) {
        writeObject(((KeyPair) obj).getPrivate());
        return;
    }
    String type = null;
    byte[] keyData = null;
    if (obj instanceof RSAPrivateCrtKey) {
        type = "RSA PRIVATE KEY";
        RSAPrivateCrtKey k = (RSAPrivateCrtKey) obj;
        RSAPrivateKeyStructure keyStruct = new RSAPrivateKeyStructure(k.getModulus(), k.getPublicExponent(), k.getPrivateExponent(), k.getPrimeP(), k.getPrimeQ(), k.getPrimeExponentP(), k.getPrimeExponentQ(), k.getCrtCoefficient());
        // convert to bytearray
        keyData = keyStruct.getEncoded();
    } else if (obj instanceof DSAPrivateKey) {
        type = "DSA PRIVATE KEY";
        DSAPrivateKey k = (DSAPrivateKey) obj;
        DSAParams p = k.getParams();
        ASN1EncodableVector v = new ASN1EncodableVector();
        v.add(new DERInteger(0));
        v.add(new DERInteger(p.getP()));
        v.add(new DERInteger(p.getQ()));
        v.add(new DERInteger(p.getG()));
        BigInteger x = k.getX();
        BigInteger y = p.getG().modPow(x, p.getP());
        v.add(new DERInteger(y));
        v.add(new DERInteger(x));
        keyData = new DERSequence(v).getEncoded();
    }
    if (type == null || keyData == null) {
        // TODO Support other types?
        throw new IllegalArgumentException("Object type not supported: " + obj.getClass().getName());
    }
    String dekAlgName = Strings.toUpperCase(algorithm);
    // Note: For backward compatibility
    if (dekAlgName.equals("DESEDE")) {
        dekAlgName = "DES-EDE3-CBC";
    }
    int ivLength = dekAlgName.startsWith("AES-") ? 16 : 8;
    byte[] iv = new byte[ivLength];
    random.nextBytes(iv);
    byte[] encData = PEMUtilities.crypt(true, provider, keyData, password, dekAlgName, iv);
    // write the data
    writeHeader(type);
    this.write("Proc-Type: 4,ENCRYPTED");
    this.newLine();
    this.write("DEK-Info: " + dekAlgName + ",");
    this.writeHexEncoded(iv);
    this.newLine();
    this.newLine();
    this.writeEncoded(encData);
    writeFooter(type);
}
Also used : RSAPrivateCrtKey(java.security.interfaces.RSAPrivateCrtKey) DSAParams(java.security.interfaces.DSAParams) RSAPrivateKeyStructure(org.gudy.bouncycastle.asn1.pkcs.RSAPrivateKeyStructure) DSAPrivateKey(java.security.interfaces.DSAPrivateKey) BigInteger(java.math.BigInteger)

Example 39 with DSAPrivateKey

use of java.security.interfaces.DSAPrivateKey in project chromeview by pwnall.

the class AndroidKeyStore method rawSignDigestWithPrivateKey.

/**
 * Sign a given message with a given PrivateKey object. This method
 * shall only be used to implement signing in the context of SSL
 * client certificate support.
 *
 * The message will actually be a hash, computed and padded by OpenSSL,
 * itself, depending on the type of the key. The result should match
 * exactly what the vanilla implementations of the following OpenSSL
 * function calls do:
 *
 *  - For a RSA private key, this should be equivalent to calling
 *    RSA_sign(NDI_md5_sha1,....), i.e. it must generate a raw RSA
 *    signature. The message must a combined, 36-byte MD5+SHA1 message
 *    digest padded to the length of the modulus using PKCS#1 padding.
 *
 *  - For a DSA and ECDSA private keys, this should be equivalent to
 *    calling DSA_sign(0,...) and ECDSA_sign(0,...) respectively. The
 *    message must be a 20-byte SHA1 hash and the function shall
 *    compute a direct DSA/ECDSA signature for it.
 *
 * @param privateKey The PrivateKey handle.
 * @param message The message to sign.
 * @return signature as a byte buffer.
 *
 * Important: Due to a platform bug, this function will always fail on
 *            Android < 4.2 for RSA PrivateKey objects. See the
 *            getOpenSSLHandleForPrivateKey() below for work-around.
 */
@CalledByNative
public static byte[] rawSignDigestWithPrivateKey(PrivateKey privateKey, byte[] message) {
    // Get the Signature for this key.
    Signature signature = null;
    // http://docs.oracle.com/javase/6/docs/technotes/guides/security/StandardNames.html
    try {
        if (privateKey instanceof RSAPrivateKey) {
            // IMPORTANT: Due to a platform bug, this will throw NoSuchAlgorithmException
            // on Android 4.0.x and 4.1.x. Fixed in 4.2 and higher.
            // See https://android-review.googlesource.com/#/c/40352/
            signature = Signature.getInstance("NONEwithRSA");
        } else if (privateKey instanceof DSAPrivateKey) {
            signature = Signature.getInstance("NONEwithDSA");
        } else if (privateKey instanceof ECPrivateKey) {
            signature = Signature.getInstance("NONEwithECDSA");
        }
    } catch (NoSuchAlgorithmException e) {
        ;
    }
    if (signature == null) {
        Log.e(TAG, "Unsupported private key algorithm: " + privateKey.getAlgorithm());
        return null;
    }
    // Sign the message.
    try {
        signature.initSign(privateKey);
        signature.update(message);
        return signature.sign();
    } catch (Exception e) {
        Log.e(TAG, "Exception while signing message with " + privateKey.getAlgorithm() + " private key: " + e);
        return null;
    }
}
Also used : ECPrivateKey(java.security.interfaces.ECPrivateKey) Signature(java.security.Signature) DSAPrivateKey(java.security.interfaces.DSAPrivateKey) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) InvocationTargetException(java.lang.reflect.InvocationTargetException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CalledByNative(org.chromium.base.CalledByNative)

Example 40 with DSAPrivateKey

use of java.security.interfaces.DSAPrivateKey in project xipki by xipki.

the class SoftTokenContentSignerBuilder method createSigner.

public ConcurrentContentSigner createSigner(AlgorithmIdentifier signatureAlgId, int parallelism, SecureRandom random) throws XiSecurityException, NoSuchPaddingException {
    ParamUtil.requireNonNull("signatureAlgId", signatureAlgId);
    ParamUtil.requireMin("parallelism", parallelism, 1);
    List<XiContentSigner> signers = new ArrayList<>(parallelism);
    final String provName = "SunJCE";
    if (Security.getProvider(provName) != null) {
        String algoName;
        try {
            algoName = AlgorithmUtil.getSignatureAlgoName(signatureAlgId);
        } catch (NoSuchAlgorithmException ex) {
            throw new XiSecurityException(ex.getMessage());
        }
        try {
            for (int i = 0; i < parallelism; i++) {
                Signature signature = Signature.getInstance(algoName, provName);
                signature.initSign(key);
                if (i == 0) {
                    signature.update(new byte[] { 1, 2, 3, 4 });
                    signature.sign();
                }
                XiContentSigner signer = new SignatureSigner(signatureAlgId, signature, key);
                signers.add(signer);
            }
        } catch (Exception ex) {
            signers.clear();
        }
    }
    if (CollectionUtil.isEmpty(signers)) {
        BcContentSignerBuilder signerBuilder;
        AsymmetricKeyParameter keyparam;
        try {
            if (key instanceof RSAPrivateKey) {
                keyparam = SignerUtil.generateRSAPrivateKeyParameter((RSAPrivateKey) key);
                signerBuilder = new RSAContentSignerBuilder(signatureAlgId);
            } else if (key instanceof DSAPrivateKey) {
                keyparam = DSAUtil.generatePrivateKeyParameter(key);
                signerBuilder = new DSAContentSignerBuilder(signatureAlgId, AlgorithmUtil.isDSAPlainSigAlg(signatureAlgId));
            } else if (key instanceof ECPrivateKey) {
                keyparam = ECUtil.generatePrivateKeyParameter(key);
                EllipticCurve curve = ((ECPrivateKey) key).getParams().getCurve();
                if (GMUtil.isSm2primev2Curve(curve)) {
                    signerBuilder = new SM2ContentSignerBuilder();
                } else {
                    signerBuilder = new ECDSAContentSignerBuilder(signatureAlgId, AlgorithmUtil.isDSAPlainSigAlg(signatureAlgId));
                }
            } else {
                throw new XiSecurityException("unsupported key " + key.getClass().getName());
            }
        } catch (InvalidKeyException ex) {
            throw new XiSecurityException("invalid key", ex);
        } catch (NoSuchAlgorithmException ex) {
            throw new XiSecurityException("no such algorithm", ex);
        }
        for (int i = 0; i < parallelism; i++) {
            if (random != null) {
                signerBuilder.setSecureRandom(random);
            }
            ContentSigner signer;
            try {
                signer = signerBuilder.build(keyparam);
            } catch (OperatorCreationException ex) {
                throw new XiSecurityException("operator creation error", ex);
            }
            signers.add(new XiWrappedContentSigner(signer, true));
        }
    }
    final boolean mac = false;
    ConcurrentContentSigner concurrentSigner;
    try {
        concurrentSigner = new DfltConcurrentContentSigner(mac, signers, key);
    } catch (NoSuchAlgorithmException ex) {
        throw new XiSecurityException(ex.getMessage(), ex);
    }
    if (certificateChain != null) {
        concurrentSigner.setCertificateChain(certificateChain);
    } else {
        concurrentSigner.setPublicKey(publicKey);
    }
    return concurrentSigner;
}
Also used : ArrayList(java.util.ArrayList) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) XiSecurityException(org.xipki.security.exception.XiSecurityException) XiWrappedContentSigner(org.xipki.security.XiWrappedContentSigner) DfltConcurrentContentSigner(org.xipki.security.DfltConcurrentContentSigner) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) XiContentSigner(org.xipki.security.XiContentSigner) BcContentSignerBuilder(org.bouncycastle.operator.bc.BcContentSignerBuilder) ECPrivateKey(java.security.interfaces.ECPrivateKey) DfltConcurrentContentSigner(org.xipki.security.DfltConcurrentContentSigner) ContentSigner(org.bouncycastle.operator.ContentSigner) XiContentSigner(org.xipki.security.XiContentSigner) XiWrappedContentSigner(org.xipki.security.XiWrappedContentSigner) ConcurrentContentSigner(org.xipki.security.ConcurrentContentSigner) InvalidKeyException(java.security.InvalidKeyException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) XiSecurityException(org.xipki.security.exception.XiSecurityException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) NoSuchProviderException(java.security.NoSuchProviderException) SignatureSigner(org.xipki.security.SignatureSigner) DfltConcurrentContentSigner(org.xipki.security.DfltConcurrentContentSigner) ConcurrentContentSigner(org.xipki.security.ConcurrentContentSigner) AsymmetricKeyParameter(org.bouncycastle.crypto.params.AsymmetricKeyParameter) EllipticCurve(java.security.spec.EllipticCurve) Signature(java.security.Signature) DSAPrivateKey(java.security.interfaces.DSAPrivateKey) RSAPrivateKey(java.security.interfaces.RSAPrivateKey)

Aggregations

DSAPrivateKey (java.security.interfaces.DSAPrivateKey)48 BigInteger (java.math.BigInteger)23 DSAParams (java.security.interfaces.DSAParams)18 DSAPublicKey (java.security.interfaces.DSAPublicKey)15 RSAPrivateKey (java.security.interfaces.RSAPrivateKey)14 KeyPair (java.security.KeyPair)12 RSAPrivateCrtKey (java.security.interfaces.RSAPrivateCrtKey)12 DSAPrivateKeySpec (java.security.spec.DSAPrivateKeySpec)11 IOException (java.io.IOException)10 KeyPairGenerator (java.security.KeyPairGenerator)8 DSAPublicKeySpec (java.security.spec.DSAPublicKeySpec)8 InvalidKeyException (java.security.InvalidKeyException)7 ECPrivateKey (java.security.interfaces.ECPrivateKey)7 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)7 Signature (java.security.Signature)6 PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)6 X509EncodedKeySpec (java.security.spec.X509EncodedKeySpec)6 PrivateKey (java.security.PrivateKey)5 SlowTest (com.google.security.wycheproof.WycheproofRunner.SlowTest)4 Test (org.junit.Test)4