本文整理匯總了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;
}
}
示例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();
}
示例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;
}
示例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;
}
示例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;
}
示例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;
}
示例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;
}
}
示例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);
}
}
示例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));
}
}
示例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);
}
示例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;
}
示例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;
}
}
示例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);
}
示例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());
}
示例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));
}