Java Code Examples for org.bouncycastle.asn1.ASN1Primitive#fromByteArray()

The following examples show how to use org.bouncycastle.asn1.ASN1Primitive#fromByteArray() . 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: 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 2
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 3
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 4
Source File: TimeStampToken.java    From signer with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public Attribute getValue() throws SignerException {
    try {
        logger.info(cadesMessagesBundle.getString("info.tsa.connecting"));

        if (timeStampGenerator != null) {
              //Inicializa os valores para o timestmap
        	timeStampGenerator.initialize(content, privateKey, certificates, hash);

            //Obtem o carimbo de tempo atraves do servidor TSA
            byte[] response = timeStampGenerator.generateTimeStamp();

            //Valida o carimbo de tempo gerado
            timeStampGenerator.validateTimeStamp(content, response, hash);

            return new Attribute(new ASN1ObjectIdentifier(identifier), new DERSet(ASN1Primitive.fromByteArray(response)));
        } else {
            throw new SignerException(cadesMessagesBundle.getString("error.tsa.not.found"));
        }
    } catch (SecurityException | IOException ex) {
        throw new SignerException(ex.getMessage());
    }
}
 
Example 5
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 6
Source File: EscTimeStamp.java    From signer with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public Attribute getValue() throws SignerException {
	try {
        logger.info(cadesMessagesBundle.getString("info.tsa.connecting"));

        if (timeStampGenerator != null) {
              //Inicializa os valores para o timestmap
        	timeStampGenerator.initialize(content, privateKey, certificates, hash);

            //Obtem o carimbo de tempo atraves do servidor TSA
            byte[] response = timeStampGenerator.generateTimeStamp();

            //Valida o carimbo de tempo gerado
            timeStampGenerator.validateTimeStamp(content, response, hash);

            return new Attribute(new ASN1ObjectIdentifier(identifier), new DERSet(ASN1Primitive.fromByteArray(response)));
        } else {
            throw new SignerException(cadesMessagesBundle.getString("error.tsa.not.found"));
        }
    } catch (SecurityException | IOException ex) {
    }
    throw new UnsupportedOperationException(cadesMessagesBundle.getString("error.not.supported",getClass().getName()));
}
 
Example 7
Source File: DistinguishedName.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
private static String convertToString(byte[] value) {
   try {
      ASN1Primitive content = ASN1Primitive.fromByteArray(value);
      if (content instanceof DERPrintableString) {
         return ((DERPrintableString)content).getString();
      }

      LOG.error("Unsupported ASN1Object :" + content.getClass());
   } catch (Exception var2) {
      LOG.error("Error while converting to String", var2);
   }

   return null;
}
 
Example 8
Source File: X509Ext.java    From portecle with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Get Policy Constraints (2.5.29.36) extension value as a string.
 *
 * <pre>
 * PolicyConstraints ::= SEQUENCE {
 *     requireExplicitPolicy           [0] SkipCerts OPTIONAL,
 *     inhibitPolicyMapping            [1] SkipCerts OPTIONAL }
 * SkipCerts ::= INTEGER (0..MAX)
 * </pre>
 *
 * @param bValue The octet string value
 * @return Extension value as a string
 * @throws IOException If an I/O problem occurs
 */
private String getPolicyConstraintsStringValue(byte[] bValue)
    throws IOException
{
	// Get sequence of policy constraint
	ASN1Sequence policyConstraints = (ASN1Sequence) ASN1Primitive.fromByteArray(bValue);

	StringBuilder strBuff = new StringBuilder();

	for (int i = 0, len = policyConstraints.size(); i < len; i++)
	{
		DERTaggedObject policyConstraint = (DERTaggedObject) policyConstraints.getObjectAt(i);
		ASN1Integer skipCerts = new ASN1Integer(((DEROctetString) policyConstraint.getObject()).getOctets());
		int iSkipCerts = skipCerts.getValue().intValue();

		switch (policyConstraint.getTagNo())
		{
			case 0: // Require Explicit Policy Skip Certs
				if (strBuff.length() != 0)
				{
					strBuff.append("<br><br>");
				}
				strBuff.append(MessageFormat.format(RB.getString("RequireExplicitPolicy"), iSkipCerts));
				break;
			case 1: // Inhibit Policy Mapping Skip Certs
				if (strBuff.length() != 0)
				{
					strBuff.append("<br><br>");
				}
				strBuff.append(MessageFormat.format(RB.getString("InhibitPolicyMapping"), iSkipCerts));
				break;
		}
	}

	return strBuff.toString();

}
 
Example 9
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 10
Source File: PemUtils.java    From hedera-sdk-java with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unused")
public static void writeEncryptedPrivateKey(PrivateKeyInfo pkInfo, Writer out, String passphrase) throws IOException {
    byte[] salt = CryptoUtils.randomBytes(CryptoUtils.SALT_LEN);

    KeyParameter derivedKey = CryptoUtils.deriveKeySha256(
        passphrase, salt, CryptoUtils.ITERATIONS, CryptoUtils.CBC_DK_LEN);

    byte[] iv = CryptoUtils.randomBytes(CryptoUtils.IV_LEN);

    Cipher cipher = CryptoUtils.initAesCbc128Encrypt(derivedKey, iv);

    byte[] encryptedKey = CryptoUtils.runCipher(cipher, pkInfo.getEncoded());

    // I wanted to just do this with BC's PKCS8Generator and KcePKCSPBEOutputEncryptorBuilder
    // but it tries to init AES instance of `Cipher` with a `PBKDF2Key` and the former complains

    // So this is basically a reimplementation of that minus the excess OO
    PBES2Parameters parameters = new PBES2Parameters(
        new KeyDerivationFunc(
            PKCSObjectIdentifiers.id_PBKDF2,
            new PBKDF2Params(
                salt,
                CryptoUtils.ITERATIONS,
                CryptoUtils.CBC_DK_LEN,
                new AlgorithmIdentifier(PKCSObjectIdentifiers.id_hmacWithSHA256))),
        new EncryptionScheme(NISTObjectIdentifiers.id_aes128_CBC,
            ASN1Primitive.fromByteArray(cipher.getParameters().getEncoded())));

    EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = new EncryptedPrivateKeyInfo(
        new AlgorithmIdentifier(PKCSObjectIdentifiers.id_PBES2, parameters),
        encryptedKey);

    PemWriter writer = new PemWriter(out);
    writer.writeObject(new PemObject(TYPE_ENCRYPTED_PRIVATE_KEY, encryptedPrivateKeyInfo.getEncoded()));
    writer.flush();
}
 
Example 11
Source File: CertificateParser.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
private String convertToString(byte[] value) {
   try {
      ASN1Primitive content = ASN1Primitive.fromByteArray(value);
      if (content instanceof DERPrintableString) {
         return ((DERPrintableString)content).getString();
      }

      LOG.error("Unsupported ASN1Object :" + content.getClass());
   } catch (Exception var3) {
      LOG.error("Error while converting to String", var3);
   }

   return "";
}
 
Example 12
Source File: CertificateParser.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
private String convertToString(byte[] value) {
   try {
      ASN1Primitive content = ASN1Primitive.fromByteArray(value);
      if (content instanceof DERPrintableString) {
         return ((DERPrintableString)content).getString();
      }

      LOG.error("Unsupported ASN1Object :" + content.getClass());
   } catch (Exception var3) {
      LOG.error("Error while converting to String", var3);
   }

   return "";
}
 
Example 13
Source File: CertificateParser.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
private String convertToString(byte[] value) {
   try {
      ASN1Primitive content = ASN1Primitive.fromByteArray(value);
      if (content instanceof DERPrintableString) {
         return ((DERPrintableString)content).getString();
      }

      LOG.error("Unsupported ASN1Object :" + content.getClass());
   } catch (Exception var3) {
      LOG.error("Error while converting to String", var3);
   }

   return "";
}
 
Example 14
Source File: X509Ext.java    From portecle with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Get Microsoft Previous CA Certificate Hash (1.3.6.1.4.1.311.21.2) extension value as a string.
 *
 * @see <a href="https://support.microsoft.com/help/287547">Microsoft support</a>
 * @param bValue The octet string value
 * @return Extension value as a string
 * @throws IOException If an I/O problem occurs
 */
private String getMicrosoftPreviousCACertificateHashStringValue(byte[] bValue)
    throws IOException
{
	DEROctetString derOctetStr = (DEROctetString) ASN1Primitive.fromByteArray(bValue);
	byte[] bKeyIdent = derOctetStr.getOctets();

	return convertToHexString(bKeyIdent);
}
 
Example 15
Source File: ExtensionType.java    From xipki with Apache License 2.0 5 votes vote down vote up
private static ASN1Primitive asn1PrimitivefromByteArray(byte[] encoded)
    throws CertprofileException {
  try {
    return ASN1Primitive.fromByteArray(encoded);
  } catch (IOException ex) {
    throw new CertprofileException(ex.getMessage(), ex);
  }
}
 
Example 16
Source File: DistinguishedName.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
private static String convertToString(byte[] value) {
   try {
      ASN1Primitive content = ASN1Primitive.fromByteArray(value);
      if (content instanceof DERPrintableString) {
         return ((DERPrintableString)content).getString();
      }

      LOG.error("Unsupported ASN1Object :" + content.getClass());
   } catch (Exception var2) {
      LOG.error("Error while converting to String", var2);
   }

   return null;
}
 
Example 17
Source File: DistinguishedName.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
private static String convertToString(byte[] value) {
   try {
      ASN1Primitive content = ASN1Primitive.fromByteArray(value);
      if (content instanceof DERPrintableString) {
         return ((DERPrintableString)content).getString();
      }

      LOG.error("Unsupported ASN1Object :" + content.getClass());
   } catch (Exception var2) {
      LOG.error("Error while converting to String", var2);
   }

   return null;
}
 
Example 18
Source File: X509Ext.java    From portecle with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Get Policy Mappings (2.5.29.33) extension value as a string.
 *
 * <pre>
 * PolicyMappings ::= SEQUENCE SIZE (1..MAX) OF SEQUENCE {
 *     issuerDomainPolicy      CertPolicyId,
 *      subjectDomainPolicy     CertPolicyId }
 * CertPolicyId ::= OBJECT IDENTIFIER
 * </pre>
 *
 * @param bValue The octet string value
 * @return Extension value as a string
 * @throws IOException If an I/O problem occurs
 */
private String getPolicyMappingsStringValue(byte[] bValue)
    throws IOException
{
	// Get sequence of policy mappings
	ASN1Sequence policyMappings = (ASN1Sequence) ASN1Primitive.fromByteArray(bValue);

	StringBuilder strBuff = new StringBuilder("<ul>");

	// Get each policy mapping
	for (int i = 0, len = policyMappings.size(); i < len; i++)
	{
		ASN1Sequence policyMapping = (ASN1Sequence) policyMappings.getObjectAt(i);
		int pmLen = policyMapping.size();

		strBuff.append("<li>");
		strBuff.append(MessageFormat.format(RB.getString("PolicyMapping"), i + 1));

		if (pmLen > 0)
		{
			ASN1ObjectIdentifier issuerDomainPolicy = (ASN1ObjectIdentifier) policyMapping.getObjectAt(0);

			strBuff.append("<ul><li>");
			strBuff.append(MessageFormat.format(RB.getString("IssuerDomainPolicy"), issuerDomainPolicy.getId()));
			strBuff.append("</li></ul>");
		}

		if (pmLen > 1)
		{
			ASN1ObjectIdentifier subjectDomainPolicy = (ASN1ObjectIdentifier) policyMapping.getObjectAt(1);

			strBuff.append("<ul><li>");
			strBuff.append(MessageFormat.format(RB.getString("SubjectDomainPolicy"), subjectDomainPolicy.getId()));
			strBuff.append("</li></ul>");
		}

		strBuff.append("</li>");
	}
	strBuff.append("</ul>");

	return strBuff.toString();
}
 
Example 19
Source File: ExtensionsChecker.java    From xipki with Apache License 2.0 4 votes vote down vote up
private void checkDirectoryString(ASN1ObjectIdentifier extnType,
    DirectoryStringType type, String text,
    StringBuilder failureMsg, byte[] extensionValue, Extensions requestedExtns,
    ExtensionControl extControl) {
  if (type == null) {
    checkConstantExtnValue(extnType, failureMsg, extensionValue, requestedExtns, extControl);
    return;
  }

  ASN1Primitive asn1;
  try {
    asn1 = ASN1Primitive.fromByteArray(extensionValue);
  } catch (IOException ex) {
    failureMsg.append("invalid syntax of extension value; ");
    return;
  }

  boolean correctStringType;

  switch (type) {
    case bmpString:
      correctStringType = (asn1 instanceof DERBMPString);
      break;
    case printableString:
      correctStringType = (asn1 instanceof DERPrintableString);
      break;
    case teletexString:
      correctStringType = (asn1 instanceof DERT61String);
      break;
    case utf8String:
      correctStringType = (asn1 instanceof DERUTF8String);
      break;
    default:
      throw new IllegalStateException("should not reach here, unknown DirectoryStringType "
          + type);
  } // end switch

  if (!correctStringType) {
    failureMsg.append("extension value is not of type DirectoryString.")
      .append(text).append("; ");
    return;
  }

  String extTextValue = ((ASN1String) asn1).getString();
  if (!text.equals(extTextValue)) {
    addViolation(failureMsg, "content", extTextValue, text);
  }
}
 
Example 20
Source File: X509Ext.java    From portecle with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Get Invalidity Date (2.5.29.24) extension value as a string.
 *
 * <pre>
 * InvalidityDate ::=  GeneralizedTime
 * </pre>
 *
 * @param bValue The octet string value
 * @return Extension value as a string
 * @throws IOException If an I/O problem occurs
 * @throws ParseException If a date formatting problem occurs
 */
private String getInvalidityDateStringValue(byte[] bValue)
    throws IOException, ParseException
{
	// Get invalidity date
	ASN1GeneralizedTime invalidityDate = (ASN1GeneralizedTime) ASN1Primitive.fromByteArray(bValue);

	// Format invalidity date for display
	return formatGeneralizedTime(invalidityDate);
}