Example usage for org.bouncycastle.asn1 ASN1Integer ASN1Integer

List of usage examples for org.bouncycastle.asn1 ASN1Integer ASN1Integer

Introduction

In this page you can find the example usage for org.bouncycastle.asn1 ASN1Integer ASN1Integer.

Prototype

public ASN1Integer(byte[] bytes) 

Source Link

Document

Construct an INTEGER from the passed in byte array.

Usage

From source file:org.jmrtd.lds.ActiveAuthenticationInfo.java

License:Open Source License

@Deprecated
public ASN1Primitive getDERObject() {
    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(new ASN1ObjectIdentifier(oid));
    v.add(new ASN1Integer(version));
    if (signatureAlgorithmOID != null) {
        v.add(new ASN1ObjectIdentifier(signatureAlgorithmOID));
    }/*from w  w  w. j a  v  a2s .c o  m*/
    return new DLSequence(v);
}

From source file:org.jmrtd.lds.ChipAuthenticationInfo.java

License:Open Source License

@Deprecated
public ASN1Primitive getDERObject() {
    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(new ASN1ObjectIdentifier(oid));
    v.add(new ASN1Integer(version));
    if (keyId.compareTo(BigInteger.ZERO) >= 0) {
        v.add(new ASN1Integer(keyId));
    }/* w  w  w.  j  a v  a 2 s  . c o  m*/
    return new DLSequence(v);
}

From source file:org.jmrtd.lds.ChipAuthenticationPublicKeyInfo.java

License:Open Source License

@Deprecated
public ASN1Primitive getDERObject() {
    ASN1EncodableVector vector = new ASN1EncodableVector();
    vector.add(new ASN1ObjectIdentifier(oid));
    vector.add((ASN1Sequence) subjectPublicKeyInfo.toASN1Primitive());
    if (keyId.compareTo(BigInteger.ZERO) >= 0) {
        vector.add(new ASN1Integer(keyId));
    }//from   ww w .j a  v  a2s.co m
    return new DLSequence(vector);
}

From source file:org.jmrtd.lds.PACEDomainParameterInfo.java

License:Open Source License

@Deprecated
@Override//from w  ww  .ja v a  2  s  .c o m
public ASN1Primitive getDERObject() {
    ASN1EncodableVector vector = new ASN1EncodableVector();

    /* Protocol */
    vector.add(new ASN1ObjectIdentifier(protocolOID));

    /* Required data */
    vector.add(domainParameter);

    /* Optional data */
    if (parameterId >= 0) {
        vector.add(new ASN1Integer(parameterId));
    }
    return new DLSequence(vector);
}

From source file:org.jmrtd.lds.PACEInfo.java

License:Open Source License

@Deprecated
@Override// w  w  w .j av a  2  s  .  c  o  m
public ASN1Primitive getDERObject() {
    ASN1EncodableVector vector = new ASN1EncodableVector();

    /* Protocol */
    vector.add(new ASN1ObjectIdentifier(protocolOID));

    /* Required data */
    vector.add(new ASN1Integer(version));

    /* Optional data */
    if (parameterId >= 0) {
        vector.add(new ASN1Integer(parameterId));
    }
    return new DLSequence(vector);
}

From source file:org.jmrtd.lds.TerminalAuthenticationInfo.java

License:Open Source License

@Deprecated
public ASN1Primitive getDERObject() {
    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(new ASN1ObjectIdentifier(oid));
    v.add(new ASN1Integer(version));
    if (efCVCA != null) {
        v.add(efCVCA);// w  ww  . java 2 s  .  com
    }
    return new DLSequence(v);
}

From source file:org.jmrtd.Passport.java

License:Open Source License

/**
 * Check the active authentication result.
 * //  ww  w . j  av a2  s.  c  om
 * @param aaResult
 * @return
 */
public boolean verifyAA(ActiveAuthenticationResult aaResult) {
    try {
        PublicKey publicKey = aaResult.getPublicKey();
        String digestAlgorithm = aaResult.getDigestAlgorithm();
        String signatureAlgorithm = aaResult.getSignatureAlgorithm();
        byte[] challenge = aaResult.getChallenge();
        byte[] response = aaResult.getResponse();

        String pubKeyAlgorithm = publicKey.getAlgorithm();
        if ("RSA".equals(pubKeyAlgorithm)) {
            /* FIXME: check that digestAlgorithm = "SHA1" in this case, check (and re-initialize) rsaAASignature (and rsaAACipher). */
            if (!"SHA1".equalsIgnoreCase(digestAlgorithm) || !"SHA-1".equalsIgnoreCase(digestAlgorithm)
                    || !"SHA1WithRSA/ISO9796-2".equalsIgnoreCase(signatureAlgorithm)) {
                LOGGER.warning("Unexpected algorithms for RSA AA: " + "digest algorithm = "
                        + (digestAlgorithm == null ? "null" : digestAlgorithm) + ", signature algorithm = "
                        + (signatureAlgorithm == null ? "null" : signatureAlgorithm));

                rsaAADigest = MessageDigest
                        .getInstance(digestAlgorithm); /* NOTE: for output length measurement only. -- MO */
                rsaAASignature = Signature.getInstance(signatureAlgorithm, BC_PROVIDER);
            }

            RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
            rsaAACipher.init(Cipher.DECRYPT_MODE, rsaPublicKey);
            rsaAASignature.initVerify(rsaPublicKey);

            int digestLength = rsaAADigest.getDigestLength(); /* SHA1 should be 20 bytes = 160 bits */
            assert (digestLength == 20);
            byte[] plaintext = rsaAACipher.doFinal(response);
            byte[] m1 = Util.recoverMessage(digestLength, plaintext);
            rsaAASignature.update(m1);
            rsaAASignature.update(challenge);
            boolean success = rsaAASignature.verify(response);

            if (success) {
                verificationStatus.setAA(VerificationStatus.Verdict.SUCCEEDED, ReasonCode.SIGNATURE_CHECKED,
                        aaResult);
            } else {
                verificationStatus.setAA(VerificationStatus.Verdict.FAILED, ReasonCode.SIGNATURE_FAILURE,
                        aaResult);
            }
            return success;
        } else if ("EC".equals(pubKeyAlgorithm) || "ECDSA".equals(pubKeyAlgorithm)) {
            ECPublicKey ecdsaPublicKey = (ECPublicKey) publicKey;

            if (ecdsaAASignature == null || signatureAlgorithm != null
                    && !signatureAlgorithm.equals(ecdsaAASignature.getAlgorithm())) {
                LOGGER.warning(
                        "Re-initializing ecdsaAASignature with signature algorithm " + signatureAlgorithm);
                ecdsaAASignature = Signature.getInstance(signatureAlgorithm);
            }
            if (ecdsaAADigest == null
                    || digestAlgorithm != null && !digestAlgorithm.equals(ecdsaAADigest.getAlgorithm())) {
                LOGGER.warning("Re-initializing ecdsaAADigest with digest algorithm " + digestAlgorithm);
                ecdsaAADigest = MessageDigest.getInstance(digestAlgorithm);
            }

            ecdsaAASignature.initVerify(ecdsaPublicKey);

            if (response.length % 2 != 0) {
                LOGGER.warning("Active Authentication response is not of even length");
            }

            int l = response.length / 2;
            BigInteger r = Util.os2i(response, 0, l);
            BigInteger s = Util.os2i(response, l, l);

            ecdsaAASignature.update(challenge);

            try {

                ASN1Sequence asn1Sequence = new DERSequence(
                        new ASN1Encodable[] { new ASN1Integer(r), new ASN1Integer(s) });
                boolean success = ecdsaAASignature.verify(asn1Sequence.getEncoded());
                if (success) {
                    verificationStatus.setAA(VerificationStatus.Verdict.SUCCEEDED, ReasonCode.SUCCEEDED,
                            aaResult);
                } else {
                    verificationStatus.setAA(VerificationStatus.Verdict.FAILED, ReasonCode.SIGNATURE_FAILURE,
                            aaResult);
                }
                return success;
            } catch (IOException ioe) {
                LOGGER.severe("Unexpected exception during AA signature verification with ECDSA");
                ioe.printStackTrace();
                verificationStatus.setAA(VerificationStatus.Verdict.FAILED,
                        ReasonCode.UNEXPECTED_EXCEPTION_FAILURE, aaResult);
                return false;
            }
        } else {
            LOGGER.severe("Unsupported AA public key type " + publicKey.getClass().getSimpleName());
            verificationStatus.setAA(VerificationStatus.Verdict.FAILED, ReasonCode.UNSUPPORTED_KEY_TYPE_FAILURE,
                    aaResult);
            return false;
        }
    } catch (Exception e) {
        verificationStatus.setAA(VerificationStatus.Verdict.FAILED, ReasonCode.UNEXPECTED_EXCEPTION_FAILURE,
                aaResult);
        return false;
    }
}

From source file:org.jmrtd.Util.java

License:Open Source License

public static SubjectPublicKeyInfo toSubjectPublicKeyInfo(PublicKey publicKey) {
    try {//from   w w  w .j  a v a 2s .  c om
        String algorithm = publicKey.getAlgorithm();
        if ("EC".equals(algorithm) || "ECDH".equals(algorithm) || (publicKey instanceof ECPublicKey)) {
            ASN1InputStream asn1In = new ASN1InputStream(publicKey.getEncoded());
            SubjectPublicKeyInfo subjectPublicKeyInfo = new SubjectPublicKeyInfo(
                    (ASN1Sequence) asn1In.readObject());
            asn1In.close();
            AlgorithmIdentifier algorithmIdentifier = subjectPublicKeyInfo.getAlgorithm();
            String algOID = algorithmIdentifier.getAlgorithm().getId();
            if (!SecurityInfo.ID_EC_PUBLIC_KEY.equals(algOID)) {
                throw new IllegalStateException("Was expecting id-ecPublicKey ("
                        + SecurityInfo.ID_EC_PUBLIC_KEY_TYPE + "), found " + algOID);
            }
            ASN1Primitive derEncodedParams = algorithmIdentifier.getParameters().toASN1Primitive();
            X9ECParameters params = null;
            if (derEncodedParams instanceof ASN1ObjectIdentifier) {
                ASN1ObjectIdentifier paramsOID = (ASN1ObjectIdentifier) derEncodedParams;

                /* It's a named curve from X9.62. */
                params = X962NamedCurves.getByOID(paramsOID);
                if (params == null) {
                    throw new IllegalStateException(
                            "Could not find X9.62 named curve for OID " + paramsOID.getId());
                }

                /* Reconstruct the parameters. */
                org.bouncycastle.math.ec.ECPoint generator = params.getG();
                org.bouncycastle.math.ec.ECCurve curve = generator.getCurve();
                generator = curve.createPoint(generator.getX().toBigInteger(), generator.getY().toBigInteger(),
                        false);
                params = new X9ECParameters(params.getCurve(), generator, params.getN(), params.getH(),
                        params.getSeed());
            } else {
                /* It's not a named curve, we can just return the decoded public key info. */
                return subjectPublicKeyInfo;
            }

            if (publicKey instanceof org.bouncycastle.jce.interfaces.ECPublicKey) {
                org.bouncycastle.jce.interfaces.ECPublicKey ecPublicKey = (org.bouncycastle.jce.interfaces.ECPublicKey) publicKey;
                AlgorithmIdentifier id = new AlgorithmIdentifier(
                        subjectPublicKeyInfo.getAlgorithm().getAlgorithm(), params.toASN1Primitive());
                org.bouncycastle.math.ec.ECPoint q = ecPublicKey.getQ();
                /* FIXME: investigate the compressed versus uncompressed point issue. What is allowed in TR03110? -- MO */
                // In case we would like to compress the point:
                // p = p.getCurve().createPoint(p.getX().toBigInteger(), p.getY().toBigInteger(), true);
                subjectPublicKeyInfo = new SubjectPublicKeyInfo(id, q.getEncoded());
                return subjectPublicKeyInfo;
            } else {
                return subjectPublicKeyInfo;
            }
        } else if ("DH".equals(algorithm) || (publicKey instanceof DHPublicKey)) {
            DHPublicKey dhPublicKey = (DHPublicKey) publicKey;
            DHParameterSpec dhSpec = dhPublicKey.getParams();
            return new SubjectPublicKeyInfo(
                    new AlgorithmIdentifier(EACObjectIdentifiers.id_PK_DH,
                            new DHParameter(dhSpec.getP(), dhSpec.getG(), dhSpec.getL()).toASN1Primitive()),
                    new ASN1Integer(dhPublicKey.getY()));
        } else {
            throw new IllegalArgumentException(
                    "Unrecognized key type, found " + publicKey.getAlgorithm() + ", should be DH or ECDH");
        }
    } catch (Exception e) {
        LOGGER.severe("Exception: " + e.getMessage());
        return null;
    }
}

From source file:org.jruby.ext.openssl.impl.Envelope.java

License:LGPL

public ASN1Encodable asASN1() {
    ASN1EncodableVector vector = new ASN1EncodableVector();
    vector.add(new ASN1Integer(version));
    vector.add(receipientInfosToASN1Set());
    vector.add(encData.asASN1());/*from   ww  w .j a  va  2  s  . c  o m*/
    return new DLSequence(vector);
}

From source file:org.jruby.ext.openssl.impl.pem.MiscPEMGenerator.java

License:Open Source License

private PemObject createPemObject(Object o) throws IOException {
    String type;/*ww  w . j a  va2 s .  c om*/
    byte[] encoding;

    if (o instanceof PemObject) {
        return (PemObject) o;
    }
    if (o instanceof PemObjectGenerator) {
        return ((PemObjectGenerator) o).generate();
    }
    if (o instanceof X509CertificateHolder) {
        type = "CERTIFICATE";
        encoding = ((X509CertificateHolder) o).getEncoded();
    } else if (o instanceof X509CRLHolder) {
        type = "X509 CRL";
        encoding = ((X509CRLHolder) o).getEncoded();
    } else if (o instanceof PrivateKeyInfo) {
        PrivateKeyInfo info = (PrivateKeyInfo) o;
        ASN1ObjectIdentifier algOID = info.getPrivateKeyAlgorithm().getAlgorithm();

        if (algOID.equals(PKCSObjectIdentifiers.rsaEncryption)) {
            type = "RSA PRIVATE KEY";
            encoding = info.parsePrivateKey().toASN1Primitive().getEncoded();
        } else if (algOID.equals(dsaOids[0]) || algOID.equals(dsaOids[1])) {
            type = "DSA PRIVATE KEY";

            DSAParameter p = DSAParameter.getInstance(info.getPrivateKeyAlgorithm().getParameters());
            ASN1EncodableVector v = new ASN1EncodableVector();

            v.add(new ASN1Integer(BigInteger.ZERO));
            v.add(new ASN1Integer(p.getP()));
            v.add(new ASN1Integer(p.getQ()));
            v.add(new ASN1Integer(p.getG()));

            BigInteger x = ASN1Integer.getInstance(info.parsePrivateKey()).getValue();
            BigInteger y = p.getG().modPow(x, p.getP());

            v.add(new ASN1Integer(y));
            v.add(new ASN1Integer(x));

            encoding = new DERSequence(v).getEncoded();
        } else if (algOID.equals(X9ObjectIdentifiers.id_ecPublicKey)) {
            type = "EC PRIVATE KEY";
            encoding = info.parsePrivateKey().toASN1Primitive().getEncoded();
        } else {
            throw new IOException("Cannot identify private key");
        }
    } else if (o instanceof SubjectPublicKeyInfo) {
        type = "PUBLIC KEY";
        encoding = ((SubjectPublicKeyInfo) o).getEncoded();
    } else if (o instanceof X509AttributeCertificateHolder) {
        type = "ATTRIBUTE CERTIFICATE";
        encoding = ((X509AttributeCertificateHolder) 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();
    }
    //
    // NOTE: added behaviour to provide backwards compatibility with 1.47 :
    //
    else if (o instanceof java.security.cert.X509Certificate) // 1.47 compatibility
    {
        type = "CERTIFICATE";
        try {
            encoding = ((java.security.cert.X509Certificate) o).getEncoded();
        } catch (CertificateEncodingException e) {
            throw new PemGenerationException("Cannot encode object: " + e.toString());
        }
    } else if (o instanceof java.security.cert.X509CRL) // 1.47 compatibility
    {
        type = "X509 CRL";
        try {
            encoding = ((java.security.cert.X509CRL) o).getEncoded();
        } catch (CRLException e) {
            throw new PemGenerationException("Cannot encode object: " + e.toString());
        }
    } else if (o instanceof java.security.KeyPair) // 1.47 compatibility
    {
        return createPemObject(((java.security.KeyPair) o).getPrivate());
    } else if (o instanceof java.security.PrivateKey) // 1.47 compatibility
    {
        PrivateKeyInfo info = new PrivateKeyInfo(
                (ASN1Sequence) ASN1Primitive.fromByteArray(((java.security.Key) o).getEncoded()));

        if (o instanceof java.security.interfaces.RSAPrivateKey) {
            type = "RSA PRIVATE KEY";

            encoding = info.parsePrivateKey().toASN1Primitive().getEncoded();
        } else if (o instanceof java.security.interfaces.DSAPrivateKey) {
            type = "DSA PRIVATE KEY";

            DSAParameter p = DSAParameter.getInstance(info.getPrivateKeyAlgorithm().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 = ((java.security.interfaces.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 if (((java.security.PrivateKey) o).getAlgorithm().equals("ECDSA")) {
            type = "EC PRIVATE KEY";

            encoding = info.parsePrivateKey().toASN1Primitive().getEncoded();
        } else {
            throw new IOException("Cannot identify private key");
        }
    } else if (o instanceof java.security.PublicKey) // 1.47 compatibility
    {
        type = "PUBLIC KEY";

        encoding = ((java.security.PublicKey) o).getEncoded();
    } else if (o instanceof X509AttributeCertificate) // 1.47 compatibility
    {
        type = "ATTRIBUTE CERTIFICATE";
        encoding = ((X509AttributeCertificate) o).getEncoded();
    }
    //
    //
    //
    else {
        throw new PemGenerationException("unknown object passed - can't encode.");
    }

    if (encryptor != null) // NEW STUFF (NOT IN OLD)
    {
        String dekAlgName = Strings.toUpperCase(encryptor.getAlgorithm());

        // Note: For backward compatibility
        if (dekAlgName.equals("DESEDE")) {
            dekAlgName = "DES-EDE3-CBC";
        }

        byte[] iv = encryptor.getIV();
        byte[] encData = encryptor.encrypt(encoding);

        List<PemHeader> headers = new ArrayList<PemHeader>(2);

        headers.add(new PemHeader("Proc-Type", "4,ENCRYPTED"));
        headers.add(new PemHeader("DEK-Info", dekAlgName + "," + getHexEncoded(iv)));

        return new PemObject(type, headers, encData);
    }
    return new PemObject(type, encoding);
}