當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。