org.bouncycastle.asn1.ASN1Integer Java Examples

The following examples show how to use org.bouncycastle.asn1.ASN1Integer. 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: SigningCertificate.java    From signer with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public Attribute getValue() {
    try {
        X509Certificate cert = (X509Certificate) certificates[0];
        Digest digest = DigestFactory.getInstance().factoryDefault();
        digest.setAlgorithm(DigestAlgorithmEnum.SHA_1);
        byte[] hash = digest.digest(cert.getEncoded());
        X500Name dirName = new X500Name(cert.getSubjectDN().getName());
        GeneralName name = new GeneralName(dirName);
        GeneralNames issuer = new GeneralNames(name);
        ASN1Integer serial = new ASN1Integer(cert.getSerialNumber());
        IssuerSerial issuerSerial = new IssuerSerial(issuer, serial);
        ESSCertID essCertId = new ESSCertID(hash, issuerSerial);
        return new Attribute(new ASN1ObjectIdentifier(identifier), new DERSet(new DERSequence(new ASN1Encodable[]{new DERSequence(essCertId), new DERSequence(DERNull.INSTANCE)})));

    } catch (CertificateEncodingException ex) {
        throw new SignerException(ex.getMessage());
    }
}
 
Example #2
Source File: BouncyCastleCrypto.java    From fabric-api-archive with Apache License 2.0 6 votes vote down vote up
@Override
public byte[] sign(byte[] hash, byte[] privateKey) {
    ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest()));
    signer.init(true, new ECPrivateKeyParameters(new BigInteger(privateKey), domain));
    BigInteger[] signature = signer.generateSignature(hash);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        DERSequenceGenerator seq = new DERSequenceGenerator(baos);
        seq.addObject(new ASN1Integer(signature[0]));
        seq.addObject(new ASN1Integer(toCanonicalS(signature[1])));
        seq.close();
        return baos.toByteArray();
    } catch (IOException e) {
        return new byte[0];
    }
}
 
Example #3
Source File: SignTest.java    From web3sdk with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #4
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 #5
Source File: SFTrustManager.java    From snowflake-jdbc with Apache License 2.0 6 votes vote down vote up
/**
 * Convert cache key to base64 encoded
 * cert id
 *
 * @param ocsp_cache_key Cache key to encode
 */
private static String encodeCacheKey(OcspResponseCacheKey ocsp_cache_key)
{
  try
  {
    DigestCalculator digest = new SHA1DigestCalculator();
    AlgorithmIdentifier algo = digest.getAlgorithmIdentifier();
    ASN1OctetString nameHash = ASN1OctetString.getInstance(ocsp_cache_key.nameHash);
    ASN1OctetString keyHash = ASN1OctetString.getInstance(ocsp_cache_key.keyHash);
    ASN1Integer snumber = new ASN1Integer(ocsp_cache_key.serialNumber);
    CertID cid = new CertID(algo, nameHash, keyHash, snumber);
    return Base64.encodeBase64String(cid.toASN1Primitive().getEncoded());
  }
  catch (Exception ex)
  {
    LOGGER.debug("Failed to encode cache key to base64 encoded cert id");
  }
  return null;
}
 
Example #6
Source File: XijsonCertprofile.java    From xipki with Apache License 2.0 6 votes vote down vote up
private void initInhibitAnyPolicy(Set<ASN1ObjectIdentifier> extnIds,
    Map<String, ExtensionType> extensions) throws CertprofileException {
  ASN1ObjectIdentifier type = Extension.inhibitAnyPolicy;
  if (extensionControls.containsKey(type)) {
    extnIds.remove(type);
    InhibitAnyPolicy extConf = getExtension(type, extensions).getInhibitAnyPolicy();
    if (extConf != null) {
      int skipCerts = extConf.getSkipCerts();
      if (skipCerts < 0) {
        throw new CertprofileException(
            "negative inhibitAnyPolicy.skipCerts is not allowed: " + skipCerts);
      }
      ASN1Integer value = new ASN1Integer(BigInteger.valueOf(skipCerts));
      this.inhibitAnyPolicy = new ExtensionValue(extensionControls.get(type).isCritical(), value);
    }
  }
}
 
Example #7
Source File: SECPrivateKey.java    From InflatableDonkey with MIT License 6 votes vote down vote up
@Override
public ASN1Primitive toASN1Primitive() {
    DERTaggedObject parametersEncodable = parameters()
            .map(DEROctetString::new)
            .map(e -> new DERTaggedObject(PARAMETERS, e))
            .orElseGet(null);

    DERTaggedObject publicKeyEncodable = publicKey()
            .map(DERBitString::new)
            .map(e -> new DERTaggedObject(PUBLIC_KEY, e))
            .orElseGet(null);

    ASN1EncodableVector vector = DER.vector(
            new ASN1Integer(version),
            new DEROctetString(privateKey),
            parametersEncodable,
            publicKeyEncodable);

    return new DERSequence(vector);
}
 
Example #8
Source File: KeySet.java    From InflatableDonkey with MIT License 6 votes vote down vote up
ASN1Primitive toASN1Primitive(boolean includeChecksum) {

        DEROctetString checksumEncodable = includeChecksum
                ? new DEROctetString(checksum())
                : null;

        ASN1Integer flagsEncodable = flags.map(ASN1Integer::new)
                .orElse(null);

        ASN1EncodableVector vector = DER.vector(
                new DERUTF8String(name),
                DER.toSet(keys),
                DER.toSet(serviceKeyIDs),
                checksumEncodable,
                flagsEncodable,
                signatureInfo.orElse(null));

        DERSequence sequence = new DERSequence(vector);
        return DER.toApplicationSpecific(APPLICATION_TAG, sequence);
    }
 
Example #9
Source File: SSDManager.java    From snowflake-jdbc with Apache License 2.0 6 votes vote down vote up
SFTrustManager.OcspResponseCacheKey getWildCardCertId()
{
  DigestCalculator digest = new SFTrustManager.SHA1DigestCalculator();
  AlgorithmIdentifier algo = digest.getAlgorithmIdentifier();
  ASN1OctetString nameHash = ASN1OctetString.getInstance("0");
  ASN1OctetString keyHash = ASN1OctetString.getInstance("0");
  ASN1Integer serial_number = ASN1Integer.getInstance(0);
  CertID cid = new CertID(algo, nameHash, keyHash, serial_number);
  SFTrustManager.OcspResponseCacheKey keyOcspResp = null;
  try
  {
    keyOcspResp = new SFTrustManager.OcspResponseCacheKey(
        ASN1OctetString.getInstance("0").getEncoded(),
        ASN1OctetString.getInstance("0").getEncoded(),
        ASN1Integer.getInstance(0).getValue());
  }
  catch (Throwable ex)
  {
    LOGGER.debug("Could not create wildcard certid as cache key");
    keyOcspResp = null;
  }
  return keyOcspResp;
}
 
Example #10
Source File: X509Ext.java    From portecle with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Get Microsoft certificate template name V2 (1.3.6.1.4.1.311.20.7) extension value as a string.
 *
 * <pre>
 * CertificateTemplate ::= SEQUENCE {
 *   templateID OBJECT IDENTIFIER,
 *   templateMajorVersion TemplateVersion,
 *   templateMinorVersion TemplateVersion OPTIONAL
 * }
 * TemplateVersion ::= INTEGER (0..4294967295)
 * </pre>
 *
 * @see <a href="https://groups.google.com/groups?selm=OXFILYELDHA.1908%40TK2MSFTNGP11.phx.gbl">https://groups
 *      .google.com/groups?selm=OXFILYELDHA.1908%40TK2MSFTNGP11.phx.gbl</a>
 * @param bValue The octet string value
 * @return Extension value as a string
 * @throws IOException If an I/O problem occurs
 */
private String getMicrosoftCertificateTemplateV2StringValue(byte[] bValue)
    throws IOException
{
	ASN1Sequence seq = (ASN1Sequence) ASN1Primitive.fromByteArray(bValue);
	StringBuilder sb = new StringBuilder();

	sb.append(RB.getString("MsftCertTemplateId"));
	sb.append(": ");
	sb.append(((ASN1ObjectIdentifier) seq.getObjectAt(0)).getId());
	sb.append("<br><br>");

	ASN1Integer derInt = (ASN1Integer) seq.getObjectAt(1);
	sb.append(MessageFormat.format(RB.getString("MsftCertTemplateMajorVer"), derInt.getValue()));

	if ((derInt = (ASN1Integer) seq.getObjectAt(2)) != null)
	{
		sb.append("<br><br>");
		sb.append(MessageFormat.format(RB.getString("MsftCertTemplateMinorVer"), derInt.getValue()));
	}

	return sb.toString();
}
 
Example #11
Source File: CmpCaClient.java    From xipki with Apache License 2.0 6 votes vote down vote up
private Certificate[] cmpCaCerts() throws Exception {
  ProtectedPKIMessageBuilder builder = new ProtectedPKIMessageBuilder(
      PKIHeader.CMP_2000, requestorSubject, responderSubject);
  builder.setMessageTime(new Date());
  builder.setTransactionID(randomTransactionId());
  builder.setSenderNonce(randomSenderNonce());

  ASN1EncodableVector vec = new ASN1EncodableVector();
  vec.add(new ASN1Integer(CMP_ACTION_CACERTCHAIN));

  InfoTypeAndValue itv = new InfoTypeAndValue(id_xipki_cmp_cacertchain, new DERSequence(vec));
  PKIBody body = new PKIBody(PKIBody.TYPE_GEN_MSG, new GenMsgContent(itv));
  builder.setBody(body);

  ProtectedPKIMessage request = build(builder);
  PKIMessage response = transmit(request, null);
  ASN1Encodable asn1Value = extractGeneralRepContent(response, id_xipki_cmp_cacertchain.getId());
  ASN1Sequence seq = ASN1Sequence.getInstance(asn1Value);

  final int size = seq.size();
  Certificate[] caCerts = new Certificate[size];
  for (int i = 0; i < size; i++) {
    caCerts[i] = CMPCertificate.getInstance(seq.getObjectAt(i)).getX509v3PKCert();
  }
  return caCerts;
}
 
Example #12
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 #13
Source File: BouncyCastleCrypto.java    From fabric-api with Apache License 2.0 6 votes vote down vote up
@Override
public byte[] sign(byte[] hash, byte[] privateKey) {
    ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest()));
    signer.init(true, new ECPrivateKeyParameters(new BigInteger(privateKey), domain));
    BigInteger[] signature = signer.generateSignature(hash);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        DERSequenceGenerator seq = new DERSequenceGenerator(baos);
        seq.addObject(new ASN1Integer(signature[0]));
        seq.addObject(new ASN1Integer(toCanonicalS(signature[1])));
        seq.close();
        return baos.toByteArray();
    } catch (IOException e) {
        return new byte[0];
    }
}
 
Example #14
Source File: X509Ext.java    From keystore-explorer with GNU General Public License v3.0 6 votes vote down vote up
private String getMsCaVersionStringValue(byte[] octets) {

		/*
            "The extension data is a DWORD value (encoded as X509_INTEGER in the extension);
            the low 16 bits are the certificate index, and the high 16 bits are the key index."
		 */

		ASN1Integer asn1Integer = ASN1Integer.getInstance(octets);
		int version = asn1Integer.getValue().intValue();
		String certIndex = String.valueOf(version & 0xffff);
		String keyIndex = String.valueOf(version >> 16);

		StringBuilder sb = new StringBuilder();

		sb.append(MessageFormat.format(res.getString("MSCaVersion.CertIndex"), certIndex));
		sb.append(NEWLINE);
		sb.append(MessageFormat.format(res.getString("MSCaVersion.KeyIndex"), keyIndex));
		sb.append(NEWLINE);

		return sb.toString();
	}
 
Example #15
Source File: Actions.java    From xipki with Apache License 2.0 6 votes vote down vote up
@Override
protected Object execute0() throws Exception {
  CertificateList crl = CertificateList.getInstance(
      X509Util.toDerEncoded(IoUtil.read(inFile)));

  if (crlNumber != null && crlNumber) {
    ASN1Encodable asn1 = crl.getTBSCertList().getExtensions().getExtensionParsedValue(
        Extension.cRLNumber);
    if (asn1 == null) {
      return "null";
    }
    return getNumber(ASN1Integer.getInstance(asn1).getPositiveValue());
  } else if (issuer != null && issuer) {
    return crl.getIssuer().toString();
  } else if (thisUpdate != null && thisUpdate) {
    return toUtcTimeyyyyMMddhhmmssZ(crl.getThisUpdate().getDate());
  } else if (nextUpdate != null && nextUpdate) {
    return crl.getNextUpdate() == null ? "null" :
      toUtcTimeyyyyMMddhhmmssZ(crl.getNextUpdate().getDate());
  }

  return null;
}
 
Example #16
Source File: CaClientExample.java    From xipki with Apache License 2.0 6 votes vote down vote up
protected static MyKeypair generateDsaKeypair() throws Exception {
  // plen: 2048, qlen: 256
  DSAParameterSpec spec = new DSAParameterSpec(P2048_Q256_P, P2048_Q256_Q, P2048_Q256_G);
  KeyPairGenerator kpGen = KeyPairGenerator.getInstance("DSA");
  kpGen.initialize(spec);
  KeyPair kp = kpGen.generateKeyPair();

  DSAPublicKey dsaPubKey = (DSAPublicKey) kp.getPublic();
  ASN1EncodableVector vec = new ASN1EncodableVector();
  vec.add(new ASN1Integer(dsaPubKey.getParams().getP()));
  vec.add(new ASN1Integer(dsaPubKey.getParams().getQ()));
  vec.add(new ASN1Integer(dsaPubKey.getParams().getG()));
  ASN1Sequence dssParams = new DERSequence(vec);

  SubjectPublicKeyInfo subjectPublicKeyInfo = new SubjectPublicKeyInfo(
      new AlgorithmIdentifier(X9ObjectIdentifiers.id_dsa, dssParams),
      new ASN1Integer(dsaPubKey.getY()));

  return new MyKeypair(kp.getPrivate(), subjectPublicKeyInfo);
}
 
Example #17
Source File: Spkac.java    From keystore-explorer with GNU General Public License v3.0 6 votes vote down vote up
private ASN1Sequence createPublicKeyAndChallenge() throws SpkacException {
	ASN1EncodableVector publicKeyAlgorithm = new ASN1EncodableVector();
	publicKeyAlgorithm.add(new ASN1ObjectIdentifier(getPublicKeyAlg().oid()));

	if (getPublicKey() instanceof RSAPublicKey) {
		publicKeyAlgorithm.add(DERNull.INSTANCE);
	} else {
		DSAParams dsaParams = ((DSAPublicKey) getPublicKey()).getParams();

		ASN1EncodableVector dssParams = new ASN1EncodableVector();
		dssParams.add(new ASN1Integer(dsaParams.getP()));
		dssParams.add(new ASN1Integer(dsaParams.getQ()));
		dssParams.add(new ASN1Integer(dsaParams.getG()));

		publicKeyAlgorithm.add(new DERSequence(dssParams));
	}

	ASN1EncodableVector spki = new ASN1EncodableVector();
	spki.add(new DERSequence(publicKeyAlgorithm));
	spki.add(encodePublicKeyAsBitString(getPublicKey()));

	ASN1EncodableVector publicKeyAndChallenge = new ASN1EncodableVector();
	publicKeyAndChallenge.add(new DERSequence(spki));
	publicKeyAndChallenge.add(new DERIA5String(getChallenge()));
	return new DERSequence(publicKeyAndChallenge);
}
 
Example #18
Source File: Spkac.java    From keystore-explorer with GNU General Public License v3.0 6 votes vote down vote up
private PublicKey decodePublicKeyFromBitString(ASN1ObjectIdentifier publicKeyAlgorithmOid,
		ASN1Primitive algorithmParameters, DERBitString publicKey) throws SpkacException {
	if (publicKeyAlgorithmOid.getId().equals(RSA.oid())) {
		return decodeRsaPublicKeyFromBitString(publicKey); // Algorithm parameters are ASN1Null and unnecessary
	} else if (publicKeyAlgorithmOid.getId().equals(DSA.oid())) {
		ASN1Sequence dssParams = (ASN1Sequence) algorithmParameters;

		BigInteger p = ((ASN1Integer) dssParams.getObjectAt(0)).getValue();
		BigInteger q = ((ASN1Integer) dssParams.getObjectAt(1)).getValue();
		BigInteger g = ((ASN1Integer) dssParams.getObjectAt(2)).getValue();

		return decodeDsaPublicKeyFromBitString(publicKey, p, q, g);
	} else {
		throw new SpkacException(MessageFormat.format(
				res.getString("NoSupportPublicKeyAlgorithm.exception.message"), publicKeyAlgorithmOid.getId()));

	}
}
 
Example #19
Source File: CtLog.java    From xipki with Apache License 2.0 6 votes vote down vote up
public Object getSignatureObject() {
  switch (algorithm.signature) {
    case ecdsa:
    case dsa:
      ASN1Sequence seq = ASN1Sequence.getInstance(signature);
      return new BigInteger[] {
          ASN1Integer.getInstance(seq.getObjectAt(0)).getPositiveValue(),
          ASN1Integer.getInstance(seq.getObjectAt(1)).getPositiveValue()};
    case rsa:
      return signature;
    case anonymous:
      return signature;
    default:
      return signature;
  }
}
 
Example #20
Source File: ECKeyPair.java    From WalletCordova with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public byte[] sign (byte[] hash) throws ValidationException
{
	if ( priv == null )
	{
		throw new ValidationException ("Need private key to sign");
	}
	ECDSASigner signer = new ECDSASigner (new HMacDSAKCalculator (new SHA256Digest ()));
	signer.init (true, new ECPrivateKeyParameters (priv, domain));
	BigInteger[] signature = signer.generateSignature (hash);
	ByteArrayOutputStream s = new ByteArrayOutputStream ();
	try
	{
		DERSequenceGenerator seq = new DERSequenceGenerator (s);
		seq.addObject (new ASN1Integer (signature[0]));
		seq.addObject (new ASN1Integer (signature[1]));
		seq.close ();
		return s.toByteArray ();
	}
	catch ( IOException e )
	{
	}
	return null;
}
 
Example #21
Source File: ProxyMessage.java    From xipki with Apache License 2.0 5 votes vote down vote up
@Override
public ASN1Primitive toASN1Primitive() {
  ASN1EncodableVector vecVersions = new ASN1EncodableVector();
  for (Short version : versions) {
    vecVersions.add(new ASN1Integer(BigInteger.valueOf(version)));
  }

  ASN1EncodableVector vec = new ASN1EncodableVector();
  vec.add(ASN1Boolean.getInstance(readOnly));
  vec.add(new DERSequence(vecVersions));
  return new DERSequence(vec);
}
 
Example #22
Source File: ProxyMessage.java    From xipki with Apache License 2.0 5 votes vote down vote up
@Override
public ASN1Primitive toASN1Primitive() {
  ASN1EncodableVector vector = new ASN1EncodableVector();
  vector.add(new SlotIdentifier(slotId));
  vector.add(new NewKeyControl(control));
  vector.add(new ASN1Integer(keyType));
  vector.add(new ASN1Integer(keysize));
  return new DERSequence(vector);
}
 
Example #23
Source File: CmpAgent.java    From xipki with Apache License 2.0 5 votes vote down vote up
public X509CRLHolder downloadCrl(BigInteger crlNumber, ReqRespDebug debug)
    throws CmpClientException, PkiErrorException {
  Integer action = null;
  PKIMessage request;
  if (crlNumber == null) {
    ASN1ObjectIdentifier type = CMPObjectIdentifiers.it_currentCRL;
    request = buildMessageWithGeneralMsgContent(type, null);
  } else {
    action = XiSecurityConstants.CMP_ACTION_GET_CRL_WITH_SN;
    request = buildMessageWithXipkiAction(action, new ASN1Integer(crlNumber));
  }

  VerifiedPkiMessage response = signAndSend(request, debug);
  return evaluateCrlResponse(response, action);
}
 
Example #24
Source File: EncryptedKey.java    From InflatableDonkey with MIT License 5 votes vote down vote up
@Override
public ASN1Primitive toASN1Primitive() {
    ASN1Integer asn1IntegerFlags = flags.map(ASN1Integer::new)
            .orElse(null);

    ASN1EncodableVector vector = DER.vector(
            masterKey,
            new DEROctetString(wrappedKey()),
            asn1IntegerFlags);

    return new DERSequence(vector);
}
 
Example #25
Source File: SFTrustManager.java    From snowflake-jdbc with Apache License 2.0 5 votes vote down vote up
/**
 * Encode OCSP Response Cache to JSON
 *
 * @return JSON object
 */
private static ObjectNode encodeCacheToJSON()
{
  try
  {
    ObjectNode out = OBJECT_MAPPER.createObjectNode();
    for (Map.Entry<OcspResponseCacheKey, SFPair<Long, String>> elem :
        OCSP_RESPONSE_CACHE.entrySet())
    {
      OcspResponseCacheKey key = elem.getKey();
      SFPair<Long, String> value0 = elem.getValue();
      long currentTimeSecond = value0.left;

      DigestCalculator digest = new SHA1DigestCalculator();
      AlgorithmIdentifier algo = digest.getAlgorithmIdentifier();
      ASN1OctetString nameHash = ASN1OctetString.getInstance(key.nameHash);
      ASN1OctetString keyHash = ASN1OctetString.getInstance(key.keyHash);
      ASN1Integer serialNumber = new ASN1Integer(key.serialNumber);
      CertID cid = new CertID(algo, nameHash, keyHash, serialNumber);
      ArrayNode vout = OBJECT_MAPPER.createArrayNode();
      vout.add(currentTimeSecond);
      vout.add(value0.right);
      out.set(
          Base64.encodeBase64String(cid.toASN1Primitive().getEncoded()),
          vout);
    }
    return out;
  }
  catch (IOException ex)
  {
    LOGGER.debug("Failed to encode ASN1 object.");
  }
  return null;
}
 
Example #26
Source File: CmpAgent.java    From xipki with Apache License 2.0 5 votes vote down vote up
private PKIMessage buildUnrevokeOrRemoveCertRequest(UnrevokeOrRemoveCertRequest request,
    int reasonCode) throws CmpClientException {
  PKIHeader header = buildPkiHeader(null);

  List<UnrevokeOrRemoveCertRequest.Entry> requestEntries = request.getRequestEntries();
  List<RevDetails> revDetailsArray = new ArrayList<>(requestEntries.size());
  for (UnrevokeOrRemoveCertRequest.Entry requestEntry : requestEntries) {
    CertTemplateBuilder certTempBuilder = new CertTemplateBuilder();
    certTempBuilder.setIssuer(requestEntry.getIssuer());
    certTempBuilder.setSerialNumber(new ASN1Integer(requestEntry.getSerialNumber()));
    byte[] aki = requestEntry.getAuthorityKeyIdentifier();
    if (aki != null) {
      Extensions certTempExts = getCertTempExtensions(aki);
      certTempBuilder.setExtensions(certTempExts);
    }

    Extension[] extensions = new Extension[1];

    try {
      ASN1Enumerated reason = new ASN1Enumerated(reasonCode);
      extensions[0] = new Extension(Extension.reasonCode, true,
              new DEROctetString(reason.getEncoded()));
    } catch (IOException ex) {
      throw new CmpClientException(ex.getMessage(), ex);
    }
    Extensions exts = new Extensions(extensions);

    RevDetails revDetails = new RevDetails(certTempBuilder.build(), exts);
    revDetailsArray.add(revDetails);
  }

  RevReqContent content = new RevReqContent(revDetailsArray.toArray(new RevDetails[0]));
  PKIBody body = new PKIBody(PKIBody.TYPE_REVOCATION_REQ, content);
  return new PKIMessage(header, body);
}
 
Example #27
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 #28
Source File: ProxyMessage.java    From xipki with Apache License 2.0 5 votes vote down vote up
@Override
public ASN1Primitive toASN1Primitive() {
  ASN1EncodableVector vector = new ASN1EncodableVector();
  vector.add(new SlotIdentifier(slotId));
  vector.add(new NewKeyControl(control));
  vector.add(new ASN1Integer(keysize));
  if (publicExponent != null) {
    vector.add(new ASN1Integer(publicExponent));
  }
  return new DERSequence(vector);
}
 
Example #29
Source File: CryptoPrimitives.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * Decodes an ECDSA signature and returns a two element BigInteger array.
 *
 * @param signature ECDSA signature bytes.
 * @return BigInteger array for the signature's r and s values
 * @throws Exception
 */
private static BigInteger[] decodeECDSASignature(byte[] signature) throws Exception {

    try (ByteArrayInputStream inStream = new ByteArrayInputStream(signature)) {
        ASN1InputStream asnInputStream = new ASN1InputStream(inStream);
        ASN1Primitive asn1 = asnInputStream.readObject();

        BigInteger[] sigs = new BigInteger[2];
        int count = 0;
        if (asn1 instanceof ASN1Sequence) {
            ASN1Sequence asn1Sequence = (ASN1Sequence) asn1;
            ASN1Encodable[] asn1Encodables = asn1Sequence.toArray();
            for (ASN1Encodable asn1Encodable : asn1Encodables) {
                ASN1Primitive asn1Primitive = asn1Encodable.toASN1Primitive();
                if (asn1Primitive instanceof ASN1Integer) {
                    ASN1Integer asn1Integer = (ASN1Integer) asn1Primitive;
                    BigInteger integer = asn1Integer.getValue();
                    if (count < 2) {
                        sigs[count] = integer;
                    }
                    count++;
                }
            }
        }
        if (count != 2) {
            throw new CryptoException(format("Invalid ECDSA signature. Expected count of 2 but got: %d. Signature is: %s", count,
                    DatatypeConverter.printHexBinary(signature)));
        }
        return sigs;
    }

}
 
Example #30
Source File: EncryptedKeys.java    From InflatableDonkey with MIT License 5 votes vote down vote up
@Override
public ASN1Primitive toASN1Primitive() {
    DERTaggedObject cont0Encodable = cont0()
            .map(DEROctetString::new)
            .map(e -> new DERTaggedObject(CONT0, e))
            .orElseGet(null);

    ASN1EncodableVector vector = DER.vector(
            new ASN1Integer(x),
            DER.toSet(encryptedKeySet),
            cont0Encodable);

    return new DERSequence(vector);
}