List of usage examples for org.bouncycastle.util.encoders Hex toHexString
public static String toHexString(byte[] data)
From source file:SampleUser.java
License:Open Source License
/** * Save the state of this user to the key value store. *///from www .j av a 2 s .c o m void saveState() { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(this); oos.flush(); keyValStore.setValue(keyValStoreName, Hex.toHexString(bos.toByteArray())); bos.close(); } catch (IOException e) { e.printStackTrace(); } }
From source file:bisq.common.crypto.Encryption.java
License:Open Source License
public static byte[] decryptPayloadWithHmac(byte[] encryptedPayloadWithHmac, SecretKey secretKey) throws CryptoException { byte[] payloadWithHmac = decrypt(encryptedPayloadWithHmac, secretKey); String payloadWithHmacAsHex = Hex.toHexString(payloadWithHmac); // first part is raw message int length = payloadWithHmacAsHex.length(); int sep = length - 64; String payloadAsHex = payloadWithHmacAsHex.substring(0, sep); // last 64 bytes is hmac String hmacAsHex = payloadWithHmacAsHex.substring(sep, length); if (verifyHmac(Hex.decode(payloadAsHex), Hex.decode(hmacAsHex), secretKey)) { return Hex.decode(payloadAsHex); } else {//from w w w. j a v a2 s . co m throw new CryptoException("Hmac does not match."); } }
From source file:bisq.price.spot.providers.BitcoinAverage.java
License:Open Source License
protected String getAuthSignature() { String payload = String.format("%s.%s", Instant.now().getEpochSecond(), pubKey); return String.format("%s.%s", payload, Hex.toHexString(mac.doFinal(payload.getBytes(Charsets.UTF_8)))); }
From source file:ca.trustpoint.m2m.AuthorityKeyIdentifier.java
License:Apache License
/** * Converts this instance to its string representation using the given indentation level. * * @param depth Indentation level.//from ww w .j a va2 s.co m * @return String representation of this instance at the given indentation level. */ public String toString(int depth) { StringBuffer buffer = new StringBuffer(); final String LINE_SEPARATOR = System.getProperty("line.separator"); FormattingUtils.indent(buffer, depth).append("AuthKeyId SEQUENCE {").append(LINE_SEPARATOR); if (keyIdentifier != null) { FormattingUtils.indent(buffer, depth + 1).append("[0] keyIdentifier OCTET STRING: "); buffer.append(Hex.toHexString(keyIdentifier)).append(LINE_SEPARATOR); } if (certificateIssuer != null) { FormattingUtils.indent(buffer, depth + 1).append("[1] authCertIssuer GeneralName: ") .append(LINE_SEPARATOR); buffer.append(certificateIssuer.toString(depth + 2)); } if (certificateSerialNumber != null) { FormattingUtils.indent(buffer, depth + 1).append("[2] authCertSerialNum OCTET STRING: "); buffer.append(Hex.toHexString(certificateSerialNumber.toByteArray())).append(LINE_SEPARATOR); } FormattingUtils.indent(buffer, depth).append("}").append(LINE_SEPARATOR); return buffer.toString(); }
From source file:ca.trustpoint.m2m.KeyAlgorithmDefinition.java
License:Apache License
/** * Returns the string representation of the signature algorithm parameters. * * @return The string representation of the signature algorithm parameters. *//*from www.j av a2 s . com*/ public String toStringParameters() { if (algorithm != null) { return ("OCTET STRING: " + Hex.toHexString(parameters)); } return null; }
From source file:ca.trustpoint.m2m.M2mCertificate.java
License:Apache License
/** * Converts this instance to its string representation using the given indentation level. * * @param depth Indentation level.//from w ww. java 2 s . com * @return String representation of this instance at the given indentation level. */ public String toString(int depth) { StringBuffer buffer = new StringBuffer(); final String LINE_SEPARATOR = System.getProperty("line.separator"); FormattingUtils.indent(buffer, depth).append("M2MCertificate [APPLICATION 20] SEQUENCE {") .append(LINE_SEPARATOR); FormattingUtils.indent(buffer, depth + 1).append("[0] tbsCertificate TBSCertificate: ") .append(LINE_SEPARATOR); FormattingUtils.indent(buffer, depth + 2).append("TBSCertificate SEQUENCE {").append(LINE_SEPARATOR); FormattingUtils.indent(buffer, depth + 3).append("[ 0] version INTEGER: "); buffer.append(VERSION).append(LINE_SEPARATOR); if (serialNumber != null) { FormattingUtils.indent(buffer, depth + 3).append("[ 1] serialNumber OCTET STRING: "); buffer.append(Hex.toHexString(serialNumber)).append(LINE_SEPARATOR); } if (caKeyDefinition != null) { if (caKeyDefinition.getAlgorithm() != null) { FormattingUtils.indent(buffer, depth + 3).append("[ 2] cAAlgorithm OBJECT IDENTIFIER: "); buffer.append(caKeyDefinition.getAlgorithm().getOid()).append(LINE_SEPARATOR); } if (caKeyDefinition.getParameters() != null) { FormattingUtils.indent(buffer, depth + 3).append("[ 3] cAAlgParams OCTET STRING: "); buffer.append(Hex.toHexString(caKeyDefinition.getParameters())).append(LINE_SEPARATOR); } } if (issuer != null) { FormattingUtils.indent(buffer, depth + 3).append("[ 4] issuer Name: ").append(LINE_SEPARATOR); buffer.append(issuer.toString(depth + 4)); } if (validFrom != null) { FormattingUtils.indent(buffer, depth + 3).append("[ 5] validFrom OCTET STRING: "); buffer.append(Hex.toHexString(BigInteger.valueOf(validFrom.getTime() / 1000).toByteArray())) .append(LINE_SEPARATOR); } if (validDuration != null) { FormattingUtils.indent(buffer, depth + 3).append("[ 6] validDuration OCTET STRING: "); buffer.append(validDuration).append(LINE_SEPARATOR); } if (subject != null) { FormattingUtils.indent(buffer, depth + 3).append("[ 7] subject Name: ").append(LINE_SEPARATOR); buffer.append(subject.toString(depth + 4)); } if (publicKeyDefinition != null) { if (publicKeyDefinition.getAlgorithm() != null) { FormattingUtils.indent(buffer, depth + 3).append("[ 8] pKAlgorithm OBJECT IDENTIFIER: "); buffer.append(publicKeyDefinition.getAlgorithm()).append(LINE_SEPARATOR); } if (publicKeyDefinition.getParameters() != null) { FormattingUtils.indent(buffer, depth + 3).append("[ 9] pKAlgParams OCTET STRING: "); buffer.append(Hex.toHexString(publicKeyDefinition.getParameters())).append(LINE_SEPARATOR); } } if (publicKey != null) { FormattingUtils.indent(buffer, depth + 3).append("[10] pubKey OCTET STRING: "); buffer.append(Hex.toHexString(publicKey.getEncoded())).append(LINE_SEPARATOR); } if (authorityKeyIdentifier != null) { FormattingUtils.indent(buffer, depth + 3).append("[11] authKeyId OCTET STRING: ") .append(LINE_SEPARATOR); buffer.append(authorityKeyIdentifier.toString(depth + 4)).append(LINE_SEPARATOR); } if (subjectKeyIdentifier != null) { FormattingUtils.indent(buffer, depth + 3).append("[12] subjKeyId OCTET STRING: "); buffer.append(Hex.toHexString(subjectKeyIdentifier)).append(LINE_SEPARATOR); } if (keyUsage != null) { FormattingUtils.indent(buffer, depth + 3).append("[13] keyUsage OCTET STRING: "); buffer.append(keyUsage.toString(depth + 4)).append(LINE_SEPARATOR); } if (basicConstraints != null) { FormattingUtils.indent(buffer, depth + 3).append("[14] basicConstraints INTEGER: "); buffer.append(basicConstraints).append(LINE_SEPARATOR); } if (certificatePolicy != null) { FormattingUtils.indent(buffer, depth + 3).append("[15] certificatePolicy OBJECT IDENTIFIER: "); buffer.append(certificatePolicy).append(LINE_SEPARATOR); } if (subjectAlternativeName != null) { FormattingUtils.indent(buffer, depth + 3).append("[16] subjectAltName GeneralName: "); buffer.append(subjectAlternativeName.toString(depth + 4)).append(LINE_SEPARATOR); } if (issuerAlternativeName != null) { FormattingUtils.indent(buffer, depth + 3).append("[17] issuerAltName GeneralName: "); buffer.append(issuerAlternativeName.toString(depth + 4)).append(LINE_SEPARATOR); } if (extendedKeyUsage != null) { FormattingUtils.indent(buffer, depth + 3).append("[18] extendedKeyUsage OBJECT IDENTIFIER: "); buffer.append(extendedKeyUsage).append(LINE_SEPARATOR); } if (authenticationInfoAccessOcsp != null) { FormattingUtils.indent(buffer, depth + 3).append("[19] authInfoAccess IA5String: "); buffer.append(authenticationInfoAccessOcsp.toString()).append(LINE_SEPARATOR); } if (crlDistributionPointUri != null) { FormattingUtils.indent(buffer, depth + 3).append("[20] cRLDistribPoint IA5String: "); buffer.append(crlDistributionPointUri.toString()).append(LINE_SEPARATOR); } if (!extensions.isEmpty()) { FormattingUtils.indent(buffer, depth + 3).append("[21] x509extensions:").append(LINE_SEPARATOR); FormattingUtils.indent(buffer, depth + 4).append("X509Extensions SEQUENCE {").append(LINE_SEPARATOR); for (int i = 0; i < extensions.size(); i++) { Extension e = extensions.get(i); FormattingUtils.indent(buffer, depth + 5).append("[").append(i).append("] Extension SEQUENCE {") .append(LINE_SEPARATOR); FormattingUtils.indent(buffer, depth + 6).append("extnId OBJECT IDENTIFIER: "); buffer.append(e.oid).append(LINE_SEPARATOR); FormattingUtils.indent(buffer, depth + 6).append("criticality BOOLEAN: "); buffer.append((e.isCritical ? "TRUE" : "FALSE")).append(LINE_SEPARATOR); if (e.value != null) { FormattingUtils.indent(buffer, depth + 6).append("extnValue OCTET STRING: "); buffer.append(Hex.toHexString(e.value)).append(LINE_SEPARATOR); } FormattingUtils.indent(buffer, depth + 5).append("}").append(LINE_SEPARATOR); } FormattingUtils.indent(buffer, depth + 4).append("}").append(LINE_SEPARATOR); } if (caCalcValue != null) { ASN1Sequence caCalcValueSequence = null; // The caCalcValue is an ASN1Sequence for non-ECQV certificate but not for ECQV // certificate, so exception may be encountered try { caCalcValueSequence = ASN1Sequence.getInstance(caCalcValue); } catch (Exception e) { // Not an ASN1Sequence caCalcValueSequence = null; } if (caCalcValueSequence != null) { FormattingUtils.indent(buffer, depth + 1).append("[1] cACalcValue OCTET STRING representing: ") .append(LINE_SEPARATOR); FormattingUtils.indent(buffer, depth + 2).append("SEQUENCE {").append(LINE_SEPARATOR); for (int i = 0; i < caCalcValueSequence.size(); i++) { try { FormattingUtils.indent(buffer, depth + 3).append("INTEGER: ") .append(Hex.toHexString( caCalcValueSequence.getObjectAt(i).toASN1Primitive().getEncoded())) .append(LINE_SEPARATOR); } catch (IOException ex) { // Do nothing. } } FormattingUtils.indent(buffer, depth + 2).append("}").append(LINE_SEPARATOR); } else { FormattingUtils.indent(buffer, depth + 1).append("[1] cACalcValue OCTET STRING: "); buffer.append(Hex.toHexString(caCalcValue)).append(LINE_SEPARATOR); } } FormattingUtils.indent(buffer, depth).append("}").append(LINE_SEPARATOR); return buffer.toString(); }
From source file:ca.trustpoint.m2m.M2mCertificateFactory.java
License:Apache License
/** * Parses ASN.1 tagged object to construct an {@link EntityNameAttribute} object. * * @param obj ASN.1 tagged object for {@link EntityNameAttribute}. * @return An instance of {@link EntityNameAttribute} constructed from obj. * @throw IOException if parsing has error or unknown ID or no value. *//* w w w . jav a 2 s . c o m*/ private EntityNameAttribute parseEntityNameAttribute(ASN1TaggedObject obj) throws IOException { EntityNameAttributeId aid = EntityNameAttributeId.getInstance(obj.getTagNo()); String value = null; switch (aid) { case Country: case DistinguishedNameQualifier: case SerialNumber: value = DERPrintableString.getInstance(obj, false).getString(); break; case Organization: case OrganizationalUnit: case StateOrProvince: case Locality: case CommonName: value = DERUTF8String.getInstance(obj, false).getString(); break; case DomainComponent: value = DERIA5String.getInstance(obj, false).getString(); break; case RegisteredId: value = ASN1ObjectIdentifier.getInstance(obj, false).getId(); break; case OctetsName: byte[] octets = ASN1OctetString.getInstance(obj, false).getOctets(); value = Hex.toHexString(octets); break; default: throw new IOException("unknown entity name attribute id: " + aid.getIndexId()); } if (value == null) { throw new IOException("null entity name attribute value for id: " + aid.getIndexId()); } EntityNameAttribute attribute = new EntityNameAttribute(); attribute.setId(aid); attribute.setValue(value); if (!attribute.isValid()) { throw new IOException("invalid entity name attribute value for id: " + aid.getIndexId()); } return attribute; }
From source file:ch.lamacrypt.internal.crypto.GCMCipher.java
License:Open Source License
/** * Decrypts a given file with AES-256 in GCM mode of operation * * @param outputFile/*from w w w.jav a2 s . com*/ * @return * @throws java.io.IOException * @throws java.security.InvalidKeyException * @throws java.security.InvalidAlgorithmParameterException * @throws javax.crypto.BadPaddingException * @throws javax.crypto.IllegalBlockSizeException */ protected int decrypt_V00(File outputFile) throws IOException, InvalidKeyException, InvalidAlgorithmParameterException, BadPaddingException, IllegalBlockSizeException { updateStatus("Reading header"); // getting file size and calculating iterCnt long fileSize = dis.readLong(), dlSize = fileSize + GCM_TAG_BITS / 8, iterCnt = dlSize / BUFFER_SIZE, percentage = dlSize / 100L, bytesRead = 0L; // defining output stream OutputStream output = new FileOutputStream(outputFile); // getting the encryption password char[] pass = DefaultCipher.getEncryptionPassword(); // reading header byte[] header = new byte[234]; dis.read(header, 0, 234); // reading Sx, Nx, scrypt factors and generating K1 final byte[] S1 = Arrays.copyOfRange(header, 0, VS1), N1 = Arrays.copyOfRange(header, VS1, S1N1), K1_N = Arrays.copyOfRange(header, S1N1, N1K1N), S2 = Arrays.copyOfRange(header, K1NR, RS2), N2 = Arrays.copyOfRange(header, RS2, S2N2), K2_N = Arrays.copyOfRange(header, S2N2, N2K2N); final int K1_N_bak = (int) Math.pow(2, Integer.valueOf(Hex.toHexString(K1_N), 16)), K2_N_bak = (int) Math.pow(2, Integer.valueOf(Hex.toHexString(K2_N), 16)); final SecretKey K1 = new SecretKeySpec( SCrypt.generate(GPCrypto.charToByte(pass), S1, K1_N_bak, KDF_r, KDF_p, CIPHER_KEY_BITS / 8), 0, CIPHER_KEY_BITS / 8, "AES"); // reading E(K1, N1, R) this.cipher.init(Cipher.DECRYPT_MODE, K1, new GCMParameterSpec(GCM_TAG_BITS, N1, 0, GCM_NONCE_BYTES)); boolean failFree = true, AEADBadTag = false; byte[] R = new byte[64]; try { R = cipher.doFinal(Arrays.copyOfRange(header, N1K1N, K1NR)); } catch (IllegalBlockSizeException | BadPaddingException e) { failFree = false; updateStatus("Error"); if (e instanceof javax.crypto.AEADBadTagException) { AEADBadTag = true; } } dos.writeBoolean(failFree); // decrypting file if no exception has been caught if (failFree) { // generating K2 final SecretKey K2 = new SecretKeySpec( SCrypt.generate(R, S2, K2_N_bak, KDF_r, KDF_p, CIPHER_KEY_BITS / 8), 0, CIPHER_KEY_BITS / 8, "AES"); updateStatus("Downloading (0%)"); this.cipher.init(Cipher.DECRYPT_MODE, K2, new GCMParameterSpec(GCM_TAG_BITS, N2, 0, GCM_NONCE_BYTES)); if (dlSize > BUFFER_SIZE) { if (dlSize % BUFFER_SIZE == 0) { iterCnt--; } // reading full blocks for (long i = 0; i < iterCnt; i++) { dis.readFully(buf); output.write(this.cipher.update(buf)); bytesRead += BUFFER_SIZE; if (bytesRead % percentage > 1) { updateStatus("Downloading (" + bytesRead / percentage + "%)"); } } // reading last chunk if (dlSize % BUFFER_SIZE != 0) { r = dis.read(buf, 0, (int) dlSize % BUFFER_SIZE); output.write(this.cipher.doFinal(buf, 0, r)); } else { dis.readFully(buf); output.write(this.cipher.doFinal(buf)); } } else { r = dis.read(buf, 0, (int) dlSize); output.write(this.cipher.doFinal(buf, 0, r)); } // erasing cryptographic parameters and closing streams updateStatus("Finalizing"); GPCrypto.eraseByteArrays(header, S1, S2, N1, N2, R); GPCrypto.eraseKeys(K1, K2); GPCrypto.sanitize(pass); output.close(); return dis.readInt(); } else { // erasing cryptographic parameters and closing streams GPCrypto.eraseByteArrays(header, S1, S2, N1, N2, R); GPCrypto.eraseKeys(K1); GPCrypto.sanitize(pass); output.close(); if (AEADBadTag) { return AEAD_EXCEPTION; } else { return 5; } } }
From source file:ch.lamacrypt.internal.crypto.GCMCipher.java
License:Open Source License
protected static String getKey_V00(byte[] header) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException { // getting the encryption password char[] pass = DefaultCipher.getEncryptionPassword(); // reading Sx, Nx, scrypt factors and generating K1 final byte[] S1 = Arrays.copyOfRange(header, 0, VS1), N1 = Arrays.copyOfRange(header, VS1, S1N1), K1_N = Arrays.copyOfRange(header, S1N1, N1K1N), S2 = Arrays.copyOfRange(header, K1NR, RS2), N2 = Arrays.copyOfRange(header, RS2, S2N2), K2_N = Arrays.copyOfRange(header, S2N2, N2K2N); final int K1_N_bak = (int) Math.pow(2, Integer.valueOf(Hex.toHexString(K1_N), 16)), K2_N_bak = (int) Math.pow(2, Integer.valueOf(Hex.toHexString(K2_N), 16)); final SecretKey K1 = new SecretKeySpec( SCrypt.generate(GPCrypto.charToByte(pass), S1, K1_N_bak, KDF_r, KDF_p, CIPHER_KEY_BITS / 8), 0, CIPHER_KEY_BITS / 8, "AES"); // reading E(K1, N1, R) Cipher cipher = Cipher.getInstance(CIPHER); cipher.init(Cipher.DECRYPT_MODE, K1, new GCMParameterSpec(GCM_TAG_BITS, N1, 0, GCM_NONCE_BYTES)); byte[] R = new byte[64]; boolean failFree = true; try {/*from ww w . ja v a2s . co m*/ R = cipher.doFinal(Arrays.copyOfRange(header, N1K1N, K1NR)); } catch (IllegalBlockSizeException | BadPaddingException ex) { failFree = false; } if (failFree) { // generating K2 final SecretKey K2 = new SecretKeySpec( SCrypt.generate(R, S2, K2_N_bak, KDF_r, KDF_p, CIPHER_KEY_BITS / 8), 0, CIPHER_KEY_BITS / 8, "AES"); GPCrypto.eraseByteArrays(header, S1, S2, N1, N2, R); GPCrypto.eraseKeys(K1); GPCrypto.sanitize(pass); return Hex.toHexString(K2.getEncoded()); } else { GPCrypto.eraseByteArrays(header, S1, S2, N1, N2, R); GPCrypto.eraseKeys(K1); GPCrypto.sanitize(pass); return "error"; } }
From source file:ch.lamacrypt.internal.crypto.GPCrypto.java
License:Open Source License
/** * Formats the hash in the following format: * <p>// w w w .java 2 s.c om * N$r$p$salt$digest * * @param hash * @param salt * * @return * * @throws UnsupportedEncodingException */ public static String encodeDigest(byte[] hash, byte[] salt) throws UnsupportedEncodingException { return KDF_N + "$" + KDF_r + "$" + KDF_p + "$" + Hex.toHexString(salt) + "$" + Hex.toHexString(hash); }