当前位置: 首页>>代码示例>>Java>>正文


Java DatatypeConverter类代码示例

本文整理汇总了Java中javax.xml.bind.DatatypeConverter的典型用法代码示例。如果您正苦于以下问题:Java DatatypeConverter类的具体用法?Java DatatypeConverter怎么用?Java DatatypeConverter使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


DatatypeConverter类属于javax.xml.bind包,在下文中一共展示了DatatypeConverter类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: Verify

import javax.xml.bind.DatatypeConverter; //导入依赖的package包/类
public static boolean Verify(String jwt, String type) throws Exception {
    
    try{
        Claims claims = Jwts.parser()
            .setSigningKey(DatatypeConverter.parseBase64Binary(Parameters.TOKENKEY))
            .parseClaimsJws(jwt).getBody();
        
        //verifica se o issuer é igual ao type
        return claims.getIssuer().equals(type);
        
    } catch (ExpiredJwtException | MalformedJwtException | SignatureException 
            | UnsupportedJwtException | IllegalArgumentException e) {
        System.out.println(e.getMessage());
        return false;
    }
}
 
开发者ID:Montanheiro,项目名称:SistemaAlmoxarifado,代码行数:17,代码来源:Token.java

示例2: Gerate

import javax.xml.bind.DatatypeConverter; //导入依赖的package包/类
public static String Gerate(String issuer, int idSubject, int hours) {

        //The JWT signature algorithm we will be using to sign the token
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        
        //Hours to milliseconds
        long ttlMillis = hours * 3600000;
        String subject = String.valueOf(idSubject);
        
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        
        //We will sign our JWT with our ApiKey secret
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(Parameters.TOKENKEY);
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

        //Let's set the JWT Claims
        JwtBuilder builder = Jwts.builder().setIssuedAt(now)
                                    .setSubject(subject)
                                    .setIssuer(issuer)
                                    .signWith(signatureAlgorithm, signingKey);

        //if it has been specified, let's add the expiration
        if (ttlMillis >= 0) {
        long expMillis = nowMillis + ttlMillis;
            Date exp = new Date(expMillis);
            builder.setExpiration(exp);
        }

        //Builds the JWT and serializes it to a compact, URL-safe string
        return builder.compact();
    }
 
开发者ID:Montanheiro,项目名称:SistemaAlmoxarifado,代码行数:33,代码来源:Token.java

示例3: streamEncrypt

import javax.xml.bind.DatatypeConverter; //导入依赖的package包/类
public static byte[] streamEncrypt(String message, SecretKey key,
    MessageDigest digest)
    throws Exception {

    byte[] data;
    Cipher encCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    encCipher.init(Cipher.ENCRYPT_MODE, key);
    try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
        DigestOutputStream dos = new DigestOutputStream(bos, digest);
        CipherOutputStream cos = new CipherOutputStream(dos, encCipher)) {
        try (ObjectOutputStream oos = new ObjectOutputStream(cos)) {
            oos.writeObject(message);
        }
        data = bos.toByteArray();
    }

    if (debug) {
        System.out.println(DatatypeConverter.printHexBinary(data));
    }
    return data;
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:22,代码来源:CipherStreamClose.java

示例4: encodeImg2String

import javax.xml.bind.DatatypeConverter; //导入依赖的package包/类
/**
 * Encodes the given image InputStream to a base64 coded string.
 *
 * @param is image InputStream to encode
 * @param type type of the image: jpeg, bmp, png, gif etc.
 * @return encoded string
 */
public static String encodeImg2String(InputStream is, String type) {
    String imageString = null;
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    try {
        BufferedImage image = ImageIO.read(is);
        ImageIO.write(image, type, bos);
        byte[] imageBytes = bos.toByteArray();
        imageString = DatatypeConverter.printBase64Binary(imageBytes);
        bos.close();
    } catch (IOException ex) {
        LOGGER.error(ex.getMessage(), ex);
    }
    return imageString;
}
 
开发者ID:vrk-kpa,项目名称:xrd4j,代码行数:23,代码来源:MessageHelper.java

示例5: getDataToSign

import javax.xml.bind.DatatypeConverter; //导入依赖的package包/类
@RequestMapping(value = "/get-data-to-sign", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public GetDataToSignResponse getDataToSign(Model model, @RequestBody @Valid DataToSignParams params,
		@ModelAttribute("signatureMultipleDocumentsForm") @Valid SignatureMultipleDocumentsForm signatureMultipleDocumentsForm, BindingResult result) {
	signatureMultipleDocumentsForm.setBase64Certificate(params.getSigningCertificate());
	signatureMultipleDocumentsForm.setBase64CertificateChain(params.getCertificateChain());
	signatureMultipleDocumentsForm.setEncryptionAlgorithm(params.getEncryptionAlgorithm());
	signatureMultipleDocumentsForm.setSigningDate(new Date());
	model.addAttribute("signatureMultipleDocumentsForm", signatureMultipleDocumentsForm);

	ToBeSigned dataToSign = signingService.getDataToSign(signatureMultipleDocumentsForm);
	if (dataToSign == null) {
		return null;
	}

	GetDataToSignResponse responseJson = new GetDataToSignResponse();
	responseJson.setDataToSign(DatatypeConverter.printBase64Binary(dataToSign.getBytes()));
	return responseJson;
}
 
开发者ID:esig,项目名称:dss-demonstrations,代码行数:20,代码来源:SignatureMultipleDocumentsController.java

示例6: signDocument

import javax.xml.bind.DatatypeConverter; //导入依赖的package包/类
@SuppressWarnings({ "rawtypes", "unchecked" })
public DSSDocument signDocument(SignatureDocumentForm form) {
	logger.info("Start signDocument with one document");
	DocumentSignatureService service = getSignatureService(form.getContainerType(), form.getSignatureForm());

	AbstractSignatureParameters parameters = fillParameters(form);

	DSSDocument signedDocument = null;
	try {
		DSSDocument toSignDocument = WebAppUtils.toDSSDocument(form.getDocumentToSign());
		SignatureAlgorithm sigAlgorithm = SignatureAlgorithm.getAlgorithm(form.getEncryptionAlgorithm(), form.getDigestAlgorithm());
		SignatureValue signatureValue = new SignatureValue(sigAlgorithm, DatatypeConverter.parseBase64Binary(form.getBase64SignatureValue()));
		signedDocument = service.signDocument(toSignDocument, parameters, signatureValue);
	} catch (Exception e) {
		logger.error("Unable to execute signDocument : " + e.getMessage(), e);
	}
	logger.info("End signDocument with one document");
	return signedDocument;
}
 
开发者ID:esig,项目名称:dss-demonstrations,代码行数:20,代码来源:SigningService.java

示例7: ServerFinalMessage

import javax.xml.bind.DatatypeConverter; //导入依赖的package包/类
public ServerFinalMessage(byte[] messageBytes) throws SaslException {
    String message = toMessage(messageBytes);
    Matcher matcher = PATTERN.matcher(message);
    if (!matcher.matches())
        throw new SaslException("Invalid SCRAM server final message format: " + message);
    String error = null;
    try {
        error = matcher.group("error");
    } catch (IllegalArgumentException e) {
        // ignore
    }
    if (error == null) {
        this.serverSignature = DatatypeConverter.parseBase64Binary(matcher.group("signature"));
        this.error = null;
    } else {
        this.serverSignature = null;
        this.error = error;
    }
}
 
开发者ID:YMCoding,项目名称:kafka-0.11.0.0-src-with-comment,代码行数:20,代码来源:ScramMessages.java

示例8: deserialize

import javax.xml.bind.DatatypeConverter; //导入依赖的package包/类
@SuppressWarnings("unchecked")
@Override
public T deserialize(String topic, byte[] data) {
	try {
		T result = null;

		if (data != null) {
			LOGGER.debug("data='{}'", DatatypeConverter.printHexBinary(data));

			DatumReader<GenericRecord> datumReader = new SpecificDatumReader<>(
					targetType.newInstance().getSchema());
			Decoder decoder = DecoderFactory.get().binaryDecoder(data, null);

			result = (T) datumReader.read(null, decoder);
			LOGGER.debug("deserialized data='{}'", result);
		}
		return result;
	} catch (Exception ex) {
		throw new SerializationException(
				"Can't deserialize data '" + Arrays.toString(data) + "' from topic '" + topic + "'", ex);
	}
}
 
开发者ID:italia,项目名称:daf-replicate-ingestion,代码行数:23,代码来源:AvroDeserializer.java

示例9: checkSHA256

import javax.xml.bind.DatatypeConverter; //导入依赖的package包/类
private static boolean checkSHA256(File provingKey, Component parent) throws IOException {
    MessageDigest sha256;
    try {
        sha256 = MessageDigest.getInstance("SHA-256");
    } catch (NoSuchAlgorithmException impossible) {
        throw new RuntimeException(impossible);
    }
    try (InputStream is = new BufferedInputStream(new FileInputStream(provingKey))) {
        ProgressMonitorInputStream pmis = new ProgressMonitorInputStream(parent,"Verifying proving key",is);
        pmis.getProgressMonitor().setMaximum(PROVING_KEY_SIZE);
        pmis.getProgressMonitor().setMillisToPopup(10);
        DigestInputStream dis = new DigestInputStream(pmis, sha256);
        byte [] temp = new byte[0x1 << 13];
        while(dis.read(temp) >= 0);
        byte [] digest = sha256.digest();
        return SHA256.equalsIgnoreCase(DatatypeConverter.printHexBinary(digest));
    }
}
 
开发者ID:ca333,项目名称:komodoGUI,代码行数:19,代码来源:ProvingKeyFetcher.java

示例10: decode

import javax.xml.bind.DatatypeConverter; //导入依赖的package包/类
public static String[] decode(String auth) {
    //Replacing "Basic THE_BASE_64" to "THE_BASE_64" directly
    auth = auth.replaceFirst("[B|b]asic ", "");
 
    //Decode the Base64 into byte[]
    byte[] decodedBytes = DatatypeConverter.parseBase64Binary(auth);
 
    //If the decode fails in any case
    if(decodedBytes == null || decodedBytes.length == 0){
        return null;
    }
 
    //Now split the byte[] into an array :
    //  - the first one is login,
    //  - the second one password
    return new String(decodedBytes).split(":", 2);
}
 
开发者ID:NLPReViz,项目名称:emr-nlp-server,代码行数:18,代码来源:AuthFilter.java

示例11: decompress

import javax.xml.bind.DatatypeConverter; //导入依赖的package包/类
/**
   * Testing method for decompression of ewf file hex bytes
   * @param ewfHexStr any zlib compressed hex
   * @return decompressed string
   */
  protected static String decompress(String ewfHexStr) {
Inflater inflater = new Inflater();
byte[] input = DatatypeConverter.parseHexBinary(ewfHexStr);
inflater.setInput(input, 0, input.length);
String outputString = "empty";

byte[] result = new byte[input.length];
int resultLength;
try {
	resultLength = inflater.inflate(result);
	outputString = new String(result, 0, resultLength, "UTF-8");
} catch (DataFormatException | UnsupportedEncodingException e) {
	e.printStackTrace();
}
inflater.end();

return outputString;
  }
 
开发者ID:ciphertechsolutions,项目名称:IO,代码行数:24,代码来源:CompressionTask.java

示例12: verifyAssertionExpirationDate

import javax.xml.bind.DatatypeConverter; //导入依赖的package包/类
/**
 * Verify that the NotOnOrAfter attribute in any bearer
 * <SubjectConfirmationData> has not passed, subject to allowable clock skew
 * between the providers
 * 
 * @throws AssertionValidationException
 */
void verifyAssertionExpirationDate(Node nodeAssertion,
        Node nodeConfirmationData) throws AssertionValidationException {

    Calendar expirationDate = DatatypeConverter.parseDateTime(XMLConverter
            .getStringAttValue(nodeConfirmationData,
                    SamlXmlTags.ATTRIBUTE_NOT_ON_OR_AFTER));
    if (now.equals(expirationDate) || now.after(expirationDate)) {
        String assertionId = XMLConverter.getStringAttValue(nodeAssertion,
                SamlXmlTags.ATTRIBUTE_ID);
        AssertionValidationException exception = new AssertionValidationException(
                String.format("Assertion (id=%s) expired", assertionId),
                AssertionValidationException.ReasonEnum.ASSERTION_EXPIRED,
                new String[] { assertionId });
        throw exception;
    }
}
 
开发者ID:servicecatalog,项目名称:oscm,代码行数:24,代码来源:AssertionContentVerifier.java

示例13: EncryptAES

import javax.xml.bind.DatatypeConverter; //导入依赖的package包/类
public static String EncryptAES(String input, SecretKey key) throws CryptoException {
    // encode input
    input = DatatypeConverter.printBase64Binary(input.getBytes());

    byte[] ciphertext = null;
    try {
        ciphertext = AES.encrypt(input.getBytes(), key);
    } catch (Exception e) {
        throw new CryptoException(e);
    }


    // encode encrypted input
    //return DatatypeConverter.printBase64Binary(ciphertext.getBytes());
    return DatatypeConverter.printHexBinary(ciphertext);
}
 
开发者ID:richkmeli,项目名称:Richkware-Manager-Client,代码行数:17,代码来源:Crypto.java

示例14: generateSidelineRequestIdentifier

import javax.xml.bind.DatatypeConverter; //导入依赖的package包/类
/**
 * Using a filter chain step, make some JSON out of it and then hash it to create an idempotent identifier.
 * @param triggerEvent Trigger event that contains metadata about the request
 * @param step The FilterChainStep that we are going to generate the request from
 * @return A sideline request identifier for the filter chain step
 * @throws NoSuchAlgorithmException Your java install is whack yo, it's missing MD5, for realz???
 */
private SidelineRequestIdentifier generateSidelineRequestIdentifier(
    final TriggerEvent triggerEvent,
    final FilterChainStep step
) throws NoSuchAlgorithmException, UnsupportedEncodingException {
    final String json = gson.toJson(step);

    final StringBuilder identifier = new StringBuilder(
        DatatypeConverter.printHexBinary(MessageDigest.getInstance("MD5").digest(json.getBytes("UTF-8")))
    );

    // If we were provided a date time in the event, append the time stamp of that event to the identifier
    if (triggerEvent.getCreatedAt() != null) {
        identifier.append("-");
        identifier.append(
            triggerEvent.getCreatedAt().atZone(ZoneOffset.UTC).toInstant().toEpochMilli()
        );
    }

    return new SidelineRequestIdentifier(identifier.toString());
}
 
开发者ID:salesforce,项目名称:storm-dynamic-spout,代码行数:28,代码来源:ZookeeperWatchTrigger.java

示例15: testExec_withValidKeyStoreProperties_ProperlyEncodesBackup

import javax.xml.bind.DatatypeConverter; //导入依赖的package包/类
@Test
public void testExec_withValidKeyStoreProperties_ProperlyEncodesBackup() throws Exception {
	// Arrange.
	TestBackupFileServiceRequest testRequest = new TestBackupFileServiceRequest();

       SecretKey secretKey = generateTestSecretKey();
       KeyStoreProvider.getInstance().putSecretKey(BACKUP_KEY_ALIAS, secretKey, BACKUP_KEY_PASSWORD);
       String ivHex = generateTestIVHex();
       KeyStoreProvider.getInstance().putPassword(BACKUP_IV_ALIAS, ivHex, BACKUP_IV_PASSWORD);

	// Act.
	TestBackupFileServiceResponse response = this.target.exec(testRequest, this.em);

	// Assert.
	assertEquals(secretKey, response.key);
	assertEquals(ivHex, DatatypeConverter.printHexBinary(response.iv));
}
 
开发者ID:opensecuritycontroller,项目名称:osc-core,代码行数:18,代码来源:BackupFileServiceTest.java


注:本文中的javax.xml.bind.DatatypeConverter类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。