Search in sources :

Example 81 with ASN1Integer

use of com.mindbright.asn1.ASN1Integer in project android_frameworks_base by crdroidandroid.

the class AndroidKeyStoreKeyPairGeneratorSpi method generateSelfSignedCertificateWithFakeSignature.

@SuppressWarnings("deprecation")
private X509Certificate generateSelfSignedCertificateWithFakeSignature(PublicKey publicKey) throws IOException, CertificateParsingException {
    V3TBSCertificateGenerator tbsGenerator = new V3TBSCertificateGenerator();
    ASN1ObjectIdentifier sigAlgOid;
    AlgorithmIdentifier sigAlgId;
    byte[] signature;
    switch(mKeymasterAlgorithm) {
        case KeymasterDefs.KM_ALGORITHM_EC:
            sigAlgOid = X9ObjectIdentifiers.ecdsa_with_SHA256;
            sigAlgId = new AlgorithmIdentifier(sigAlgOid);
            ASN1EncodableVector v = new ASN1EncodableVector();
            v.add(new DERInteger(0));
            v.add(new DERInteger(0));
            signature = new DERSequence().getEncoded();
            break;
        case KeymasterDefs.KM_ALGORITHM_RSA:
            sigAlgOid = PKCSObjectIdentifiers.sha256WithRSAEncryption;
            sigAlgId = new AlgorithmIdentifier(sigAlgOid, DERNull.INSTANCE);
            signature = new byte[1];
            break;
        default:
            throw new ProviderException("Unsupported key algorithm: " + mKeymasterAlgorithm);
    }
    try (ASN1InputStream publicKeyInfoIn = new ASN1InputStream(publicKey.getEncoded())) {
        tbsGenerator.setSubjectPublicKeyInfo(SubjectPublicKeyInfo.getInstance(publicKeyInfoIn.readObject()));
    }
    tbsGenerator.setSerialNumber(new ASN1Integer(mSpec.getCertificateSerialNumber()));
    X509Principal subject = new X509Principal(mSpec.getCertificateSubject().getEncoded());
    tbsGenerator.setSubject(subject);
    tbsGenerator.setIssuer(subject);
    tbsGenerator.setStartDate(new Time(mSpec.getCertificateNotBefore()));
    tbsGenerator.setEndDate(new Time(mSpec.getCertificateNotAfter()));
    tbsGenerator.setSignature(sigAlgId);
    TBSCertificate tbsCertificate = tbsGenerator.generateTBSCertificate();
    ASN1EncodableVector result = new ASN1EncodableVector();
    result.add(tbsCertificate);
    result.add(sigAlgId);
    result.add(new DERBitString(signature));
    return new X509CertificateObject(Certificate.getInstance(new DERSequence(result)));
}
Also used : ASN1InputStream(com.android.org.bouncycastle.asn1.ASN1InputStream) ProviderException(java.security.ProviderException) Time(com.android.org.bouncycastle.asn1.x509.Time) DERBitString(com.android.org.bouncycastle.asn1.DERBitString) ASN1Integer(com.android.org.bouncycastle.asn1.ASN1Integer) AlgorithmIdentifier(com.android.org.bouncycastle.asn1.x509.AlgorithmIdentifier) DERInteger(com.android.org.bouncycastle.asn1.DERInteger) DERSequence(com.android.org.bouncycastle.asn1.DERSequence) X509CertificateObject(com.android.org.bouncycastle.jce.provider.X509CertificateObject) X509Principal(com.android.org.bouncycastle.jce.X509Principal) ASN1EncodableVector(com.android.org.bouncycastle.asn1.ASN1EncodableVector) V3TBSCertificateGenerator(com.android.org.bouncycastle.asn1.x509.V3TBSCertificateGenerator) TBSCertificate(com.android.org.bouncycastle.asn1.x509.TBSCertificate) ASN1ObjectIdentifier(com.android.org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 82 with ASN1Integer

use of com.mindbright.asn1.ASN1Integer in project android_frameworks_base by crdroidandroid.

the class ESTHandler method unpackPkcs7.

private static List<X509Certificate> unpackPkcs7(ByteBuffer pkcs7) throws IOException, GeneralSecurityException {
    Collection<Asn1Object> pkcs7Content = Asn1Decoder.decode(pkcs7);
    if (pkcs7Content.size() != 1) {
        throw new IOException("Unexpected pkcs 7 container: " + pkcs7Content.size());
    }
    Asn1Object data = pkcs7Content.iterator().next();
    if (!data.isConstructed() || !data.matches(sSEQUENCE)) {
        throw new IOException("Expected SEQ OF, got " + data.toSimpleString());
    } else if (data.getChildren().size() != 2) {
        throw new IOException("Expected content info to have two children, got " + data.getChildren().size());
    }
    Iterator<Asn1Object> children = data.getChildren().iterator();
    Asn1Object contentType = children.next();
    if (!contentType.equals(Asn1Oid.PKCS7SignedData)) {
        throw new IOException("Content not PKCS7 signed data");
    }
    Asn1Object content = children.next();
    if (!content.isConstructed() || !content.matches(sCTXT0)) {
        throw new IOException("Expected [CONTEXT 0] with one child, got " + content.toSimpleString() + ", " + content.getChildren().size());
    }
    Asn1Object signedData = content.getChildren().iterator().next();
    Map<Integer, Asn1Object> itemMap = new HashMap<>();
    for (Asn1Object item : signedData.getChildren()) {
        if (itemMap.put(item.getTag(), item) != null && item.getTag() != Asn1Decoder.TAG_SET) {
            throw new IOException("Duplicate item in SignedData: " + item.toSimpleString());
        }
    }
    Asn1Object versionObject = itemMap.get(Asn1Decoder.TAG_INTEGER);
    if (versionObject == null || !(versionObject instanceof Asn1Integer)) {
        throw new IOException("Bad or missing PKCS7 version: " + versionObject);
    }
    int pkcs7version = (int) ((Asn1Integer) versionObject).getValue();
    Asn1Object innerContentInfo = itemMap.get(Asn1Decoder.TAG_SEQ);
    if (innerContentInfo == null || !innerContentInfo.isConstructed() || !innerContentInfo.matches(sSEQUENCE) || innerContentInfo.getChildren().size() != 1) {
        throw new IOException("Bad or missing PKCS7 contentInfo");
    }
    Asn1Object contentID = innerContentInfo.getChildren().iterator().next();
    if (pkcs7version == PKCS7DataVersion && !contentID.equals(Asn1Oid.PKCS7Data) || pkcs7version == PKCS7SignedDataVersion && !contentID.equals(Asn1Oid.PKCS7SignedData)) {
        throw new IOException("Inner PKCS7 content (" + contentID + ") not expected for version " + pkcs7version);
    }
    Asn1Object certWrapper = itemMap.get(0);
    if (certWrapper == null || !certWrapper.isConstructed() || !certWrapper.matches(sCTXT0)) {
        throw new IOException("Expected [CONTEXT 0], got: " + certWrapper);
    }
    List<X509Certificate> certList = new ArrayList<>(certWrapper.getChildren().size());
    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
    for (Asn1Object certObject : certWrapper.getChildren()) {
        ByteBuffer certOctets = ((Asn1Constructed) certObject).getEncoding();
        if (certOctets == null) {
            throw new IOException("No cert payload in: " + certObject);
        }
        byte[] certBytes = new byte[certOctets.remaining()];
        certOctets.get(certBytes);
        certList.add((X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(certBytes)));
    }
    return certList;
}
Also used : Asn1Constructed(com.android.hotspot2.asn1.Asn1Constructed) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) IOException(java.io.IOException) CertificateFactory(java.security.cert.CertificateFactory) ByteBuffer(java.nio.ByteBuffer) X509Certificate(java.security.cert.X509Certificate) Asn1Object(com.android.hotspot2.asn1.Asn1Object) Asn1Integer(com.android.hotspot2.asn1.Asn1Integer) ByteArrayInputStream(java.io.ByteArrayInputStream) Asn1Integer(com.android.hotspot2.asn1.Asn1Integer)

Example 83 with ASN1Integer

use of com.mindbright.asn1.ASN1Integer in project android_frameworks_base by AOSPA.

the class ESTHandler method unpackPkcs7.

private static List<X509Certificate> unpackPkcs7(ByteBuffer pkcs7) throws IOException, GeneralSecurityException {
    Collection<Asn1Object> pkcs7Content = Asn1Decoder.decode(pkcs7);
    if (pkcs7Content.size() != 1) {
        throw new IOException("Unexpected pkcs 7 container: " + pkcs7Content.size());
    }
    Asn1Object data = pkcs7Content.iterator().next();
    if (!data.isConstructed() || !data.matches(sSEQUENCE)) {
        throw new IOException("Expected SEQ OF, got " + data.toSimpleString());
    } else if (data.getChildren().size() != 2) {
        throw new IOException("Expected content info to have two children, got " + data.getChildren().size());
    }
    Iterator<Asn1Object> children = data.getChildren().iterator();
    Asn1Object contentType = children.next();
    if (!contentType.equals(Asn1Oid.PKCS7SignedData)) {
        throw new IOException("Content not PKCS7 signed data");
    }
    Asn1Object content = children.next();
    if (!content.isConstructed() || !content.matches(sCTXT0)) {
        throw new IOException("Expected [CONTEXT 0] with one child, got " + content.toSimpleString() + ", " + content.getChildren().size());
    }
    Asn1Object signedData = content.getChildren().iterator().next();
    Map<Integer, Asn1Object> itemMap = new HashMap<>();
    for (Asn1Object item : signedData.getChildren()) {
        if (itemMap.put(item.getTag(), item) != null && item.getTag() != Asn1Decoder.TAG_SET) {
            throw new IOException("Duplicate item in SignedData: " + item.toSimpleString());
        }
    }
    Asn1Object versionObject = itemMap.get(Asn1Decoder.TAG_INTEGER);
    if (versionObject == null || !(versionObject instanceof Asn1Integer)) {
        throw new IOException("Bad or missing PKCS7 version: " + versionObject);
    }
    int pkcs7version = (int) ((Asn1Integer) versionObject).getValue();
    Asn1Object innerContentInfo = itemMap.get(Asn1Decoder.TAG_SEQ);
    if (innerContentInfo == null || !innerContentInfo.isConstructed() || !innerContentInfo.matches(sSEQUENCE) || innerContentInfo.getChildren().size() != 1) {
        throw new IOException("Bad or missing PKCS7 contentInfo");
    }
    Asn1Object contentID = innerContentInfo.getChildren().iterator().next();
    if (pkcs7version == PKCS7DataVersion && !contentID.equals(Asn1Oid.PKCS7Data) || pkcs7version == PKCS7SignedDataVersion && !contentID.equals(Asn1Oid.PKCS7SignedData)) {
        throw new IOException("Inner PKCS7 content (" + contentID + ") not expected for version " + pkcs7version);
    }
    Asn1Object certWrapper = itemMap.get(0);
    if (certWrapper == null || !certWrapper.isConstructed() || !certWrapper.matches(sCTXT0)) {
        throw new IOException("Expected [CONTEXT 0], got: " + certWrapper);
    }
    List<X509Certificate> certList = new ArrayList<>(certWrapper.getChildren().size());
    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
    for (Asn1Object certObject : certWrapper.getChildren()) {
        ByteBuffer certOctets = ((Asn1Constructed) certObject).getEncoding();
        if (certOctets == null) {
            throw new IOException("No cert payload in: " + certObject);
        }
        byte[] certBytes = new byte[certOctets.remaining()];
        certOctets.get(certBytes);
        certList.add((X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(certBytes)));
    }
    return certList;
}
Also used : Asn1Constructed(com.android.hotspot2.asn1.Asn1Constructed) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) IOException(java.io.IOException) CertificateFactory(java.security.cert.CertificateFactory) ByteBuffer(java.nio.ByteBuffer) X509Certificate(java.security.cert.X509Certificate) Asn1Object(com.android.hotspot2.asn1.Asn1Object) Asn1Integer(com.android.hotspot2.asn1.Asn1Integer) ByteArrayInputStream(java.io.ByteArrayInputStream) Asn1Integer(com.android.hotspot2.asn1.Asn1Integer)

Example 84 with ASN1Integer

use of com.mindbright.asn1.ASN1Integer in project web3sdk by FISCO-BCOS.

the class SignTest method testGmSignVerify.

@Test
public void testGmSignVerify() throws IOException {
    byte[] sourceData = Hex.decode("434477813974bf58f94bcf760833c2b40f77a5fc360485b0b9ed1bd9682edb45");
    String publicKey = "e8c670380cb220095268f40221fc748fa6ac39d6e930e63c30da68bad97f885da6e8c9ad722c3683ab859393220d1431eb1818ed44a942efb07b261a0fc769e7";
    String sign = "09628650676000c8d18bf43db68e7f66dfaed230d87e6391c29eb594b7b9cc3c8d370dbd29ce62bbcf3506adb57f041d8646ae4f70a26ea5179418e738fd4372e8c670380cb220095268f40221fc748fa6ac39d6e930e63c30da68bad97f885da6e8c9ad722c3683ab859393220d1431eb1818ed44a942efb07b261a0fc769e7";
    byte[] signatureBytes = Numeric.hexStringToByteArray("0x" + sign);
    ASN1Integer d_r = new ASN1Integer(new BigInteger(1, Arrays.copyOfRange(signatureBytes, 0, 32)));
    ASN1Integer d_s = new ASN1Integer(new BigInteger(1, Arrays.copyOfRange(signatureBytes, 32, 64)));
    ASN1EncodableVector v2 = new ASN1EncodableVector();
    v2.add(d_r);
    v2.add(d_s);
    DERSequence der = new DERSequence(v2);
    boolean b = SM2Algorithm.verify(sourceData, der.getEncoded(), publicKey.substring(0, 64), publicKey.substring(64, 128));
    assertTrue("Test sm2 verify", b);
}
Also used : DERSequence(org.bouncycastle.asn1.DERSequence) BigInteger(java.math.BigInteger) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) Test(org.junit.Test)

Example 85 with ASN1Integer

use of com.mindbright.asn1.ASN1Integer in project keystore-explorer by kaikramer.

the class OpenSslPvkUtil method load.

/**
 * Load an unencrypted OpenSSL private key from the stream. The encoding of
 * the private key may be PEM or DER.
 *
 * @param is
 *            Stream to load the unencrypted private key from
 * @return The private key
 * @throws PrivateKeyEncryptedException
 *             If private key is encrypted
 * @throws CryptoException
 *             Problem encountered while loading the private key
 * @throws IOException
 *             An I/O error occurred
 */
public static PrivateKey load(InputStream is) throws CryptoException, IOException {
    byte[] streamContents = ReadUtil.readFully(is);
    EncryptionType encType = getEncryptionType(new ByteArrayInputStream(streamContents));
    if (encType == null) {
        throw new CryptoException(res.getString("NotValidOpenSsl.exception.message"));
    }
    if (encType == ENCRYPTED) {
        throw new PrivateKeyEncryptedException(res.getString("OpenSslIsEncrypted.exception.message"));
    }
    // Check if stream is PEM encoded
    PemInfo pemInfo = PemUtil.decode(new ByteArrayInputStream(streamContents));
    if (pemInfo != null) {
        // It is - get DER from PEM
        streamContents = pemInfo.getContent();
    }
    try {
        // Read OpenSSL DER structure
        ASN1InputStream asn1InputStream = new ASN1InputStream(streamContents);
        ASN1Primitive openSsl = asn1InputStream.readObject();
        asn1InputStream.close();
        if (openSsl instanceof ASN1Sequence) {
            ASN1Sequence seq = (ASN1Sequence) openSsl;
            if (seq.size() == 9) {
                // RSA private key
                BigInteger version = ((ASN1Integer) seq.getObjectAt(0)).getValue();
                BigInteger modulus = ((ASN1Integer) seq.getObjectAt(1)).getValue();
                BigInteger publicExponent = ((ASN1Integer) seq.getObjectAt(2)).getValue();
                BigInteger privateExponent = ((ASN1Integer) seq.getObjectAt(3)).getValue();
                BigInteger primeP = ((ASN1Integer) seq.getObjectAt(4)).getValue();
                BigInteger primeQ = ((ASN1Integer) seq.getObjectAt(5)).getValue();
                BigInteger primeExponentP = ((ASN1Integer) seq.getObjectAt(6)).getValue();
                BigInteger primeExponenetQ = ((ASN1Integer) seq.getObjectAt(7)).getValue();
                BigInteger crtCoefficient = ((ASN1Integer) seq.getObjectAt(8)).getValue();
                if (!version.equals(VERSION)) {
                    throw new CryptoException(MessageFormat.format(res.getString("OpenSslVersionIncorrect.exception.message"), "" + VERSION.intValue(), "" + version.intValue()));
                }
                RSAPrivateCrtKeySpec rsaPrivateCrtKeySpec = new RSAPrivateCrtKeySpec(modulus, publicExponent, privateExponent, primeP, primeQ, primeExponentP, primeExponenetQ, crtCoefficient);
                KeyFactory keyFactory = KeyFactory.getInstance("RSA");
                return keyFactory.generatePrivate(rsaPrivateCrtKeySpec);
            } else if (seq.size() == 6) {
                // DSA private key
                BigInteger version = ((ASN1Integer) seq.getObjectAt(0)).getValue();
                BigInteger primeModulusP = ((ASN1Integer) seq.getObjectAt(1)).getValue();
                BigInteger primeQ = ((ASN1Integer) seq.getObjectAt(2)).getValue();
                BigInteger generatorG = ((ASN1Integer) seq.getObjectAt(3)).getValue();
                // publicExponentY not req for pvk: sequence.getObjectAt(4);
                BigInteger secretExponentX = ((ASN1Integer) seq.getObjectAt(5)).getValue();
                if (!version.equals(VERSION)) {
                    throw new CryptoException(MessageFormat.format(res.getString("OpenSslVersionIncorrect.exception.message"), "" + VERSION.intValue(), "" + version.intValue()));
                }
                DSAPrivateKeySpec dsaPrivateKeySpec = new DSAPrivateKeySpec(secretExponentX, primeModulusP, primeQ, generatorG);
                KeyFactory keyFactory = KeyFactory.getInstance("DSA");
                return keyFactory.generatePrivate(dsaPrivateKeySpec);
            } else if (seq.size() >= 2) {
                // EC private key (RFC 5915)
                org.bouncycastle.asn1.sec.ECPrivateKey pKey = org.bouncycastle.asn1.sec.ECPrivateKey.getInstance(seq);
                AlgorithmIdentifier algId = new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, pKey.getParameters());
                PrivateKeyInfo privInfo = new PrivateKeyInfo(algId, pKey);
                return new JcaPEMKeyConverter().getPrivateKey(privInfo);
            } else {
                throw new CryptoException(MessageFormat.format(res.getString("OpenSslSequenceIncorrectSize.exception.message"), "" + seq.size()));
            }
        } else {
            throw new CryptoException(res.getString("OpenSslSequenceNotFound.exception.message"));
        }
    } catch (Exception ex) {
        throw new CryptoException(res.getString("NoLoadOpenSslPrivateKey.exception.message"), ex);
    }
}
Also used : RSAPrivateCrtKeySpec(java.security.spec.RSAPrivateCrtKeySpec) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) PemInfo(org.kse.utilities.pem.PemInfo) JcaPEMKeyConverter(org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) CryptoException(org.kse.crypto.CryptoException) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) DSAPrivateKeySpec(java.security.spec.DSAPrivateKeySpec) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) ByteArrayInputStream(java.io.ByteArrayInputStream) BigInteger(java.math.BigInteger) CryptoException(org.kse.crypto.CryptoException) ASN1Primitive(org.bouncycastle.asn1.ASN1Primitive) KeyFactory(java.security.KeyFactory) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo)

Aggregations

ASN1Integer (org.bouncycastle.asn1.ASN1Integer)213 ASN1Integer (com.unboundid.asn1.ASN1Integer)96 ASN1Sequence (com.unboundid.asn1.ASN1Sequence)94 ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)91 IOException (java.io.IOException)89 DERSequence (org.bouncycastle.asn1.DERSequence)89 ASN1Integer (com.github.zhenwei.core.asn1.ASN1Integer)86 BigInteger (java.math.BigInteger)86 ASN1OctetString (com.unboundid.asn1.ASN1OctetString)80 ASN1Element (com.unboundid.asn1.ASN1Element)69 Test (org.testng.annotations.Test)63 ArrayList (java.util.ArrayList)50 ASN1EncodableVector (com.github.zhenwei.core.asn1.ASN1EncodableVector)49 DERSequence (com.github.zhenwei.core.asn1.DERSequence)47 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)47 DEROctetString (org.bouncycastle.asn1.DEROctetString)38 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)35 ASN1InputStream (org.bouncycastle.asn1.ASN1InputStream)28 ASN1Encodable (org.bouncycastle.asn1.ASN1Encodable)27 AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)27