@Override public void verify(DecodedJWT jwt, EncodeType encodeType) throws Exception { byte[] signatureBytes = null; String signature = jwt.getSignature(); String urlDecoded = null; switch (encodeType) { case Base16: urlDecoded = URLDecoder.decode(signature, "UTF-8"); signatureBytes = Hex.decodeHex(urlDecoded); break; case Base32: Base32 base32 = new Base32(); urlDecoded = URLDecoder.decode(signature, "UTF-8"); signatureBytes = base32.decode(urlDecoded); break; case Base64: signatureBytes = Base64.decodeBase64(signature); break; } if (signatureBytes.length > 0) { throw new SignatureVerificationException(this); } }
private static Token makeTokenFromJSON(JSONObject o) throws JSONException { Token tmp = new Token(new Base32().decode(o.getString(SECRET)), o.getString(LABEL), o.getString(TYPE), o.getInt(DIGITS)); tmp.setAlgorithm(o.getString(ALGORITHM)); if (o.getString(TYPE).equals(HOTP)) { tmp.setCounter(o.getInt(COUNTER)); } if (o.getString(TYPE).equals(TOTP)) { tmp.setPeriod(o.getInt(PERIOD)); } if (o.optBoolean(WITHPIN, false)) { tmp.setWithPIN(true); tmp.setPin(o.getString(PIN)); tmp.setLocked(true); } if (o.optBoolean(TAPTOSHOW, false)) { tmp.setWithTapToShow(true); } return tmp; }
private static JSONObject makeJSONfromToken(Token t) throws JSONException { JSONObject o = new JSONObject(); o.put(SECRET, new String(new Base32().encode(t.getSecret()))); o.put(LABEL, t.getLabel()); o.put(DIGITS, t.getDigits()); o.put(ALGORITHM, t.getAlgorithm()); o.put(TYPE, t.getType()); if (t.getType().equals(HOTP)) { o.put(COUNTER, t.getCounter()); } if (t.getType().equals(TOTP)) { o.put(PERIOD, t.getPeriod()); } if (t.isWithPIN()) { o.put(WITHPIN, true); o.put(PIN, t.getPin()); } else { o.put(WITHPIN, false); } if (t.isWithTapToShow()) { o.put(TAPTOSHOW, true); } return o; }
public JWTDecoder(String jwt, EncodeType encodeType) throws Exception { parts = TokenUtils.splitToken(jwt); final JWTParser converter = new JWTParser(); String headerJson = null; String payloadJson = null; switch (encodeType) { case Base16: headerJson = URLDecoder.decode(new String(Hex.decodeHex(parts[0])), "UTF-8"); payloadJson = URLDecoder.decode(new String(Hex.decodeHex(parts[1])), "UTF-8"); break; case Base32: Base32 base32 = new Base32(); headerJson = URLDecoder.decode(new String(base32.decode(parts[0]), "UTF-8")); payloadJson = URLDecoder.decode(new String(base32.decode(parts[1]), "UTF-8")); break; case Base64: headerJson = StringUtils.newStringUtf8(Base64.decodeBase64(parts[0])); payloadJson = StringUtils.newStringUtf8(Base64.decodeBase64(parts[1])); break; } header = converter.parseHeader(headerJson); payload = converter.parsePayload(payloadJson); }
private String signBase32Encoding() throws UnsupportedEncodingException{ Base32 base32 = new Base32(); String header = URLEncoder.encode(headerJson, "UTF-8"); String payload = URLEncoder.encode(payloadJson, "UTF-8"); byte[] bHeader = header.getBytes("UTF-8"); String encodedHeader = base32.encodeAsString(bHeader); byte[] bPayload = payload.getBytes("UTF-8"); String encodedPayload = base32.encodeAsString(bPayload); String content = String.format("%s.%s", encodedHeader, encodedPayload); byte[] signatureBytes = algorithm.sign(content.getBytes(StandardCharsets.UTF_8)); String signature = base32.encodeAsString(signatureBytes); String signatureFinal = URLEncoder.encode(signature, "UTF-8"); return String.format("%s.%s", content, signatureFinal); }
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { Vault v = (Vault) SingleTon.getTon().getExtra(SettingValues.ACTIVE_VAULT.toString()); credential = v.findCredentialByGUID(getArguments().getString(CREDENTIAL)); } handler = new Handler(); otp_refresh = new Runnable() { @Override public void run() { int progress = (int) (System.currentTimeMillis() / 1000) % 30 ; otp_progress.setProgress(progress*100); ObjectAnimator animation = ObjectAnimator.ofInt(otp_progress, "progress", (progress+1)*100); animation.setDuration(1000); animation.setInterpolator(new LinearInterpolator()); animation.start(); otp.setText(TOTPHelper.generate(new Base32().decode(credential.getOtp()))); handler.postDelayed(this, 1000); } }; }
public static String encryptString(String password, String value) { String salt = KeyGenerators.string().generateKey(); SecretKeySpec skeySpec = makeKeySpec(password, salt); byte[] iv = KeyGenerators.secureRandom(16).generateKey(); String ivString = Hex.encodeHexString(iv); try { Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new GCMParameterSpec(128, iv)); /* Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(iv)); */ byte[] encrypted = cipher.doFinal(value.getBytes(Charset.forName("UTF-8"))); String s = StringUtils.strip(new Base32().encodeAsString(encrypted), "=").toLowerCase(); // Strip line breaks s = salt + ivString + s.replaceAll("(\\n|\\r)", ""); return s; } catch (Exception e) { throw new RuntimeException(e); } }
/** * Generates a random secret that is 16 characters long for the client which * is encoded using Base32 according to RFC 3548. * * @return Base32 encoded shared Secret * @throws OTPManagerException * if a failure occur while generating the shared secret */ protected String generateSharedSecret() throws OTPManagerException { LOG.info("Generating shared secret..."); int value = Constants.SECRET_BITS / 8 + Constants.SCRATCH_CODES * Constants.BYTES_PER_SCRATCH_CODE; byte[] sharedSecret = null; byte[] encodedSharedSecret = null; Base32 codec = new Base32(); try { secureRandom = SecureRandom.getInstance(Constants.RANDOM_NUMBER_ALGORITHM); byte[] buffer = new byte[value]; secureRandom.nextBytes(buffer); sharedSecret = Arrays.copyOf(buffer, Constants.SECRET_BITS / 8); encodedSharedSecret = codec.encode(sharedSecret); reSeed(); } catch (Exception e) { LOG.error("Error while generating shared secret " + e.getMessage(), e); throw new OTPManagerException("Error while generating shared secret " + e.getMessage(), e); } LOG.debug("Generated shared secret successfully"); return new String(encodedSharedSecret); }
private int authCodeInternal(long time) throws NoSuchAlgorithmException, InvalidKeyException { long t = time / 30000; byte[] key = new Base32().decode(sharedSecret.toUpperCase().getBytes()); byte[] data = new byte[8]; long value = t; int i = 8; while (true) { int i2 = i - 1; if (i <= 0) { break; } data[i2] = (byte) ((int) value); value >>>= 8; i = i2; } SecretKeySpec signKey = new SecretKeySpec(key, "HmacSHA1"); Mac mac = Mac.getInstance("HmacSHA1"); mac.init(signKey); byte[] hash = mac.doFinal(data); int offset = hash[19] & 15; long truncatedHash = 0; for (int i2 = 0; i2 < 4; i2 += 1) { truncatedHash = (truncatedHash << 8) | ((long) (hash[offset + i2] & 255)); } return (int) ((truncatedHash & 2147483647L) % 1000000); }
public Entry(String contents) throws Exception { contents = contents.replaceFirst("otpauth", "http"); Uri uri = Uri.parse(contents); URL url = new URL(contents); if(!url.getProtocol().equals("http")){ throw new Exception("Invalid Protocol"); } if(!url.getHost().equals("totp")){ throw new Exception(); } String secret = uri.getQueryParameter("secret"); String label = uri.getPath().substring(1); String issuer = uri.getQueryParameter("issuer"); if(issuer != null){ label = issuer +" - "+label; } this.label = label; this.secret = new Base32().decode(secret.toUpperCase()); }
public static boolean isValidOTP(String secret, int code) { if (secret == null) { return false; } else { byte[] buffer = new Base32().decode(secret); long index = getTimeIndexOTP(); if (code == getCodeOTP(buffer, index - 2)) { return true; } else if (code == getCodeOTP(buffer, index - 1)) { return true; } else if (code == getCodeOTP(buffer, index)) { return true; } else if (code == getCodeOTP(buffer, index + 1)) { return true; } else if (code == getCodeOTP(buffer, index + 2)) { return true; } else { return false; } } }
public static boolean checkCode(String secret, long code, long timeMsec) { Base32 codec = new Base32(); byte[] decodedKey = codec.decode(secret); long t = (timeMsec / 1000L) / 30L; for (int i = -WINDOW_SIZE; i <= WINDOW_SIZE; ++i) { long hash; try { hash = computeHash(decodedKey, t + i); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e.getMessage()); } if (hash == code) { return true; } } return false; }
/** Enables two-factor auth for testIdentity, storing parameters in twoFactorData. */ @Before public void twoFactorTestSetup() throws Exception { twoFactorData = new TwoFactorTestData(); // set secret in DB means two factor auth is enabled testIdentity.setTwoFactorSecret(twoFactorData.testSecret); // create testToken and sign it twoFactorData.testToken = GetMyPrivateKey.makeLoginTokenString(testIdentity, twoFactorData.redirectUrl, null); twoFactorData.testSignature = TwoFactorSigningService.signToken(twoFactorData.testToken); // create code as if the google authenticator had Base32 codec = new Base32(); byte[] decodedKey = codec.decode(twoFactorData.testSecret); long t = (System.currentTimeMillis() / 1000L) / 30L; twoFactorData.validTimeCode = Integer.toString(TwoFactorCodeChecker.computeHash(decodedKey, t)); twoFactorData.backupCode = "123456789"; byte[] salt = CryptoForBackupCodes.randSaltGen(); testIdentity.setBackup(0, CryptoForBackupCodes.digest(twoFactorData.backupCode, salt)); manager.identityDao.update(testIdentity); manager.commitTransaction(); }
/** * This method implements the algorithm specified in RFC 6238 to check if a * validation code is valid in a given instant of time for the given secret * key. * * @param secret the Base32 encoded secret key. * @param codeString the code to validate. * @return <code>true</code> if the validation code is valid, * <code>false</code> otherwise. */ public static boolean checkCode(final String secret, final String codeString) { final long code; try { code = Long.parseLong(codeString); } catch(final NumberFormatException e) { return false; } final Base32 codec32 = new Base32(); final byte[] decodedKey = codec32.decode(secret); final long timeWindow = System.currentTimeMillis() / 30000; final int window = 0; for (int i = -((window - 1) / 2); i <= window / 2; ++i) { final long hash = calculateCode(decodedKey, timeWindow + i); if (hash == code) { return true; } } return false; }
/** * Verifies if a code is valid for a given secret. The code is valid for 90 * seconds. The current system time is used in the calculation. * * @param code * The user supplied code to verify * @param secret * The shared secret between the mobile phone and the server * @return true if the code is valid, false if the code is invalid */ public static boolean verifyCode(String code, String secret) { try { // Number of 30 second intervals since epoch long timesteps = System.currentTimeMillis() / 1000L / 30L; byte[] secretBytes = new Base32().decode(secret); int codeInt = Integer.parseInt(code); // A window where the code is valid int window = 1; for (int i = -window; i <= window; i++) { if (hotp(secretBytes, timesteps + i) == codeInt) { return true; } } } catch (Exception e) { // Catch all types of exceptions and return false } return false; }
/** * @param base32Key base32 encoded key * @param timeStepInMills * @return */ public static String getGeneratedValue(String base32Key, long timeStepInMills) { // time step String hexKey = new String(Hex.encode(new Base32().decode(base32Key))); return TOTP.generateTOTP(hexKey, Long.toHexString(System.currentTimeMillis() / timeStepInMills), "6", "HmacSHA1"); }
/** * Creates a new JWT and signs it with the given algorithm * * @param algorithm used to sign the JWT * @param encodeType specifies which base encoding is required * @return a new JWT token * @throws IllegalArgumentException if the provided algorithm is null. * @throws JWTCreationException if the claims could not be converted to a valid JSON or there was a problem with the signing key. */ public String sign(Algorithm algorithm, EncodeType encodeType) throws Exception { if (algorithm == null) { throw new IllegalArgumentException("The Algorithm cannot be null."); } if(encodeType == null) { throw new IllegalArgumentException("Encodetype cannot be null."); } headerClaims.put(PublicClaims.ALGORITHM, algorithm.getName()); headerClaims.put(PublicClaims.TYPE, "JWT"); String signingKeyId = algorithm.getSigningKeyId(); if (signingKeyId != null) { withKeyId(signingKeyId); } JWTCreator jwtCreator = new JWTCreator(algorithm, headerClaims, payloadClaims); String token = null; switch (encodeType) { case Base16: token = jwtCreator.signBase16Encoding(); break; case Base32: token = jwtCreator.signBase32Encoding(); break; case Base64: token = jwtCreator.defaultSign(); break; } return token; }
@Override public void verify(DecodedJWT jwt, EncodeType encodeType) throws Exception { byte[] contentBytes = String.format("%s.%s", jwt.getHeader(), jwt.getPayload()).getBytes(StandardCharsets.UTF_8); byte[] signatureBytes = null; String signature = jwt.getSignature(); String urlDecoded = null; switch (encodeType) { case Base16: urlDecoded = URLDecoder.decode(signature, "UTF-8"); signatureBytes = Hex.decodeHex(urlDecoded); break; case Base32: Base32 base32 = new Base32(); urlDecoded = URLDecoder.decode(signature, "UTF-8"); signatureBytes = base32.decode(urlDecoded); break; case Base64: signatureBytes = Base64.decodeBase64(signature); break; } try { ECPublicKey publicKey = keyProvider.getPublicKeyById(jwt.getKeyId()); if (publicKey == null) { throw new IllegalStateException("The given Public Key is null."); } boolean valid = crypto.verifySignatureFor(getDescription(), publicKey, contentBytes, JOSEToDER(signatureBytes)); if (!valid) { throw new SignatureVerificationException(this); } } catch (NoSuchAlgorithmException | SignatureException | InvalidKeyException | IllegalStateException e) { throw new SignatureVerificationException(this, e); } }
@Override public void verify(DecodedJWT jwt, EncodeType encodeType) throws Exception { byte[] contentBytes = String.format("%s.%s", jwt.getHeader(), jwt.getPayload()).getBytes(StandardCharsets.UTF_8); byte[] signatureBytes = null; String signature = jwt.getSignature(); String urlDecoded = null; switch (encodeType) { case Base16: urlDecoded = URLDecoder.decode(signature, "UTF-8"); signatureBytes = Hex.decodeHex(urlDecoded); break; case Base32: Base32 base32 = new Base32(); urlDecoded = URLDecoder.decode(signature, "UTF-8"); signatureBytes = base32.decode(urlDecoded); break; case Base64: signatureBytes = Base64.decodeBase64(signature); break; } try { boolean valid = crypto.verifySignatureFor(getDescription(), secret, contentBytes, signatureBytes); if (!valid) { throw new SignatureVerificationException(this); } } catch (IllegalStateException | InvalidKeyException | NoSuchAlgorithmException e) { throw new SignatureVerificationException(this, e); } }
@Override public void verify(DecodedJWT jwt, EncodeType encodeType) throws Exception { byte[] contentBytes = String.format("%s.%s", jwt.getHeader(), jwt.getPayload()).getBytes(StandardCharsets.UTF_8); byte[] signatureBytes = null; String signature = jwt.getSignature(); String urlDecoded = null; switch (encodeType) { case Base16: urlDecoded = URLDecoder.decode(signature, "UTF-8"); signatureBytes = Hex.decodeHex(urlDecoded); break; case Base32: Base32 base32 = new Base32(); urlDecoded = URLDecoder.decode(signature, "UTF-8"); signatureBytes = base32.decode(urlDecoded); break; case Base64: signatureBytes = Base64.decodeBase64(signature); break; } try { RSAPublicKey publicKey = keyProvider.getPublicKeyById(jwt.getKeyId()); if (publicKey == null) { throw new IllegalStateException("The given Public Key is null."); } boolean valid = crypto.verifySignatureFor(getDescription(), publicKey, contentBytes, signatureBytes); if (!valid) { throw new SignatureVerificationException(this); } } catch (NoSuchAlgorithmException | SignatureException | InvalidKeyException | IllegalStateException e) { throw new SignatureVerificationException(this, e); } }
public static String newRandomId() { // 120 bits of randomness // a Type 4 UUID has 122 // but multiples of 40 are nicer for BASE-32 // and 160 bits seems overkill (and inconvenient to type) // this will make a 24 digit code byte[] randomBytes = new byte[15]; random.nextBytes(randomBytes); return new Base32().encodeAsString(randomBytes); }
private static String doDecryptString(String password, String encryptedBase32) throws Exception { encryptedBase32 = StringUtils.strip(encryptedBase32, "="); String salt = encryptedBase32.substring(0, 16); String ivString = encryptedBase32.substring(16, 48); byte[] iv = new byte[0]; try { iv = Hex.decodeHex(ivString.toCharArray()); } catch (DecoderException e) { throw new RuntimeException(e); } encryptedBase32 = encryptedBase32.substring(48); Base32 decoder = new Base32(); byte[] encrypted = decoder.decode(encryptedBase32.toUpperCase()); SecretKeySpec skeySpec = makeKeySpec(password, salt); /* Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, skeySpec, new IvParameterSpec(iv)); */ Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); cipher.init(Cipher.DECRYPT_MODE, skeySpec, new GCMParameterSpec(128, iv)); byte[] original = cipher.doFinal(encrypted); return new String(original, Charset.forName("UTF-8")); }
/** * Psuedo-random string of the given length, in base32 characters * @param length * @return */ public static String randomTokenBase32(int length) { byte[] r = new byte[256]; //Means 2048 bit new Random().nextBytes(r); String s = new Base32().encodeAsString(r).substring(0, length).toLowerCase(); return s; }
public static String getOtpSecret(final String username, final String salt) { // User specific secret is combined with global secret as salt to generate time-based OTP codes // Only first 10 bytes is used, so SHA1 (10 bytes) is plenty final byte[] keyMaterial = DigestUtils.sha1(salt + username); final byte[] secretKey = Arrays.copyOf(keyMaterial, Math.max(10, keyMaterial.length)); return new String(new Base32().encode(secretKey)); }
public static String getRandomSecretKey() { SecureRandom random = new SecureRandom(); byte[] bytes = new byte[20]; random.nextBytes(bytes); Base32 base32 = new Base32(); String secretKey = base32.encodeToString(bytes); // make the secret key more human-readable by lower-casing and // inserting spaces between each group of 4 characters return secretKey.toLowerCase().replaceAll("(.{4})(?=.{4})", "$1 "); }
public static String getTOTPCode(String secretKey) { String normalizedBase32Key = secretKey.replace(" ", "").toUpperCase(); Base32 base32 = new Base32(); byte[] bytes = base32.decode(normalizedBase32Key); String hexKey = Hex.encodeHexString(bytes); long time = (System.currentTimeMillis() / 1000) / 30; String hexTime = Long.toHexString(time); return TOTP.generateTOTP(hexKey, hexTime, "6"); }
public ReplicatorItem(String secret_key, String name_deliver, String name_account, String digits) { this.name_deliver = name_deliver; Base32 base32 = new Base32(); this.secret_key = base32.decode(secret_key.replaceAll("\\s+", "").toUpperCase().getBytes()); this.name_account = name_account; this.digits = Integer.parseInt(digits); }
@Test public void testDecodeBase32() { Random random = new Random(); random.nextBytes(new byte[100]); Base32 base32 = new Base32(); for (int i = 0; i < 10000; i++) { byte[] bytes = new byte[random.nextInt(10) + 1]; random.nextBytes(bytes); String encoded = base32.encodeAsString(bytes); byte[] expected = base32.decode(encoded); byte[] actual = TimeBasedOneTimePasswordUtil.decodeBase32(encoded); assertArrayEquals(expected, actual); } }
@Test public void testBadBase32() { String[] strings = new String[] { "A", "AB", "ABC", "ABCD", "ABCDE", "ABCDEF", "ABCDEFG", "ABCDEFGH", "ABCDEFGHI" }; Base32 base32 = new Base32(); for (String str : strings) { byte[] decoded = TimeBasedOneTimePasswordUtil.decodeBase32(str); String encoded = base32.encodeAsString(decoded); byte[] result = TimeBasedOneTimePasswordUtil.decodeBase32(encoded); // System.out.println(str + " becomes " + encoded); assertArrayEquals(decoded, result); } }
public JSONObject toJSON() throws JSONException { JSONObject jsonObj = new JSONObject(); jsonObj.put(JSON_SECRET, new String(new Base32().encode(getSecret()))); jsonObj.put(JSON_LABEL, getLabel()); return jsonObj; }
public void testEntry() throws JSONException { byte secret[] = "Das System ist sicher".getBytes(); String label = "5 von 5 Sterne"; String s = "{\"secret\":\""+ new String(new Base32().encode(secret)) +"\",\"label\":\"" + label + "\"}"; Entry e = new Entry(new JSONObject(s)); assertTrue(Arrays.equals(secret, e.getSecret())); assertEquals(label, e.getLabel()); assertEquals(s, e.toJSON()+""); }
/** * Converts a string to a byte array. * * @param base32String The input Base32 string. * @return The output byte array. */ public static byte[] getBytes(final String base32String) { final Base32 codec = new Base32(); final byte[] encodedBytes = StringEncoder.getBytes(base32String); if (!codec.isInAlphabet(encodedBytes, true)) { throw new IllegalArgumentException("malformed base32 string passed to getBytes"); } return codec.decode(encodedBytes); }
/** * Generate the secrete key for mobile devices. * * @return */ public static String calculateSecretKey() throws NoSuchAlgorithmException { byte[] secretKey = new byte[10]; SecureRandom sha1Prng = SecureRandom.getInstance("SHA1PRNG"); sha1Prng.nextBytes(secretKey); Base32 codec = new Base32(); byte[] encodedKey = codec.encode(secretKey); return new String(encodedKey); }
public static String generateSecretKey() { byte[] buffer = new byte[SECRET_SIZE]; secureRandom.nextBytes(buffer); Base32 codec = new Base32(); byte[] secretKey = Arrays.copyOf(buffer, SECRET_SIZE); byte[] bEncodedKey = codec.encode(secretKey); String encodedKey = new String(bEncodedKey, Charsets.UTF_8); return encodedKey; }
public static boolean verifyCode(String secret, int code, int variance) { long timeIndex = System.currentTimeMillis() / 1000 / 30; byte[] secretBytes = new Base32().decode(secret); for (int i = -variance; i <= variance; i++) { if (getCode(secretBytes, timeIndex + i) == code) { return true; } } return false; }
protected static char[] encodeCheck(VersionByte versionByte, byte[] data) { try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); outputStream.write(versionByte.getValue()); outputStream.write(data); byte payload[] = outputStream.toByteArray(); byte checksum[] = StrKey.calculateChecksum(payload); outputStream.write(checksum); byte unencoded[] = outputStream.toByteArray(); Base32 base32Codec = new Base32(); byte[] bytesEncoded = base32Codec.encode(unencoded); char[] charsEncoded = new char[bytesEncoded.length]; for (int i = 0; i < bytesEncoded.length; i++) { charsEncoded[i] = (char) bytesEncoded[i]; } if (VersionByte.SEED == versionByte) { Arrays.fill(unencoded, (byte) 0); Arrays.fill(payload, (byte) 0); Arrays.fill(bytesEncoded, (byte) 0); } return charsEncoded; } catch (IOException e) { throw new AssertionError(e); } }
protected static byte[] decodeCheck(VersionByte versionByte, char[] encoded) { byte[] bytes = new byte[encoded.length]; for (int i = 0; i < encoded.length; i++) { if (encoded[i] > 127) { throw new IllegalArgumentException("Illegal characters in encoded char array."); } bytes[i] = (byte) encoded[i]; } Base32 base32Codec = new Base32(); byte[] decoded = base32Codec.decode(bytes); byte decodedVersionByte = decoded[0]; byte[] payload = Arrays.copyOfRange(decoded, 0, decoded.length-2); byte[] data = Arrays.copyOfRange(payload, 1, payload.length); byte[] checksum = Arrays.copyOfRange(decoded, decoded.length-2, decoded.length); if (decodedVersionByte != versionByte.getValue()) { throw new FormatException("Version byte is invalid"); } byte[] expectedChecksum = StrKey.calculateChecksum(payload); if (!Arrays.equals(expectedChecksum, checksum)) { throw new FormatException("Checksum invalid"); } if (VersionByte.SEED.getValue() == decodedVersionByte) { Arrays.fill(bytes, (byte) 0); Arrays.fill(decoded, (byte) 0); Arrays.fill(payload, (byte) 0); } return data; }
public FileEventStore(String projectId, File root) throws IOException { if (!root.exists() || !root.isDirectory()) { throw new IOException("The root directory '" + root + "' does not exist or is not a directory."); } this.root = new File(root, projectId); this.base32 = new Base32(); }
public static String generateHSDescriptor(RSAPublicKey pk, RSAPrivateKey prk) throws IOException { String serviceb32 = publicKeyToOnion(pk); StringBuilder desc = new StringBuilder(); desc.append("rendezvous-service-descriptor "+new Base32().encodeAsString(getDescId(serviceb32, (byte)0)).toLowerCase()+"\n"); desc.append("version 2\n"); desc.append("permanent-key\n-----BEGIN RSA PUBLIC KEY-----\n"); desc.append(MiscUtil.stringMaxWidth(Base64.toBase64String(TorCrypto.publicKeyToASN1(pk)),64)); desc.append("\n-----END RSA PUBLIC KEY-----\n"); desc.append("secret-id-part "+new Base32().encodeAsString(getSecretId(serviceb32, (byte)0)).toLowerCase()+"\n"); DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); desc.append("publication-time "+df.format(new Date())+"\n"); desc.append("protocol-versions 2,3\n"); desc.append("introduction-points\n" + "-----BEGIN MESSAGE-----\n"); desc.append(MiscUtil.stringMaxWidth(Base64.toBase64String("nothing to see :-)".getBytes()),64)); desc.append("\n-----END MESSAGE-----\n" + "signature\n"); byte sig[]; try { Signature instance = Signature.getInstance("SHA1withRSA"); instance.initSign(prk); instance.update(desc.toString().getBytes()); sig = instance.sign(); } catch (InvalidKeyException | NoSuchAlgorithmException |SignatureException e) { e.printStackTrace(); return null; } desc.append("-----BEGIN SIGNATURE-----\n"); desc.append(MiscUtil.stringMaxWidth(Base64.toBase64String(sig),64)); desc.append("\n-----END SIGNATURE-----\n"); return desc.toString(); }
/** * @param secret * @param lengthToken * @return */ public static long getOneTimePassword(String secret, int lengthToken) { HorusTOTP.setSecretKey(secret); Base32 codec = new Base32(); byte[] data = new byte[8]; long value = (new Date().getTime()) / TimeUnit.SECONDS.toMillis(30); for (int i = 8; i-- > 0; value >>>= 8) { data[i] = (byte) value; } SecretKeySpec signKey = new SecretKeySpec(codec.decode(secretKey), "HmacSHA1"); try { Mac mac = Mac.getInstance("HmacSHA1"); mac.init(signKey); byte[] hash = mac.doFinal(data); int offset = hash[20 - 1] & 0xF; long truncatedHash = 0; for (int i = 0; i < 4; ++i) { truncatedHash <<= 8; truncatedHash |= (hash[offset + i] & 0xFF); } truncatedHash &= 0x7FFFFFFF; truncatedHash %= 1000 * 1000; return truncatedHash; } catch (Exception e) { e.printStackTrace(); return 0; } }