List of usage examples for org.bouncycastle.util.encoders Base64 encode
public static byte[] encode(byte[] data)
From source file:my.adam.smo.RsaKeyGen.java
License:Open Source License
public static void main(String[] args) { KeyPairGenerator keyGen;//from w w w . j a v a2s. co m try { keyGen = KeyPairGenerator.getInstance("RSA"); } catch (NoSuchAlgorithmException e) { logger.error("fail to get generator"); return; } keyGen.initialize(2048); KeyPair kp = keyGen.generateKeyPair(); PKCS8EncodedKeySpec prv = new PKCS8EncodedKeySpec(kp.getPrivate().getEncoded()); X509EncodedKeySpec pub = new X509EncodedKeySpec(kp.getPublic().getEncoded()); logger.debug("conf entries as below:"); logger.debug("prv=" + new String(Base64.encode(prv.getEncoded())), "UTF-8"); logger.debug("pub=" + new String(Base64.encode(pub.getEncoded())), "UTF-8"); }
From source file:nDasJoWo.signapk.SignApk.java
License:Apache License
private static Manifest addDigestsToManifest(JarFile paramJarFile) throws IOException, GeneralSecurityException { Manifest localManifest1 = paramJarFile.getManifest(); Manifest localManifest2 = new Manifest(); Attributes localAttributes1 = localManifest2.getMainAttributes(); if (localManifest1 != null) { localAttributes1.putAll(localManifest1.getMainAttributes()); } else {/* w w w . ja v a 2s . c om*/ localAttributes1.putValue("Manifest-Version", "1.0"); localAttributes1.putValue("Created-By", "1.0 (nDasJoWo)"); } MessageDigest localMessageDigest = MessageDigest.getInstance("SHA1"); byte[] arrayOfByte = new byte[4096]; TreeMap localTreeMap = new TreeMap(); for (Object localObject = paramJarFile.entries(); ((Enumeration) localObject).hasMoreElements();) { JarEntry localJarEntry = (JarEntry) ((Enumeration) localObject).nextElement(); localTreeMap.put(localJarEntry.getName(), localJarEntry); } JarEntry localJarEntry; for (Object localObject = localTreeMap.values().iterator(); ((Iterator) localObject).hasNext();) { localJarEntry = (JarEntry) ((Iterator) localObject).next(); String str = localJarEntry.getName(); if ((!localJarEntry.isDirectory()) && (!str.equals("META-INF/MANIFEST.MF")) && (!str.equals("META-INF/CERT.SF")) && (!str.equals("META-INF/CERT.RSA")) && (!str.equals("META-INF/com/android/otacert")) && ((stripPattern == null) || (!stripPattern.matcher(str).matches()))) { InputStream localInputStream = paramJarFile.getInputStream(localJarEntry); int i; while ((i = localInputStream.read(arrayOfByte)) > 0) { localMessageDigest.update(arrayOfByte, 0, i); } Attributes localAttributes2 = null; if (localManifest1 != null) localAttributes2 = localManifest1.getAttributes(str); localAttributes2 = localAttributes2 != null ? new Attributes(localAttributes2) : new Attributes(); localAttributes2.putValue("SHA1-Digest", new String(Base64.encode(localMessageDigest.digest()), "ASCII")); localManifest2.getEntries().put(str, localAttributes2); } } return localManifest2; }
From source file:nDasJoWo.signapk.SignApk.java
License:Apache License
private static void addOtacert(JarOutputStream paramJarOutputStream, File paramFile, long paramLong, Manifest paramManifest) throws IOException, GeneralSecurityException { MessageDigest localMessageDigest = MessageDigest.getInstance("SHA1"); JarEntry localJarEntry = new JarEntry("META-INF/com/android/otacert"); localJarEntry.setTime(paramLong);// w ww. java 2 s. c om paramJarOutputStream.putNextEntry(localJarEntry); FileInputStream localFileInputStream = new FileInputStream(paramFile); byte[] arrayOfByte = new byte[4096]; int i; while ((i = localFileInputStream.read(arrayOfByte)) != -1) { paramJarOutputStream.write(arrayOfByte, 0, i); localMessageDigest.update(arrayOfByte, 0, i); } localFileInputStream.close(); Attributes localAttributes = new Attributes(); localAttributes.putValue("SHA1-Digest", new String(Base64.encode(localMessageDigest.digest()), "ASCII")); paramManifest.getEntries().put("META-INF/com/android/otacert", localAttributes); }
From source file:nDasJoWo.signapk.SignApk.java
License:Apache License
private static void writeSignatureFile(Manifest paramManifest, OutputStream paramOutputStream) throws IOException, GeneralSecurityException { Manifest localManifest = new Manifest(); Attributes localAttributes = localManifest.getMainAttributes(); localAttributes.putValue("Signature-Version", "1.0"); localAttributes.putValue("Created-By", "1.0 (nDasJoWo)"); MessageDigest localMessageDigest = MessageDigest.getInstance("SHA1"); PrintStream localPrintStream = new PrintStream( new DigestOutputStream(new ByteArrayOutputStream(), localMessageDigest), true, "UTF-8"); paramManifest.write(localPrintStream); localPrintStream.flush();/*from w ww. j av a 2 s . co m*/ localAttributes.putValue("SHA1-Digest-Manifest", new String(Base64.encode(localMessageDigest.digest()), "ASCII")); Map localMap = paramManifest.getEntries(); for (Object localObject1 = localMap.entrySet().iterator(); ((Iterator) localObject1).hasNext();) { Map.Entry localEntry1 = (Map.Entry) ((Iterator) localObject1).next(); localPrintStream.print("Name: " + (String) localEntry1.getKey() + "\r\n"); for (Object localObject2 = ((Attributes) localEntry1.getValue()).entrySet() .iterator(); ((Iterator) localObject2).hasNext();) { Map.Entry localEntry2 = (Map.Entry) ((Iterator) localObject2).next(); localPrintStream.print(localEntry2.getKey() + ": " + localEntry2.getValue() + "\r\n"); } localPrintStream.print("\r\n"); localPrintStream.flush(); Attributes localObject2 = new Attributes(); ((Attributes) localObject2).putValue("SHA1-Digest", new String(Base64.encode(localMessageDigest.digest()), "ASCII")); localManifest.getEntries().put((String) localEntry1.getKey(), localObject2); } Object localObject1 = new CountOutputStream(paramOutputStream); localManifest.write((OutputStream) localObject1); if (((CountOutputStream) localObject1).size() % 1024 == 0) { ((CountOutputStream) localObject1).write(13); ((CountOutputStream) localObject1).write(10); } }
From source file:net.geant.edugain.AESTool.java
License:Apache License
/** * Encrypt a message using the specified key. * /*ww w . j av a 2 s. com*/ * @param nameKey * The name of the key you want to use * @param data * The message you want to encrypt * @return The ciphered message in base 64, or <tt>null</tt> if it has * happened any error encrypting */ public String encode(String nameKey, String data) { try { Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); // setup key byte[] keyBytes = (byte[]) keys.get(nameKey); SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES"); cipher.init(Cipher.ENCRYPT_MODE, keySpec); byte[] rawData = data.getBytes(); byte[] results = cipher.doFinal(rawData); // return new String(base64Encoder.encode(results)); String output = new String(Base64.encode(results)); return output; } catch (Exception e) { e.printStackTrace(); return null; } }
From source file:net.java.otr4j.io.SerializationUtils.java
License:Apache License
public static String toString(AbstractMessage m) throws IOException { StringWriter writer = new StringWriter(); if (m.messageType != AbstractMessage.MESSAGE_PLAINTEXT) writer.write(SerializationConstants.HEAD); switch (m.messageType) { case AbstractMessage.MESSAGE_ERROR: ErrorMessage error = (ErrorMessage) m; writer.write(SerializationConstants.HEAD_ERROR); writer.write(SerializationConstants.ERROR_PREFIX); writer.write(error.error);//from w w w .java 2 s .c om break; case AbstractMessage.MESSAGE_PLAINTEXT: PlainTextMessage plaintxt = (PlainTextMessage) m; writer.write(plaintxt.cleanText); if (plaintxt.versions != null && plaintxt.versions.size() > 0) { writer.write(" \t \t\t\t\t \t \t \t "); for (int version : plaintxt.versions) { if (version == OTRv.ONE) writer.write(" \t \t \t "); if (version == OTRv.TWO) writer.write(" \t\t \t "); if (version == OTRv.THREE) writer.write(" \t\t \t\t"); } } break; case AbstractMessage.MESSAGE_QUERY: QueryMessage query = (QueryMessage) m; if (query.versions.size() == 1 && query.versions.get(0) == 1) { writer.write(SerializationConstants.HEAD_QUERY_Q); } else { writer.write(SerializationConstants.HEAD_QUERY_V); for (int version : query.versions) writer.write(String.valueOf(version)); writer.write(SerializationConstants.HEAD_QUERY_Q); } break; case AbstractEncodedMessage.MESSAGE_DHKEY: case AbstractEncodedMessage.MESSAGE_REVEALSIG: case AbstractEncodedMessage.MESSAGE_SIGNATURE: case AbstractEncodedMessage.MESSAGE_DH_COMMIT: case AbstractEncodedMessage.MESSAGE_DATA: ByteArrayOutputStream o = new ByteArrayOutputStream(); OtrOutputStream s = new OtrOutputStream(o); switch (m.messageType) { case AbstractEncodedMessage.MESSAGE_DHKEY: DHKeyMessage dhkey = (DHKeyMessage) m; s.writeShort(dhkey.protocolVersion); s.writeByte(dhkey.messageType); if (dhkey.protocolVersion == OTRv.THREE) { s.writeInt(dhkey.senderInstanceTag); s.writeInt(dhkey.receiverInstanceTag); } s.writeDHPublicKey(dhkey.dhPublicKey); break; case AbstractEncodedMessage.MESSAGE_REVEALSIG: RevealSignatureMessage revealsig = (RevealSignatureMessage) m; s.writeShort(revealsig.protocolVersion); s.writeByte(revealsig.messageType); if (revealsig.protocolVersion == OTRv.THREE) { s.writeInt(revealsig.senderInstanceTag); s.writeInt(revealsig.receiverInstanceTag); } s.writeData(revealsig.revealedKey); s.writeData(revealsig.xEncrypted); s.writeMac(revealsig.xEncryptedMAC); break; case AbstractEncodedMessage.MESSAGE_SIGNATURE: SignatureMessage sig = (SignatureMessage) m; s.writeShort(sig.protocolVersion); s.writeByte(sig.messageType); if (sig.protocolVersion == OTRv.THREE) { s.writeInt(sig.senderInstanceTag); s.writeInt(sig.receiverInstanceTag); } s.writeData(sig.xEncrypted); s.writeMac(sig.xEncryptedMAC); break; case AbstractEncodedMessage.MESSAGE_DH_COMMIT: DHCommitMessage dhcommit = (DHCommitMessage) m; s.writeShort(dhcommit.protocolVersion); s.writeByte(dhcommit.messageType); if (dhcommit.protocolVersion == OTRv.THREE) { s.writeInt(dhcommit.senderInstanceTag); s.writeInt(dhcommit.receiverInstanceTag); } s.writeData(dhcommit.dhPublicKeyEncrypted); s.writeData(dhcommit.dhPublicKeyHash); break; case AbstractEncodedMessage.MESSAGE_DATA: DataMessage data = (DataMessage) m; s.writeShort(data.protocolVersion); s.writeByte(data.messageType); if (data.protocolVersion == OTRv.THREE) { s.writeInt(data.senderInstanceTag); s.writeInt(data.receiverInstanceTag); } s.writeByte(data.flags); s.writeInt(data.senderKeyID); s.writeInt(data.recipientKeyID); s.writeDHPublicKey(data.nextDH); s.writeCtr(data.ctr); s.writeData(data.encryptedMessage); s.writeMac(data.mac); s.writeData(data.oldMACKeys); break; default: // NOTE We should probably move at least part of this method into individual // toString() methods of the *Message implementations. throw new UnsupportedOperationException("Unsupported message type: " + m.messageType); } writer.write(SerializationConstants.HEAD_ENCODED); writer.write(new String(Base64.encode(o.toByteArray()))); writer.write("."); break; default: throw new IOException("Illegal message type."); } return writer.toString(); }
From source file:net.java.otr4j.session.OtrFragmenterTest.java
License:Apache License
@Test public void testFragmentPatternsV3() throws IOException { final Pattern OTRv3_FRAGMENT_PATTERN = Pattern .compile("^\\?OTR\\|[0-9abcdef]{8}\\|[0-9abcdef]{8},\\d{5},\\d{5},[a-zA-Z0-9\\+/=\\?:]+,$"); final String payload = new String(Base64.encode(RandomStringUtils.random(1700).getBytes("UTF-8"))); final Session session = createSessionMock(POLICY_V3, 0x0a73a599, 0x00000007); final FragmenterInstructions instructions = new FragmenterInstructions(-1, 150); final OtrEngineHost host = host(instructions); OtrFragmenter fragmenter = new OtrFragmenter(session, host); String[] msg = fragmenter.fragment(payload); int count = 1; for (String part : msg) { Assert.assertTrue(OTRv3_FRAGMENT_PATTERN.matcher(part).matches()); // Test monotonic increase of part numbers ... int partNumber = Integer.parseInt(part.substring(23, 28), 10); Assert.assertEquals(count, partNumber); count++;// w w w .j a v a 2 s . co m } Mockito.verify(host, Mockito.times(1)).getFragmenterInstructions(Mockito.any(SessionID.class)); }
From source file:net.java.otr4j.session.OtrFragmenterTest.java
License:Apache License
@Test public void testFragmentPatternsV2() throws IOException { final Pattern OTRv2_FRAGMENT_PATTERN = Pattern.compile("^\\?OTR,\\d{1,5},\\d{1,5},[a-zA-Z0-9\\+/=\\?:]+,$"); final String payload = new String(Base64.encode(RandomStringUtils.random(700).getBytes("UTF-8"))); final Session session = createSessionMock(POLICY_V2, 0, 0); final FragmenterInstructions instructions = new FragmenterInstructions(-1, 150); final OtrEngineHost host = host(instructions); OtrFragmenter fragmenter = new OtrFragmenter(session, host); String[] msg = fragmenter.fragment(payload); int count = 1; for (String part : msg) { Assert.assertTrue(OTRv2_FRAGMENT_PATTERN.matcher(part).matches()); // Test monotonic increase of part numbers ... String temp = part.substring(5, 11); int partNumber = Integer.parseInt(temp.substring(0, temp.indexOf(',')), 10); Assert.assertEquals(count, partNumber); count++;//from w ww. j a v a2 s . c om } Mockito.verify(host, Mockito.times(1)).getFragmenterInstructions(Mockito.any(SessionID.class)); }
From source file:net.java.sip.communicator.plugin.otr.OtrConfigurator.java
License:Apache License
/** * Sets the property with the specified name to the specified value ( * {@link ConfigurationService#setProperty(String, Object)} proxy). The * value is Base64 encoded.//from w w w . ja v a2 s . c o m * * @param id the name of the property to change. * @param value the new value of the specified property. */ public void setProperty(String id, byte[] value) { String valueToStore = new String(Base64.encode(value)); OtrActivator.configService.setProperty(getID(id), valueToStore); }
From source file:net.jsign.timestamp.AuthenticodeTimestamper.java
License:Apache License
protected CMSSignedData timestamp(DigestAlgorithm algo, byte[] encryptedDigest) throws IOException, TimestampingException { AuthenticodeTimeStampRequest timestampRequest = new AuthenticodeTimeStampRequest(encryptedDigest); byte[] request = Base64.encode(timestampRequest.getEncoded("DER")); HttpURLConnection conn = (HttpURLConnection) tsaurl.openConnection(); conn.setConnectTimeout(10000);//from w ww . j ava 2 s.com conn.setReadTimeout(10000); conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-type", "application/octet-stream"); conn.setRequestProperty("Content-length", String.valueOf(request.length)); conn.setRequestProperty("Accept", "application/octet-stream"); conn.setRequestProperty("User-Agent", "Transport"); conn.getOutputStream().write(request); conn.getOutputStream().flush(); if (conn.getResponseCode() >= 400) { throw new IOException("Unable to complete the timestamping due to HTTP error: " + conn.getResponseCode() + " - " + conn.getResponseMessage()); } try { byte[] response = Base64.decode(toBytes(conn.getInputStream())); return new CMSSignedData(response); } catch (Exception e) { throw new TimestampingException("Unable to complete the timestamping", e); } }