List of usage examples for org.bouncycastle.util.encoders Base64 encode
public static byte[] encode(byte[] data)
From source file:com.android.internal.backup.LocalTransport.java
License:Apache License
public int performBackup(PackageInfo packageInfo, ParcelFileDescriptor data) { if (DEBUG)/*from ww w .j av a 2 s. c o m*/ Log.v(TAG, "performBackup() pkg=" + packageInfo.packageName); File packageDir = new File(mDataDir, packageInfo.packageName); packageDir.mkdirs(); // Each 'record' in the restore set is kept in its own file, named by // the record key. Wind through the data file, extracting individual // record operations and building a set of all the updates to apply // in this update. BackupDataInput changeSet = new BackupDataInput(data.getFileDescriptor()); try { int bufSize = 512; byte[] buf = new byte[bufSize]; while (changeSet.readNextHeader()) { String key = changeSet.getKey(); String base64Key = new String(Base64.encode(key.getBytes())); File entityFile = new File(packageDir, base64Key); int dataSize = changeSet.getDataSize(); if (DEBUG) Log.v(TAG, "Got change set key=" + key + " size=" + dataSize + " key64=" + base64Key); if (dataSize >= 0) { if (entityFile.exists()) { entityFile.delete(); } FileOutputStream entity = new FileOutputStream(entityFile); if (dataSize > bufSize) { bufSize = dataSize; buf = new byte[bufSize]; } changeSet.readEntityData(buf, 0, dataSize); if (DEBUG) Log.v(TAG, " data size " + dataSize); try { entity.write(buf, 0, dataSize); } catch (IOException e) { Log.e(TAG, "Unable to update key file " + entityFile.getAbsolutePath()); return BackupConstants.TRANSPORT_ERROR; } finally { entity.close(); } } else { entityFile.delete(); } } return BackupConstants.TRANSPORT_OK; } catch (IOException e) { // oops, something went wrong. abort the operation and return error. Log.v(TAG, "Exception reading backup input:", e); return BackupConstants.TRANSPORT_ERROR; } }
From source file:com.android.sdklib.internal.build.SignedJarBuilder.java
License:Apache License
/** Writes a .SF file with a digest to the manifest. */ private void writeSignatureFile(OutputStream out) throws IOException, GeneralSecurityException { Manifest sf = new Manifest(); Attributes main = sf.getMainAttributes(); main.putValue("Signature-Version", "1.0"); main.putValue("Created-By", "1.0 (Android)"); Base64 base64 = new Base64(); MessageDigest md = MessageDigest.getInstance(DIGEST_ALGORITHM); PrintStream print = new PrintStream(new DigestOutputStream(new ByteArrayOutputStream(), md), true, SdkConstants.UTF_8);/* w ww . j a va 2 s . c om*/ // Digest of the entire manifest mManifest.write(print); print.flush(); main.putValue(DIGEST_MANIFEST_ATTR, new String(base64.encode(md.digest()), "ASCII")); Map<String, Attributes> entries = mManifest.getEntries(); for (Map.Entry<String, Attributes> entry : entries.entrySet()) { // Digest of the manifest stanza for this entry. print.print("Name: " + entry.getKey() + "\r\n"); for (Map.Entry<Object, Object> att : entry.getValue().entrySet()) { print.print(att.getKey() + ": " + att.getValue() + "\r\n"); } print.print("\r\n"); print.flush(); Attributes sfAttr = new Attributes(); sfAttr.putValue(DIGEST_ATTR, new String(base64.encode(md.digest()), "ASCII")); sf.getEntries().put(entry.getKey(), sfAttr); } CountOutputStream cout = new CountOutputStream(out); sf.write(cout); // A bug in the java.util.jar implementation of Android platforms // up to version 1.6 will cause a spurious IOException to be thrown // if the length of the signature file is a multiple of 1024 bytes. // As a workaround, add an extra CRLF in this case. if ((cout.size() % 1024) == 0) { cout.write('\r'); cout.write('\n'); } }
From source file:com.android.signapk.SignApk.java
License:Apache License
/** * Add the hash(es) of every file to the manifest, creating it if * necessary.//w w w. ja va 2s. c om */ private static Manifest addDigestsToManifest(JarFile jar, int hashes) throws IOException, GeneralSecurityException { Manifest input = jar.getManifest(); Manifest output = new Manifest(); Attributes main = output.getMainAttributes(); if (input != null) { main.putAll(input.getMainAttributes()); } else { main.putValue("Manifest-Version", "1.0"); main.putValue("Created-By", "1.0 (Android SignApk)"); } MessageDigest md_sha1 = null; MessageDigest md_sha256 = null; if ((hashes & USE_SHA1) != 0) { md_sha1 = MessageDigest.getInstance("SHA1"); } if ((hashes & USE_SHA256) != 0) { md_sha256 = MessageDigest.getInstance("SHA256"); } byte[] buffer = new byte[4096]; int num; // We sort the input entries by name, and add them to the // output manifest in sorted order. We expect that the output // map will be deterministic. TreeMap<String, JarEntry> byName = new TreeMap<String, JarEntry>(); for (Enumeration<JarEntry> e = jar.entries(); e.hasMoreElements();) { JarEntry entry = e.nextElement(); byName.put(entry.getName(), entry); } for (JarEntry entry : byName.values()) { String name = entry.getName(); if (!entry.isDirectory() && (stripPattern == null || !stripPattern.matcher(name).matches())) { InputStream data = jar.getInputStream(entry); while ((num = data.read(buffer)) > 0) { if (md_sha1 != null) md_sha1.update(buffer, 0, num); if (md_sha256 != null) md_sha256.update(buffer, 0, num); } Attributes attr = null; if (input != null) attr = input.getAttributes(name); attr = attr != null ? new Attributes(attr) : new Attributes(); if (md_sha1 != null) { attr.putValue("SHA1-Digest", new String(Base64.encode(md_sha1.digest()), "ASCII")); } if (md_sha256 != null) { attr.putValue("SHA-256-Digest", new String(Base64.encode(md_sha256.digest()), "ASCII")); } output.getEntries().put(name, attr); } } return output; }
From source file:com.android.signapk.SignApk.java
License:Apache License
/** * Add a copy of the public key to the archive; this should * exactly match one of the files in//w w w .j av a 2s.c o m * /system/etc/security/otacerts.zip on the device. (The same * cert can be extracted from the CERT.RSA file but this is much * easier to get at.) */ private static void addOtacert(JarOutputStream outputJar, File publicKeyFile, long timestamp, Manifest manifest, int hash) throws IOException, GeneralSecurityException { MessageDigest md = MessageDigest.getInstance(hash == USE_SHA1 ? "SHA1" : "SHA256"); JarEntry je = new JarEntry(OTACERT_NAME); je.setTime(timestamp); outputJar.putNextEntry(je); FileInputStream input = new FileInputStream(publicKeyFile); byte[] b = new byte[4096]; int read; while ((read = input.read(b)) != -1) { outputJar.write(b, 0, read); md.update(b, 0, read); } input.close(); Attributes attr = new Attributes(); attr.putValue(hash == USE_SHA1 ? "SHA1-Digest" : "SHA-256-Digest", new String(Base64.encode(md.digest()), "ASCII")); manifest.getEntries().put(OTACERT_NAME, attr); }
From source file:com.android.signapk.SignApk.java
License:Apache License
/** Write a .SF file with a digest of the specified manifest. */ private static void writeSignatureFile(Manifest manifest, OutputStream out, int hash) throws IOException, GeneralSecurityException { Manifest sf = new Manifest(); Attributes main = sf.getMainAttributes(); main.putValue("Signature-Version", "1.0"); main.putValue("Created-By", "1.0 (Android SignApk)"); MessageDigest md = MessageDigest.getInstance(hash == USE_SHA256 ? "SHA256" : "SHA1"); PrintStream print = new PrintStream(new DigestOutputStream(new ByteArrayOutputStream(), md), true, "UTF-8"); // Digest of the entire manifest manifest.write(print);/*from w w w . j a va 2s . c o m*/ print.flush(); main.putValue(hash == USE_SHA256 ? "SHA-256-Digest-Manifest" : "SHA1-Digest-Manifest", new String(Base64.encode(md.digest()), "ASCII")); Map<String, Attributes> entries = manifest.getEntries(); for (Map.Entry<String, Attributes> entry : entries.entrySet()) { // Digest of the manifest stanza for this entry. print.print("Name: " + entry.getKey() + "\r\n"); for (Map.Entry<Object, Object> att : entry.getValue().entrySet()) { print.print(att.getKey() + ": " + att.getValue() + "\r\n"); } print.print("\r\n"); print.flush(); Attributes sfAttr = new Attributes(); sfAttr.putValue(hash == USE_SHA256 ? "SHA-256-Digest" : "SHA1-Digest-Manifest", new String(Base64.encode(md.digest()), "ASCII")); sf.getEntries().put(entry.getKey(), sfAttr); } CountOutputStream cout = new CountOutputStream(out); sf.write(cout); // A bug in the java.util.jar implementation of Android platforms // up to version 1.6 will cause a spurious IOException to be thrown // if the length of the signature file is a multiple of 1024 bytes. // As a workaround, add an extra CRLF in this case. if ((cout.size() % 1024) == 0) { cout.write('\r'); cout.write('\n'); } }
From source file:com.antisleuthsecurity.asc_api.cryptography.ciphers.symmetric.DESCipherTest.java
License:Apache License
@Test public void testEncryption() throws Exception { try {/*ww w . j av a 2 s. c o m*/ this.des.generateKey(); this.des.generateIV(); this.des.setMode(Cipher.ENCRYPT_MODE); Cipher cipher = this.des.getCipher(); assertNotNull(cipher); byte[] testString = "This is a test to encrypt".getBytes(); byte[] encrypted = cipher.doFinal(testString); System.out.println("Original: " + new String(Base64.encode(testString))); System.out.println("Encrypted: " + new String(Base64.encode(encrypted))); assertNotEquals(new String(testString), new String(encrypted)); cipher = this.des.getCipher(Cipher.DECRYPT_MODE); byte[] decrypted = cipher.doFinal(encrypted); System.out.println("Decrypted: " + new String(Base64.encode(decrypted))); assertEquals(new String(testString), new String(decrypted)); } catch (Exception e) { e.printStackTrace(); throw e; } }
From source file:com.antisleuthsecurity.server.rest.auth.Authentication.java
License:Apache License
/** * Consume a {@link RegistrationRequest} in order to register a new user * //from w w w . j a v a2 s. c o m * @param {@link RegistrationRequest} to consume * @return {@link RegistrationResponse} containing results pertaining to the * regsitration attempt */ @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("/register") public RegistrationResponse register(RegistrationRequest request) { RegistrationResponse response = new RegistrationResponse(); try { if (request != null) { NewAccountValidator av = new NewAccountValidator(request.getAccount()); Message[] messages = av.getReasons(); if (av.isValid()) { UserAccount account = request.getAccount(); String[] accountParams = new String[] { account.getUsername(), new String(Base64.encode(new String(account.getPassword()).getBytes()), "UTF-8"), new String(Base64.encode(account.getSalt()), "UTF-8") }; // TODO REgister Account String query = "INSERT INTO Users (username, password, salt) VALUES (?, ?, ?)"; ASServer.sql.execute(query, accountParams); accountParams = new String[] { account.getUsername(), new String(Base64.encode(new String(account.getPassword()).getBytes()), "UTF-8") }; query = "SELECT id FROM Users WHERE username=? AND password=?"; ResultSet rs = ASServer.sql.query(query, accountParams); while (rs.next()) { account.setUserId(rs.getInt("id")); response.setUserAccount(account); break; } rs.close(); if (account.getUserId() != null) { response.setSuccess(true); ASLog.debug("Account registered: " + account.getUsername()); } else { response.addMessage(MessagesEnum.REGISTRATION_FAILED); } } else { // Return error response! response.addMessages(messages); } } } catch (SQLException sqle) { ASLog.debug("Could not register user: " + request.getAccount().getUsername() + ", [" + sqle.getErrorCode() + "] " + sqle.getMessage()); response.addMessage(MessagesEnum.REGISTRATION_FAILED); } catch (Exception e) { response.addMessage(MessagesEnum.SYSTEM_ERROR); } return response; }
From source file:com.antisleuthsecurity.server.rest.auth.Authentication.java
License:Apache License
/** * Consume a {@link LoginRequest} in order to attempt to authenticate a * user./*from www. j av a 2s . co m*/ * * @param {@link LoginRequest} to consume * @return {@link LoginResponse} containing information pertaining to the * login attempt */ @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("/login") public LoginResponse login(LoginRequest request) { HttpSession session = this.servletRequest.getSession(true); LoginResponse response = new LoginResponse(); try { if (request != null) { LoginValidator lv = new LoginValidator(request.getAccount()); Message[] messages = lv.getReasons(); if (lv.isValid()) { UserAccount account = request.getAccount(); Integer userId = authUtil.findUserId(account.getUsername(), ASServer.sql); boolean accountLocked = authUtil.isAccountLocked(userId, ASServer.sql); if (!accountLocked) { String query = "SELECT id FROM Users WHERE username=? AND password=?"; ResultSet rs = ASServer.sql.query(query, new String[] { account.getUsername(), new String(Base64.encode(account.getPassword().getBytes()), "UTF-8") }); while (rs.next()) { account.setUserId(rs.getInt("id")); account.setServerId(ASServer.serverId); response.setAccount(account); response.setSuccess(true); } rs.close(); if (account.getUserId() != null) { response.setSuccess(true); authUtil.addLoginAttempt(account, true, ASServer.sql); session.setAttribute(PropsEnum.USER_ACCOUNT.getProperty(), account); } else { response.addMessage(MessagesEnum.LOGIN_FAILED); authUtil.addLoginAttempt(userId, false, ASServer.sql); } } else { response.addMessage(MessagesEnum.ACCOUNT_LOCKED); authUtil.addLoginAttempt(userId, false, ASServer.sql); } } else { response.addMessages(messages); response.addMessage(MessagesEnum.LOGIN_FAILED); } } } catch (SQLException sqle) { ASLog.debug("Could not login user: " + request.getAccount().getUsername() + ", [" + sqle.getErrorCode() + "] " + sqle.getMessage()); response.addMessage(MessagesEnum.LOGIN_FAILED); } catch (Exception e) { response.addMessage(MessagesEnum.SYSTEM_ERROR); } return response; }
From source file:com.antisleuthsecurity.server.rest.crypto.KeyManager.java
License:Apache License
/** * Method used to consume {@link AddKeyRequest} in order to register a * public key with the server./*from ww w.java 2 s. c om*/ * * @param {@link AddKeyRequest request}, this is the request object which * contains the key to add. * @return {@link AddKeyResponse} returns the status of whether or not the * key was accepted by the server */ @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("/addKey") public AddKeyResponse addKey(AddKeyRequest request) { AddKeyValidator akv = new AddKeyValidator(request); KeyManagerUtil kmu = new KeyManagerUtil(); AddKeyResponse response = new AddKeyResponse(); // Try to get the session, but don't create a new one if it doesn't // exist! HttpSession session = this.servletRequest.getSession(false); if (session != null) { // TODO Validate the addition of a new key UserAccount account = (UserAccount) session.getAttribute(PropsEnum.USER_ACCOUNT.getProperty()); if (account != null && akv.isValid()) { byte[] key = request.getKey(); try { boolean aliasExists = kmu.doesAliasExist(account.getUserId(), request.getAlias(), ASServer.sql); if (!aliasExists) { String query = "INSERT INTO PublicKeys (userId, key_alias, key_content, key_instance) VALUES (? , ?, ?, ?)"; String b64Key = new String(Base64.encode(request.getKey()), "UTF-8"); String[] params = { account.getUserId() + "", request.getAlias(), b64Key, request.getKeyInstance() }; ASServer.sql.execute(query, params); response.setSuccess(true); } else { response.addMessage(MessagesEnum.KEY_ALIAS_EXISTS); } } catch (Exception e) { response.addMessage(MessagesEnum.DATABASE_ERROR); ASLog.error(MessagesEnum.DATABASE_ERROR.getMessage(), e); } } else { response.addMessages(akv.getReasons()); } } return response; }
From source file:com.antisleuthsecurity.server.rest.messaging.MessageService.java
License:Apache License
/** * Send a message to a single user or a group of users. To identify mulriple * recipients, include multiple encrypted keys in the {@link * MessageParts#addKey(String username, byte[])} Where the username is the * recipient// w w w. ja va 2s .co m * * @param {@link SendMessageRequest request} Request containing the * information for the message to send * @return */ @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("/send") public SendMessageResponse sendMessage(SendMessageRequest request) { SendMessageResponse response = new SendMessageResponse(); HttpSession session = this.servletRequest.getSession(false); if (session != null) { if (session.getAttribute(PropsEnum.USER_ACCOUNT.getProperty()) == null) { response.addMessage(MessagesEnum.NOT_AUTHENTICATED); } else { SendMessageValidator smv = new SendMessageValidator(request); if (smv.isValid()) { MessageParts msgParts = request.getMsgParts(); TreeMap<String, byte[]> keys = msgParts.getKeys(); byte[] msg = Base64.encode(msgParts.getMessage()); TreeMap<String, Object> options = msgParts.getOptions(); Iterator<String> keySet = keys.keySet().iterator(); Iterator<String> optionSet = options.keySet().iterator(); String keyCipher = msgParts.getKeyCipherInstance(); String msgCipher = msgParts.getMessageCipherInstance(); UserAccount from = msgParts.getFrom(); while (keySet.hasNext()) { String keyName = keySet.next(); byte[] key = Base64.encode(keys.get(keyName)); try { String option = new ObjectMapper().writeValueAsString(options); Integer to = new AuthenticationUtil().findUserId(keyName, ASServer.sql); String query = "INSERT INTO Messages ([to], [from], message, [key], keyCipherInstance, msgCipherInstance, options) VALUES (?, ?, ?, ?, ?, ?, ?)"; String[] params = { to + "", msgParts.getFrom().getUserId() + "", new String(msg), new String(key), keyCipher, msgCipher, option }; boolean pass = ASServer.sql.execute(query, params); response.setSuccess(true); } catch (Exception e) { response.addMessage(MessagesEnum.DATABASE_ERROR); } } } else { response.addMessages(smv.getReasons()); } } } return response; }