org.bouncycastle.asn1.DLSequence Java Examples

The following examples show how to use org.bouncycastle.asn1.DLSequence. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DSSASN1Utils.java    From dss with GNU Lesser General Public License v2.1 7 votes vote down vote up
public static Map<String, String> get(final X500Principal x500Principal) {
	Map<String, String> treeMap = new HashMap<>();
	final byte[] encoded = x500Principal.getEncoded();
	final ASN1Sequence asn1Sequence = ASN1Sequence.getInstance(encoded);
	final ASN1Encodable[] asn1Encodables = asn1Sequence.toArray();
	for (final ASN1Encodable asn1Encodable : asn1Encodables) {

		final DLSet dlSet = (DLSet) asn1Encodable;
		for (int ii = 0; ii < dlSet.size(); ii++) {

			final DLSequence dlSequence = (DLSequence) dlSet.getObjectAt(ii);
			if (dlSequence.size() != 2) {

				throw new DSSException("The DLSequence must contains exactly 2 elements.");
			}
			final ASN1Encodable asn1EncodableAttributeType = dlSequence.getObjectAt(0);
			final String stringAttributeType = getString(asn1EncodableAttributeType);
			final ASN1Encodable asn1EncodableAttributeValue = dlSequence.getObjectAt(1);
			final String stringAttributeValue = getString(asn1EncodableAttributeValue);
			treeMap.put(stringAttributeType, stringAttributeValue);
		}
	}
	return treeMap;
}
 
Example #2
Source File: BouncyCastleCrypto.java    From fabric-api-archive with Apache License 2.0 6 votes vote down vote up
@Override
public boolean verify(byte[] hash, byte[] signature, byte[] publicKey) {
    ASN1InputStream asn1 = new ASN1InputStream(signature);
    try {
        ECDSASigner signer = new ECDSASigner();
        signer.init(false, new ECPublicKeyParameters(curve.getCurve().decodePoint(publicKey), domain));

        DLSequence seq = (DLSequence) asn1.readObject();
        BigInteger r = ((ASN1Integer) seq.getObjectAt(0)).getPositiveValue();
        BigInteger s = ((ASN1Integer) seq.getObjectAt(1)).getPositiveValue();
        return signer.verifySignature(hash, r, s);
    } catch (Exception e) {
        return false;
    } finally {
        try {
            asn1.close();
        } catch (IOException ignored) {
        }
    }
}
 
Example #3
Source File: XmppDomainVerifier.java    From Conversations with GNU General Public License v3.0 6 votes vote down vote up
private static Pair<String, String> parseOtherName(byte[] otherName) {
    try {
        ASN1Primitive asn1Primitive = ASN1Primitive.fromByteArray(otherName);
        if (asn1Primitive instanceof DERTaggedObject) {
            ASN1Primitive inner = ((DERTaggedObject) asn1Primitive).getObject();
            if (inner instanceof DLSequence) {
                DLSequence sequence = (DLSequence) inner;
                if (sequence.size() >= 2 && sequence.getObjectAt(1) instanceof DERTaggedObject) {
                    String oid = sequence.getObjectAt(0).toString();
                    ASN1Primitive value = ((DERTaggedObject) sequence.getObjectAt(1)).getObject();
                    if (value instanceof DERUTF8String) {
                        return new Pair<>(oid, ((DERUTF8String) value).getString());
                    } else if (value instanceof DERIA5String) {
                        return new Pair<>(oid, ((DERIA5String) value).getString());
                    }
                }
            }
        }
        return null;
    } catch (IOException e) {
        return null;
    }
}
 
Example #4
Source File: XmppDomainVerifier.java    From Pix-Art-Messenger with GNU General Public License v3.0 6 votes vote down vote up
private static Pair<String, String> parseOtherName(byte[] otherName) {
    try {
        ASN1Primitive asn1Primitive = ASN1Primitive.fromByteArray(otherName);
        if (asn1Primitive instanceof DERTaggedObject) {
            ASN1Primitive inner = ((DERTaggedObject) asn1Primitive).getObject();
            if (inner instanceof DLSequence) {
                DLSequence sequence = (DLSequence) inner;
                if (sequence.size() >= 2 && sequence.getObjectAt(1) instanceof DERTaggedObject) {
                    String oid = sequence.getObjectAt(0).toString();
                    ASN1Primitive value = ((DERTaggedObject) sequence.getObjectAt(1)).getObject();
                    if (value instanceof DERUTF8String) {
                        return new Pair<>(oid, ((DERUTF8String) value).getString());
                    } else if (value instanceof DERIA5String) {
                        return new Pair<>(oid, ((DERIA5String) value).getString());
                    }
                }
            }
        }
        return null;
    } catch (IOException e) {
        return null;
    }
}
 
Example #5
Source File: BouncyCastleCrypto.java    From fabric-api with Apache License 2.0 6 votes vote down vote up
@Override
public boolean verify(byte[] hash, byte[] signature, byte[] publicKey) {
    ASN1InputStream asn1 = new ASN1InputStream(signature);
    try {
        ECDSASigner signer = new ECDSASigner();
        signer.init(false, new ECPublicKeyParameters(curve.getCurve().decodePoint(publicKey), domain));

        DLSequence seq = (DLSequence) asn1.readObject();
        BigInteger r = ((ASN1Integer) seq.getObjectAt(0)).getPositiveValue();
        BigInteger s = ((ASN1Integer) seq.getObjectAt(1)).getPositiveValue();
        return signer.verifySignature(hash, r, s);
    } catch (Exception e) {
        return false;
    } finally {
        try {
            asn1.close();
        } catch (IOException ignored) {
        }
    }
}
 
Example #6
Source File: KerberosRelevantAuthData.java    From jcifs-ng with GNU Lesser General Public License v2.1 6 votes vote down vote up
public KerberosRelevantAuthData ( byte[] token, Map<Integer, KerberosKey> keys ) throws PACDecodingException {
    DLSequence authSequence;
    try {
        try ( ASN1InputStream stream = new ASN1InputStream(new ByteArrayInputStream(token)) ) {
            authSequence = ASN1Util.as(DLSequence.class, stream);
        }
    }
    catch ( IOException e ) {
        throw new PACDecodingException("Malformed kerberos ticket", e);
    }

    this.authorizations = new ArrayList<>();
    Enumeration<?> authElements = authSequence.getObjects();
    while ( authElements.hasMoreElements() ) {
        DLSequence authElement = ASN1Util.as(DLSequence.class, authElements);
        ASN1Integer authType = ASN1Util.as(ASN1Integer.class, ASN1Util.as(DERTaggedObject.class, authElement, 0));
        DEROctetString authData = ASN1Util.as(DEROctetString.class, ASN1Util.as(DERTaggedObject.class, authElement, 1));

        this.authorizations.addAll(KerberosAuthData.parse(authType.getValue().intValue(), authData.getOctets(), keys));
    }
}
 
Example #7
Source File: TestCertificateSignRequest.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
private void verifyServiceId(Extensions extensions) {
  GeneralNames gns =
      GeneralNames.fromExtensions(
          extensions, Extension.subjectAlternativeName);
  GeneralName[] names = gns.getNames();
  for(int i=0; i < names.length; i++) {
    if(names[i].getTagNo() == GeneralName.otherName) {
      ASN1Encodable asn1Encodable = names[i].getName();
      Iterator iterator = ((DLSequence) asn1Encodable).iterator();
      while (iterator.hasNext()) {
        Object o = iterator.next();
        if (o instanceof ASN1ObjectIdentifier) {
          String oid = o.toString();
          Assert.assertEquals(oid, "2.16.840.1.113730.3.1.34");
        }
        if (o instanceof DERTaggedObject) {
          String serviceName = ((DERTaggedObject)o).getObject().toString();
          Assert.assertEquals(serviceName, "OzoneMarketingCluster003");
        }
      }
    }
  }
}
 
Example #8
Source File: XmppDomainVerifier.java    From ComplianceTester with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private static OtherName parseOtherName(byte[] otherName) {
    try {
        ASN1Primitive asn1Primitive = ASN1Primitive.fromByteArray(otherName);
        if (asn1Primitive instanceof DERTaggedObject) {
            ASN1Primitive inner = ((DERTaggedObject) asn1Primitive).getObject();
            if (inner instanceof DLSequence) {
                DLSequence sequence = (DLSequence) inner;
                if (sequence.size() >= 2 && sequence.getObjectAt(1) instanceof DERTaggedObject) {
                    String oid = sequence.getObjectAt(0).toString();
                    ASN1Primitive value = ((DERTaggedObject) sequence.getObjectAt(1)).getObject();
                    if (value instanceof DERUTF8String) {
                        return new OtherName(oid, ((DERUTF8String) value).getString());
                    } else if (value instanceof DERIA5String) {
                        return new OtherName(oid, ((DERIA5String) value).getString());
                    }
                }
            }
        }
        return null;
    } catch (IOException e) {
        return null;
    }
}
 
Example #9
Source File: BasicCertificate.java    From signer with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 *     *
 * @return the authority key identifier of a certificate
 * 
 */
public String getAuthorityKeyIdentifier() {
    // TODO - Precisa validar este metodo com a RFC
	try {
		DLSequence sequence = (DLSequence) getExtensionValue(Extension.authorityKeyIdentifier.getId());
		if (sequence == null || sequence.size() == 0) {
			return null;
		}
		DERTaggedObject taggedObject = (DERTaggedObject) sequence.getObjectAt(0);
		DEROctetString oct = (DEROctetString) taggedObject.getObject();
		return toString(oct.getOctets());
	} catch (Exception error) {
		logger.info(error.getMessage());
		return null;
	}
		
}
 
Example #10
Source File: LPA.java    From signer with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void parse(ASN1Primitive derObject) {
    ASN1Sequence sequence = ASN1Object.getDERSequence(derObject);
    ASN1Primitive firstObject = sequence.getObjectAt(0).toASN1Primitive();
    this.version = new Version();
    int indice = 0;
    if (firstObject instanceof ASN1Integer) {
        this.version.parse(firstObject);
        indice++;
    }
    ASN1Primitive policyInfos = sequence.getObjectAt(indice).toASN1Primitive();
    DLSequence policyInfosSequence = (DLSequence) policyInfos;
    if (policyInfosSequence != null && policyInfosSequence.size() > 0) {
        this.policyInfos = new ArrayList<>();
        for (int i = 0; i < policyInfosSequence.size(); i++) {
            PolicyInfo policyInfo = new PolicyInfo();
            policyInfo.parse(policyInfosSequence.getObjectAt(i).toASN1Primitive());
            this.policyInfos.add(policyInfo);
        }
    }
    this.nextUpdate = new GeneralizedTime();
    this.nextUpdate.parse(sequence.getObjectAt(indice + 1).toASN1Primitive());
}
 
Example #11
Source File: OcspUtils.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
private static <T> T findObject(DLSequence sequence, ASN1ObjectIdentifier oid, Class<T> type) {
    for (ASN1Encodable element : sequence) {
        if (!(element instanceof DLSequence)) {
            continue;
        }

        DLSequence subSequence = (DLSequence) element;
        if (subSequence.size() != 2) {
            continue;
        }

        ASN1Encodable key = subSequence.getObjectAt(0);
        ASN1Encodable value = subSequence.getObjectAt(1);

        if (key.equals(oid) && type.isInstance(value)) {
            return type.cast(value);
        }
    }

    return null;
}
 
Example #12
Source File: LPA.java    From signer with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void parse(ASN1Primitive derObject) {
    ASN1Sequence sequence = ASN1Object.getDERSequence(derObject);
    ASN1Primitive policyInfos = sequence.getObjectAt(0).toASN1Primitive();
    DLSequence policyInfosSequence = (DLSequence) policyInfos;
    if (policyInfosSequence != null && policyInfosSequence.size() > 0) {
        this.policyInfos = new ArrayList<>();
        for (int i = 0; i < policyInfosSequence.size(); i++) {
            PolicyInfo policyInfo = new PolicyInfo();
            policyInfo.parse(policyInfosSequence.getObjectAt(i).toASN1Primitive());
            this.policyInfos.add(policyInfo);
        }
    }
    this.nextUpdate = new Time();
    this.nextUpdate.parse(sequence.getObjectAt(1).toASN1Primitive());
}
 
Example #13
Source File: KerberosRelevantAuthData.java    From jcifs with GNU Lesser General Public License v2.1 6 votes vote down vote up
public KerberosRelevantAuthData ( byte[] token, Map<Integer, KerberosKey> keys ) throws PACDecodingException {
    DLSequence authSequence;
    try {
        try ( ASN1InputStream stream = new ASN1InputStream(new ByteArrayInputStream(token)) ) {
            authSequence = ASN1Util.as(DLSequence.class, stream);
        }
    }
    catch ( IOException e ) {
        throw new PACDecodingException("Malformed kerberos ticket", e);
    }

    this.authorizations = new ArrayList<>();
    Enumeration<?> authElements = authSequence.getObjects();
    while ( authElements.hasMoreElements() ) {
        DLSequence authElement = ASN1Util.as(DLSequence.class, authElements);
        ASN1Integer authType = ASN1Util.as(ASN1Integer.class, ASN1Util.as(DERTaggedObject.class, authElement, 0));
        DEROctetString authData = ASN1Util.as(DEROctetString.class, ASN1Util.as(DERTaggedObject.class, authElement, 1));

        this.authorizations.addAll(KerberosAuthData.parse(authType.getValue().intValue(), authData.getOctets(), keys));
    }
}
 
Example #14
Source File: ECKey.java    From bushido-java-core with GNU General Public License v3.0 5 votes vote down vote up
public boolean verify(byte[] message, byte[] signature) throws Exception
{
    ASN1InputStream asn1 = new ASN1InputStream(signature);
    ECDSASigner signer = new ECDSASigner();
    //not for signing...
    signer.init(false, new ECPublicKeyParameters(curve.getCurve().decodePoint(pub), params));
    DLSequence seq = (DLSequence) asn1.readObject();
    BigInteger r = ((ASN1Integer) seq.getObjectAt(0)).getPositiveValue();
    BigInteger s = ((ASN1Integer) seq.getObjectAt(1)).getPositiveValue();
    return signer.verifySignature(message, r, s);
}
 
Example #15
Source File: CryptoDataLoader.java    From certificate-transparency-java with Apache License 2.0 5 votes vote down vote up
/**
 * Parses the beginning of a key, and determines the key algorithm (RSA or EC) based on the OID
 */
private static String determineKeyAlg(byte[] keyBytes) {
  ASN1Sequence seq = ASN1Sequence.getInstance(keyBytes);
  DLSequence seq1 = (DLSequence) seq.getObjects().nextElement();
  ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) seq1.getObjects().nextElement();
  if (PKCSObjectIdentifiers.rsaEncryption.equals(oid)) {
    return "RSA";
  } else if (X9ObjectIdentifiers.id_ecPublicKey.equals(oid)) {
    return "EC";
  } else {
    throw new IllegalArgumentException("Unsupported key type: " + oid);
  }
}
 
Example #16
Source File: SFTrustManager.java    From snowflake-jdbc with Apache License 2.0 5 votes vote down vote up
/**
 * Decodes OCSP Response Cache key from JSON
 *
 * @param elem A JSON element
 * @return OcspResponseCacheKey object
 */
private static SFPair<OcspResponseCacheKey, SFPair<Long, String>>
decodeCacheFromJSON(Map.Entry<String, JsonNode> elem) throws IOException
{
  long currentTimeSecond = new Date().getTime() / 1000;
  byte[] certIdDer = Base64.decodeBase64(elem.getKey());
  DLSequence rawCertId = (DLSequence) ASN1ObjectIdentifier.fromByteArray(certIdDer);
  ASN1Encodable[] rawCertIdArray = rawCertId.toArray();
  byte[] issuerNameHashDer = ((DEROctetString) rawCertIdArray[1]).getEncoded();
  byte[] issuerKeyHashDer = ((DEROctetString) rawCertIdArray[2]).getEncoded();
  BigInteger serialNumber = ((ASN1Integer) rawCertIdArray[3]).getValue();

  OcspResponseCacheKey k = new OcspResponseCacheKey(
      issuerNameHashDer, issuerKeyHashDer, serialNumber);

  JsonNode ocspRespBase64 = elem.getValue();
  if (!ocspRespBase64.isArray() || ocspRespBase64.size() != 2)
  {
    LOGGER.debug("Invalid cache file format. Ignored");
    return null;
  }
  long producedAt = ocspRespBase64.get(0).asLong();
  String ocspResp = ocspRespBase64.get(1).asText();

  if (currentTimeSecond - CACHE_EXPIRATION_IN_SECONDS <= producedAt)
  {
    // add cache
    return SFPair.of(k, SFPair.of(producedAt, ocspResp));
  }
  else
  {
    // delete cache
    return SFPair.of(k, SFPair.of(producedAt, null));
  }
}
 
Example #17
Source File: SFTrustManager.java    From snowflake-jdbc with Apache License 2.0 5 votes vote down vote up
/**
 * Gets OCSP URLs associated with the certificate.
 *
 * @param bcCert Bouncy Castle Certificate
 * @return a set of OCSP URLs
 */
private Set<String> getOcspUrls(Certificate bcCert) throws IOException
{
  TBSCertificate bcTbsCert = bcCert.getTBSCertificate();
  Extensions bcExts = bcTbsCert.getExtensions();
  if (bcExts == null)
  {
    throw new IOException("Failed to get Tbs Certificate.");
  }

  Set<String> ocsp = new HashSet<>();
  for (Enumeration<?> en = bcExts.oids(); en.hasMoreElements(); )
  {
    ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) en.nextElement();
    Extension bcExt = bcExts.getExtension(oid);
    if (Extension.authorityInfoAccess.equals(bcExt.getExtnId()))
    {
      // OCSP URLS are included in authorityInfoAccess
      DLSequence seq = (DLSequence) bcExt.getParsedValue();
      for (ASN1Encodable asn : seq)
      {
        ASN1Encodable[] pairOfAsn = ((DLSequence) asn).toArray();
        if (pairOfAsn.length == 2)
        {
          ASN1ObjectIdentifier key = (ASN1ObjectIdentifier) pairOfAsn[0];
          if (OIDocsp.equals(key))
          {
            // ensure OCSP and not CRL
            GeneralName gn = GeneralName.getInstance(pairOfAsn[1]);
            ocsp.add(gn.getName().toString());
          }
        }
      }
    }
  }
  return ocsp;
}
 
Example #18
Source File: Asn1.java    From UAF with Apache License 2.0 5 votes vote down vote up
/**
 * DER - From byte[] to Big Integer rs
 * UAF_ALG_SIGN_SECP256K1_ECDSA_SHA256_DER 0x06 DER [ITU-X690-2008] encoded
 * ECDSA signature [RFC5480] on the secp256k1 curve. I.e. a DER encoded
 * SEQUENCE { r INTEGER, s INTEGER }
 * 
 * @param signature
 * @return
 * @throws IOException
 */
public static BigInteger[] decodeToBigIntegerArray(byte[] signature)
		throws IOException {
	ASN1InputStream decoder = new ASN1InputStream(signature);
	DLSequence seq = (DLSequence) decoder.readObject();
	ASN1Integer r = (ASN1Integer) seq.getObjectAt(0);
	ASN1Integer s = (ASN1Integer) seq.getObjectAt(1);
	decoder.close();
	BigInteger[] ret = new BigInteger[2];
	ret[0] = r.getPositiveValue();
	ret[1] = s.getPositiveValue();
	return ret;
}
 
Example #19
Source File: DSSASN1Utils.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Computes SHA-1 hash of the given {@code publicKey}'s
 * @param publicKey {@link PublicKey} to compute digest for
 * @return byte array of public key's SHA-1 hash
 */
public static byte[] computeSkiFromCertPublicKey(final PublicKey publicKey) {
	try {
		DLSequence seq = (DLSequence) ASN1Primitive.fromByteArray(publicKey.getEncoded());
		DERBitString item = (DERBitString) seq.getObjectAt(1);
		return DSSUtils.digest(DigestAlgorithm.SHA1, item.getOctets());
	} catch (IOException e) {
		throw new DSSException(e);
	}
}
 
Example #20
Source File: KerberosApRequest.java    From jcifs with GNU Lesser General Public License v2.1 4 votes vote down vote up
public KerberosApRequest ( byte[] token, KerberosKey[] keys ) throws PACDecodingException {
    if ( token.length <= 0 )
        throw new PACDecodingException("Empty kerberos ApReq");

    DLSequence sequence;
    try {
        try ( ASN1InputStream stream = new ASN1InputStream(new ByteArrayInputStream(token)) ) {
            sequence = ASN1Util.as(DLSequence.class, stream);
        }
    }
    catch ( IOException e ) {
        throw new PACDecodingException("Malformed Kerberos Ticket", e);
    }

    Enumeration<?> fields = sequence.getObjects();
    while ( fields.hasMoreElements() ) {
        ASN1TaggedObject tagged = ASN1Util.as(ASN1TaggedObject.class, fields.nextElement());
        switch ( tagged.getTagNo() ) {
        case 0:
            ASN1Integer pvno = ASN1Util.as(ASN1Integer.class, tagged);
            if ( !pvno.getValue().equals(new BigInteger(KerberosConstants.KERBEROS_VERSION)) ) {
                throw new PACDecodingException("Invalid kerberos version");
            }
            break;
        case 1:
            ASN1Integer msgType = ASN1Util.as(ASN1Integer.class, tagged);
            if ( !msgType.getValue().equals(new BigInteger(KerberosConstants.KERBEROS_AP_REQ)) )
                throw new PACDecodingException("Invalid kerberos request");
            break;
        case 2:
            DERBitString bitString = ASN1Util.as(DERBitString.class, tagged);
            this.apOptions = bitString.getBytes()[ 0 ];
            break;
        case 3:
            DERApplicationSpecific derTicket = ASN1Util.as(DERApplicationSpecific.class, tagged);
            if ( !derTicket.isConstructed() )
                throw new PACDecodingException("Malformed Kerberos Ticket");
            this.ticket = new KerberosTicket(derTicket.getContents(), this.apOptions, keys);
            break;
        case 4:
            // Let's ignore this for now
            break;
        default:
            throw new PACDecodingException("Invalid field in kerberos ticket");
        }
    }
}
 
Example #21
Source File: EOSFormatter.java    From eosio-java with MIT License 4 votes vote down vote up
/**
 * This method converts a signature to a EOS compliant form.  The signature to be converted must
 * be an The ECDSA signature that is a DER encoded ASN.1 sequence of two integer fields (see
 * ECDSA-Sig-Value in rfc3279 section 2.2.3).
 *
 * The DER encoded ECDSA signature follows the following format: Byte 1 - Sequence (Should be
 * 30) Byte 2 - Signature length Byte 3 - R Marker (0x02) Byte 4 - R length Bytes 5 to 37 or 38-
 * R Byte After R - S Marker (0x02) Byte After S Marker - S Length Bytes After S Length - S
 * (always 32-33 bytes) Byte Final - Hash Type
 *
 * @param signatureDER ECDSA DER encoded signature as byte array
 * @param signableTransaction Transaction in signable format
 * @param publicKeyPEM public key in PEM format
 * @return EOS format of signature
 * @throws EOSFormatterError if DER conversion to EOS format fails.
 */
@NotNull
public static String convertDERSignatureToEOSFormat(@NotNull byte[] signatureDER,
        @NotNull byte[] signableTransaction, @NotNull String publicKeyPEM)
        throws EOSFormatterError {
    String eosFormattedSignature = "";

    try (ASN1InputStream asn1InputStream = new ASN1InputStream(signatureDER)) {

        PEMProcessor publicKey = new PEMProcessor(publicKeyPEM);
        AlgorithmEmployed algorithmEmployed = publicKey.getAlgorithm();
        byte[] keyData = publicKey.getKeyData();
        DLSequence sequence = (DLSequence) asn1InputStream.readObject();
        BigInteger r = ((ASN1Integer) sequence.getObjectAt(0)).getPositiveValue();
        BigInteger s = ((ASN1Integer) sequence.getObjectAt(1)).getPositiveValue();

        s = checkAndHandleLowS(s, algorithmEmployed);

        /*
        Get recovery ID.  This is the index of the public key (0-3) that represents the
        expected public key used to sign the transaction.
         */
        int recoverId = getRecoveryId(r, s, Sha256Hash.of(signableTransaction), keyData,
                algorithmEmployed);

        if (recoverId < 0) {
            throw new IllegalStateException(
                    ErrorConstants.COULD_NOT_RECOVER_PUBLIC_KEY_FROM_SIG);
        }

        //Add RecoveryID + 27 + 4 to create the header byte
        recoverId += VALUE_TO_ADD_TO_SIGNATURE_HEADER;
        byte headerByte = ((Integer) recoverId).byteValue();



        byte[] decodedSignature = Bytes
                .concat(new byte[]{headerByte}, org.bitcoinj.core.Utils.bigIntegerToBytes(r,EXPECTED_R_OR_S_LENGTH), org.bitcoinj.core.Utils.bigIntegerToBytes(s,EXPECTED_R_OR_S_LENGTH));
        if (algorithmEmployed.equals(AlgorithmEmployed.SECP256K1) &&
                !isCanonical(decodedSignature)) {
            throw new IllegalArgumentException(ErrorConstants.NON_CANONICAL_SIGNATURE);
        }

        //Add checksum to signature
        byte[] signatureWithCheckSum;
        String signaturePrefix;
        switch (algorithmEmployed) {
            case SECP256R1:
                signatureWithCheckSum = addCheckSumToSignature(decodedSignature,
                        SECP256R1_AND_PRIME256V1_CHECKSUM_VALIDATION_SUFFIX.getBytes());
                signaturePrefix = PATTERN_STRING_EOS_PREFIX_SIG_R1;
                break;
            case SECP256K1:
                signatureWithCheckSum = addCheckSumToSignature(decodedSignature,
                        SECP256K1_CHECKSUM_VALIDATION_SUFFIX.getBytes());
                signaturePrefix = PATTERN_STRING_EOS_PREFIX_SIG_K1;
                break;
            default:
                throw new EOSFormatterError(ErrorConstants.UNSUPPORTED_ALGORITHM);

        }

        //Base58 encode signature and add pertinent EOS prefix
        eosFormattedSignature = signaturePrefix.concat(Base58.encode(signatureWithCheckSum));

    } catch (Exception e) {
        throw new EOSFormatterError(ErrorConstants.SIGNATURE_FORMATTING_ERROR, e);
    }

    return eosFormattedSignature;
}
 
Example #22
Source File: DSSASN1Utils.java    From dss with GNU Lesser General Public License v2.1 4 votes vote down vote up
public static String getUtf8String(final X500Principal x500Principal) {

		final byte[] encoded = x500Principal.getEncoded();
		final ASN1Sequence asn1Sequence = ASN1Sequence.getInstance(encoded);
		final ASN1Encodable[] asn1Encodables = asn1Sequence.toArray();
		final StringBuilder stringBuilder = new StringBuilder();
		/**
		 * RFC 4514 LDAP: Distinguished Names
		 * 2.1. Converting the RDNSequence
		 *
		 * If the RDNSequence is an empty sequence, the result is the empty or
		 * zero-length string.
		 *
		 * Otherwise, the output consists of the string encodings of each
		 * RelativeDistinguishedName in the RDNSequence (according to Section
		 * 2.2), starting with the last element of the sequence and moving
		 * backwards toward the first.
		 * ...
		 */
		for (int ii = asn1Encodables.length - 1; ii >= 0; ii--) {

			final ASN1Encodable asn1Encodable = asn1Encodables[ii];

			final DLSet dlSet = (DLSet) asn1Encodable;
			for (int jj = 0; jj < dlSet.size(); jj++) {

				final DLSequence dlSequence = (DLSequence) dlSet.getObjectAt(jj);
				if (dlSequence.size() != 2) {

					throw new DSSException("The DLSequence must contains exactly 2 elements.");
				}
				final ASN1Encodable attributeType = dlSequence.getObjectAt(0);
				final ASN1Encodable attributeValue = dlSequence.getObjectAt(1);
				String string = getString(attributeValue);

				/**
				 * RFC 4514 LDAP: Distinguished Names
				 * ...
				 * Other characters may be escaped.
				 *
				 * Each octet of the character to be escaped is replaced by a backslash
				 * and two hex digits, which form a single octet in the code of the
				 * character. Alternatively, if and only if the character to be escaped
				 * is one of
				 *
				 * ' ', '"', '#', '+', ',', ';', '<', '=', '>', or '\'
				 * (U+0020, U+0022, U+0023, U+002B, U+002C, U+003B,
				 * U+003C, U+003D, U+003E, U+005C, respectively)
				 *
				 * it can be prefixed by a backslash ('\' U+005C).
				 */
				string = Rdn.escapeValue(string);
				if (stringBuilder.length() != 0) {
					stringBuilder.append(',');
				}
				stringBuilder.append(attributeType).append('=').append(string);
			}
		}
		return stringBuilder.toString();
	}
 
Example #23
Source File: KerberosApRequest.java    From jcifs-ng with GNU Lesser General Public License v2.1 4 votes vote down vote up
public KerberosApRequest ( byte[] token, KerberosKey[] keys ) throws PACDecodingException {
    if ( token.length <= 0 )
        throw new PACDecodingException("Empty kerberos ApReq");

    DLSequence sequence;
    try {
        try ( ASN1InputStream stream = new ASN1InputStream(new ByteArrayInputStream(token)) ) {
            sequence = ASN1Util.as(DLSequence.class, stream);
        }
    }
    catch ( IOException e ) {
        throw new PACDecodingException("Malformed Kerberos Ticket", e);
    }

    Enumeration<?> fields = sequence.getObjects();
    while ( fields.hasMoreElements() ) {
        ASN1TaggedObject tagged = ASN1Util.as(ASN1TaggedObject.class, fields.nextElement());
        switch ( tagged.getTagNo() ) {
        case 0:
            ASN1Integer pvno = ASN1Util.as(ASN1Integer.class, tagged);
            if ( !pvno.getValue().equals(new BigInteger(KerberosConstants.KERBEROS_VERSION)) ) {
                throw new PACDecodingException("Invalid kerberos version");
            }
            break;
        case 1:
            ASN1Integer msgType = ASN1Util.as(ASN1Integer.class, tagged);
            if ( !msgType.getValue().equals(new BigInteger(KerberosConstants.KERBEROS_AP_REQ)) )
                throw new PACDecodingException("Invalid kerberos request");
            break;
        case 2:
            DERBitString bitString = ASN1Util.as(DERBitString.class, tagged);
            this.apOptions = bitString.getBytes()[ 0 ];
            break;
        case 3:
            DERApplicationSpecific derTicket = ASN1Util.as(DERApplicationSpecific.class, tagged);
            if ( !derTicket.isConstructed() )
                throw new PACDecodingException("Malformed Kerberos Ticket");
            this.ticket = new KerberosTicket(derTicket.getContents(), this.apOptions, keys);
            break;
        case 4:
            // Let's ignore this for now
            break;
        default:
            throw new PACDecodingException("Invalid field in kerberos ticket");
        }
    }
}
 
Example #24
Source File: SFTrustManager.java    From snowflake-jdbc with Apache License 2.0 4 votes vote down vote up
private boolean processOCSPBypassSSD(String ocsp_ssd, OcspResponseCacheKey cid, String hostname)
{
  try
  {
    /*
     * Get unverified part of the JWT to extract issuer.
     */
    SignedJWT jwt_unverified = SignedJWT.parse(ocsp_ssd);
    String jwt_issuer = (String) jwt_unverified.getHeader().getCustomParam("ssd_iss");
    String ssd_pubKey;

    if (jwt_issuer.equals("dep1"))
    {
      ssd_pubKey = ssdManager.getPubKey("dep1");
    }
    else
    {
      ssd_pubKey = ssdManager.getPubKey("dep2");
    }

    String publicKeyContent =
        ssd_pubKey.replaceAll("\\n", "").replace("-----BEGIN PUBLIC KEY-----", "").replace("-----END PUBLIC KEY-----", "");
    KeyFactory kf = KeyFactory.getInstance("RSA");
    X509EncodedKeySpec keySpecX509 = new X509EncodedKeySpec(Base64.decodeBase64(publicKeyContent));
    RSAPublicKey rsaPubKey = (RSAPublicKey) kf.generatePublic(keySpecX509);

    /*
     * Verify signature of the JWT Token
     * Verify time validity of the JWT Token (API does not do this)
     */
    SignedJWT jwt_token_verified = SignedJWT.parse(ocsp_ssd);
    JWSVerifier jwsVerifier = new RSASSAVerifier(rsaPubKey);
    if (jwt_token_verified.verify(jwsVerifier))
    {
      String sfc_endpoint = jwt_token_verified.getJWTClaimsSet().getStringClaim("sfcEndpoint");
      String jwt_certid = jwt_token_verified.getJWTClaimsSet().getStringClaim("certId");
      Date jwt_nbf = jwt_token_verified.getJWTClaimsSet().getNotBeforeTime();
      Date jwt_exp = jwt_token_verified.getJWTClaimsSet().getExpirationTime();

      long current_ts = System.currentTimeMillis();
      if (current_ts < jwt_exp.getTime() && current_ts >= jwt_nbf.getTime())
      {
        if (!sfc_endpoint.equals("*"))
        {
          /*
           * In case there are multiple hostnames
           * associated to the same account. The
           * code expects a space separated list
           * of all hostnames associated with this
           * account in sfcEndpoint field
           */

          String[] splitString = sfc_endpoint.split("\\s+");

          for (String s : splitString)
          {
            if (s.equals(hostname))
            {
              return true;
            }
          }
          return false;
        }
        /*
         * No In Band token can have > 7 days validity
         */
        if (jwt_exp.getTime() - jwt_nbf.getTime() > (7 * 24 * 60 * 60 * 1000))
        {
          return false;
        }
        byte[] jwt_certid_dec = Base64.decodeBase64(jwt_certid);
        DLSequence jwt_rawCertId = (DLSequence) ASN1ObjectIdentifier.fromByteArray(jwt_certid_dec);
        ASN1Encodable[] jwt_rawCertIdArray = jwt_rawCertId.toArray();
        byte[] issuerNameHashDer = ((DEROctetString) jwt_rawCertIdArray[1]).getEncoded();
        byte[] issuerKeyHashDer = ((DEROctetString) jwt_rawCertIdArray[2]).getEncoded();
        BigInteger serialNumber = ((ASN1Integer) jwt_rawCertIdArray[3]).getValue();

        OcspResponseCacheKey k = new OcspResponseCacheKey(
            issuerNameHashDer, issuerKeyHashDer, serialNumber);

        if (k.equals(cid))
        {
          LOGGER.debug("Found a Signed OCSP Bypass SSD for ceri id {}", cid);
          return true;
        }
        LOGGER.debug("Found invalid OCSP bypass for cert id {}", cid);
        return false;
      }
    }
    return false;
  }
  catch (Throwable ex)
  {
    LOGGER.debug("Failed to parse JWT Token, aborting");
    return false;
  }
}
 
Example #25
Source File: PolicyIssuerName.java    From signer with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public void parse(ASN1Primitive primitive) {
    if (primitive instanceof DLSequence) {
        DLSequence sequence = (DLSequence) primitive;
        ASN1Encodable asn1Encodable = sequence.getObjectAt(0);
        if (asn1Encodable instanceof DERTaggedObject) {
            DERTaggedObject derTaggedObject = (DERTaggedObject) asn1Encodable;
            ASN1Primitive object = derTaggedObject.getObject();
            if (object instanceof DEROctetString) {
                OctetString octetString = new OctetString();
                octetString.parse(object);
                this.issuerName = octetString.getValueUTF8();
            } else if (object instanceof DERSequence) {
                DERSequence sequence2 = (DERSequence) object;
                for (int i = 0; i < sequence2.size(); i++) {
                    ASN1Encodable obj = sequence2.getObjectAt(i);
                    if (obj instanceof DERSet) {
                        DERSet set = (DERSet) obj;
                        ASN1Encodable object2 = set.getObjectAt(0);
                        if (object2 instanceof DERSequence) {
                            DERSequence sequence3 = (DERSequence) object2;
                            ObjectIdentifier objectIdendifier = new ObjectIdentifier();
                            objectIdendifier.parse(sequence3.getObjectAt(0).toASN1Primitive());
                            String name = null;
                            ASN1Encodable object3 = sequence3.getObjectAt(1);
                            if (object3 instanceof DERPrintableString) {
                                name = ((DERPrintableString) object3).getString();
                            } else if (object3 instanceof DERUTF8String) {
                                name = ((DERUTF8String) object3).getString();
                            } else {
                                System.out.println(policyMessagesBundle.getString("error.not.recognized.object",object3.getClass(),object3.toString()));
                            }
                            if (this.issuerNames == null) {
                                this.issuerNames = new HashMap<ObjectIdentifier, String>();
                            }
                            this.issuerNames.put(objectIdendifier, name);
                        }
                    }
                }
            }
        }
    }
}
 
Example #26
Source File: AlgorithmIdentifier.java    From signer with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public void parse(ASN1Primitive derObject) {
    this.algorithm = new ObjectIdentifier();
    DLSequence derSequence = (DLSequence) derObject;
    this.algorithm.parse(derSequence.getObjectAt(0).toASN1Primitive());
}
 
Example #27
Source File: BasicCertificate.java    From signer with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * returns the ICP-BRASIL Certificate Level(A1, A2, A3, A4, S1, S2, S3,
 * S4).<br>
 * DOC-ICP-04 Returns the <b>null</b> value if the CertificatePolicies is
 * NOT present.
 *
 * @return String Certificate level
 */
public String getCertificateLevel() {
    try {
        DLSequence sequence = (DLSequence) getExtensionValue(Extension.certificatePolicies.getId());
        if (sequence != null) {
            for (int pos = 0; pos < sequence.size(); pos++) {
                DLSequence sequence2 = (DLSequence) sequence.getObjectAt(pos);
                ASN1ObjectIdentifier policyIdentifier = (ASN1ObjectIdentifier) sequence2.getObjectAt(0);
                PolicyInformation policyInformation = new PolicyInformation(policyIdentifier);
                String id = policyInformation.getPolicyIdentifier().getId();
                if (id == null) {
                    continue;
                }

                if (id.startsWith(OID_A1_CERTIFICATE)) {
                    return "A1";
                }
                if (id.startsWith(OID_A2_CERTIFICATE)) {
                    return "A2";
                }
                if (id.startsWith(OID_A3_CERTIFICATE)) {
                    return "A3";
                }
                if (id.startsWith(OID_A4_CERTIFICATE)) {
                    return "A4";
                }
                if (id.startsWith(OID_S1_CERTIFICATE)) {
                    return "S1";
                }
                if (id.startsWith(OID_S2_CERTIFICATE)) {
                    return "S2";
                }
                if (id.startsWith(OID_S3_CERTIFICATE)) {
                    return "S3";
                }
                if (id.startsWith(OID_S4_CERTIFICATE)) {
                    return "S4";
                }
            }
        }
        return null;
    } catch (Exception e) {
    	logger.info(e.getMessage());
        e.printStackTrace();
        return null;
    }
}
 
Example #28
Source File: ASN1Util.java    From jcifs with GNU Lesser General Public License v2.1 2 votes vote down vote up
/**
 * 
 * @param type
 * @param sequence
 * @param index
 * @return sequence element cast to type
 * @throws PACDecodingException
 */
public static <T extends ASN1Primitive> T as ( Class<T> type, DLSequence sequence, int index ) throws PACDecodingException {
    return as(type, sequence.getObjectAt(index));
}
 
Example #29
Source File: ASN1Util.java    From jcifs-ng with GNU Lesser General Public License v2.1 2 votes vote down vote up
/**
 * 
 * @param type
 * @param sequence
 * @param index
 * @return sequence element cast to type
 * @throws PACDecodingException
 */
public static <T extends ASN1Primitive> T as ( Class<T> type, DLSequence sequence, int index ) throws PACDecodingException {
    return as(type, sequence.getObjectAt(index));
}