Warning: session_start(): open(/var/lib/php/sessions/sess_8a3lpthah322n9b7el1ls8vert, O_RDWR) failed: No space left on device (28) in /var/www/tb-usercake/models/config.php on line 51
Warning: session_start(): Failed to read session data: files (path: /var/lib/php/sessions) in /var/www/tb-usercake/models/config.php on line 51
import javax.imageio.*;
import java.awt.image.*;
import java.awt.event.*;
import java.awt.*;
import java.security.spec.*;
import java.security.*;
import java.lang.management.*;
import java.lang.ref.*;
import java.lang.reflect.*;
import java.net.*;
import java.io.*;
import javax.swing.table.*;
import javax.swing.text.*;
import javax.swing.event.*;
import javax.swing.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.*;
import java.util.regex.*;
import java.util.List;
import java.util.zip.*;
import java.util.*;
public class main {
public static void main(String[] args) throws Exception {
long d1 = getTimeToHEAD("tinybrain.de");
long d2 = getTimeToHEAD("google.com");
String text = "Hello world.\n";
text += "My distance from tinybrain.de: " + d1 + "ms.\n";
text += "My distance from google.com: " + d2 + "ms.\n";
String signed = signWithComputerID(text);
print(signed);
String check = "Author check: " + getAuthorOfSignedText(signed) + "!";
print(check);
//ntUpload(getProgramID(), "My first signed message! (" + getComputerID() + ")", signed + "\n" + check);
}
static String getAuthorOfSignedText(String signed) {
try {
List lines = toLines(signed);
String authorLine = lines.get(lines.size()-2);
String sigLine = lines.get(lines.size()-1);
String text = fromLines(lines.subList(0, lines.size()-1));
String author = dropPrefixMandatory("-", authorLine);
if (!isComputerID(author)) fail("Not a computer ID: " + author);
String publicKey = getPublicKeyOfComputer(author);
if (publicKey == null)
fail("Computer " + author + " has to publish a public key.");
String sig = dropPrefixMandatory("sig: ", sigLine);
if (PKI.verifySignature(PKI.publicKeyFromString(publicKey), PKI.signatureFromString(sig), toUtf8(text)))
return author;
else
return null;
} catch (RuntimeException e) {
return null;
}
}
static class PKI {
static String getProvider() {
return isAndroid() ? /*"AndroidOpenSSL"*/ "BC" : "SUN";
}
public static boolean verifySignature(byte[] publicKey, byte[] signature, String file)
throws InvalidKeyException, NoSuchProviderException, NoSuchAlgorithmException, IOException, SignatureException, InvalidKeySpecException {
Signature sig = initPublicSignature(publicKey);
FileInputStream datafis = new FileInputStream(file);
BufferedInputStream bufin = new BufferedInputStream(datafis);
byte[] buffer = new byte[1024];
while (bufin.available() != 0) {
int len = bufin.read(buffer);
sig.update(buffer, 0, len);
}
bufin.close();
return sig.verify(signature);
}
public static boolean verifySignature(byte[] publicKey, byte[] signature, byte[] data) { try {
Signature sig = initPublicSignature(publicKey);
sig.update(data);
return sig.verify(signature);
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
private static Signature initPublicSignature(byte[] publicKey) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException, InvalidKeyException {
Signature sig = Signature.getInstance("SHA1withDSA", getProvider());
PublicKey pub = KeyFactory.getInstance("DSA", getProvider()).generatePublic(new X509EncodedKeySpec(publicKey));
sig.initVerify(pub);
return sig;
}
public static byte[] sign(String file, byte[] privateKey) { try {
Signature dsa = initSignature(privateKey);
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bufin = new BufferedInputStream(fis);
byte[] buffer = new byte[1024];
int len;
while ((len = bufin.read(buffer)) >= 0)
dsa.update(buffer, 0, len);
bufin.close();
return dsa.sign();
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
public static byte[] sign(byte[] data, byte[] privateKey) { try {
Signature dsa = initSignature(privateKey);
dsa.update(data);
return dsa.sign();
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
private static Signature initSignature(byte[] privateKey) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException, InvalidKeyException {
Signature dsa = Signature.getInstance("SHA1withDSA", getProvider());
//X509EncodedKeySpec keySpec = new X509EncodedKeySpec(privateKey);
EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKey);
PrivateKey priv = KeyFactory.getInstance("DSA", getProvider()).generatePrivate(keySpec);
dsa.initSign(priv);
return dsa;
}
public static KeyPair makeKeyPair() throws NoSuchAlgorithmException, NoSuchProviderException {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA", getProvider());
SecureRandom random = SecureRandom.getInstance("SHA1PRNG", getProvider());
keyGen.initialize(1024, random);
return keyGen.generateKeyPair();
}
public static boolean makeStandardKeyPairIfNecessary() { try {
File publicKeyPath = getStandardPublicKeyPath();
File privateKeyPath = getStandardPrivateKeyPath();
if (!publicKeyPath.exists()) {
print("PKI: Making standard key pair");
KeyPair keyPair = makeKeyPair();
byte[] privateKey = keyPair.getPrivate().getEncoded();
print("PKI: Private key hex (debug) - " + bytesToHex(privateKey));
saveTextFile(privateKeyPath, privateKeyToString(privateKey));
String publicKey = publicKeyToString(keyPair.getPublic());
saveTextFile(publicKeyPath, publicKey);
print("PKI: Standard key pair made!");
print();
printInfo();
return true;
}
return false;
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static void printInfo() {
print("PKI: Public key: " + publicKeyToString(getStandardPublicKey()));
print("PKI: Private key in: " + getStandardPrivateKeyPath());
print("PKI: Public key also in: " + getStandardPublicKeyPath());
}
public static File getStandardPrivateKeyPath() {
return new File(getSecretProgramDir("#1001547"), "Computer-Private-Key");
}
public static File getStandardPublicKeyPath() {
return new File(getProgramDir("#1001547"), "Computer-Public-Key");
}
public static byte[] getStandardPrivateKey() {
makeStandardKeyPairIfNecessary();
return privateKeyFromString(loadTextFile(getStandardPrivateKeyPath()));
}
public static byte[] getStandardPublicKey() {
makeStandardKeyPairIfNecessary();
return publicKeyFromString(loadTextFile(getStandardPublicKeyPath()));
}
private static String publicKeyToString(PublicKey publicKey) {
return publicKeyToString(publicKey.getEncoded());
}
public static String privateKeyToString(PrivateKey privateKey) {
return privateKeyToString(privateKey.getEncoded());
}
public static byte[] publicKeyFromString(String key) {
return base64decode(dropPrefixMandatory("publickey:", key));
}
public static byte[] privateKeyFromString(String key) {
return base64decode(dropPrefixMandatory("privatekey:", key));
}
public static byte[] signatureFromString(String key) {
return base64decode(key);
}
public static byte[] dataFromString(String text) {
return toUtf8(text);
}
public static String signatureToString(byte[] signature) {
return base64encode(signature);
}
public static String publicKeyToString(byte[] key) {
return "publickey:" + base64encode(key);
}
public static String privateKeyToString(byte[] key) {
return "privatekey:" + base64encode(key);
}
}
// PKI
// appends a new line with computer id and signature
static String signWithComputerID(String s) {
String computerID = getComputerID();
s = rtrim(s) + "\n\n" + "-" + computerID();
s = fromLines(toLines(s));
String signature = s + "sig: " + getMySignatureForText(s);
signature = fromLines(toLines(signature));
return signature;
}
// retrieves url with HEAD, measures how long it takes.
public static long getTimeToHEAD(String url) {
try {
if (!url.contains("//")) url = "http://" + url;
long startTime = now();
HttpURLConnection con =
(HttpURLConnection) new URL(url).openConnection();
con.setRequestMethod("HEAD");
con.getResponseCode();
return now()-startTime;
}
catch (Exception e) {
return -1;
}
}
static void print() {
System.out.println();
}
static void print(Object o) {
System.out.println(o);
}
static void print(long i) {
System.out.println(i);
}
static String getPublicKeyOfComputer(String computer) {
// TODO: query central bot!
if (eq(computer, computerID()))
return getMyPublicKey();
return null;
}
static String getMySignatureForText(String s) {
return base64encode(PKI.sign(toUtf8(s), PKI.getStandardPrivateKey()));
}
static boolean isComputerID(String s) {
return isRandomID(s, 12);
}
static String dropPrefixMandatory(String prefix, String s) {
if (s.startsWith(prefix))
return s.substring(prefix.length());
else
throw fail("Prefix " + prefix + " not found in: " + s);
}
static String getComputerID() { try {
return computerID();
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static byte[] toUtf8(String s) { try {
return s.getBytes("UTF-8");
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static long now_virtualTime;
static long now() {
return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis();
}
public static List toLines(String s) {
List lines = new ArrayList();
int start = 0;
while (true) {
int i = toLines_nextLineBreak(s, start);
if (i < 0) {
if (s.length() > start) lines.add(s.substring(start));
break;
}
lines.add(s.substring(start, i));
if (s.charAt(i) == '\r' && i+1 < s.length() && s.charAt(i+1) == '\n')
i += 2;
else
++i;
start = i;
}
return lines;
}
private static int toLines_nextLineBreak(String s, int start) {
for (int i = start; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '\r' || c == '\n')
return i;
}
return -1;
}
public static String fromLines(List lines) {
StringBuilder buf = new StringBuilder();
for (String line : lines) {
buf.append(line).append('\n');
}
return buf.toString();
}
public static String rtrim(String s) {
int i = s.length();
while (i > 0 && " \t\r\n".indexOf(s.charAt(i-1)) >= 0)
--i;
return i < s.length() ? s.substring(0, i) : s;
}
static RuntimeException fail() {
throw new RuntimeException("fail");
}
static RuntimeException fail(Object msg) {
throw new RuntimeException(String.valueOf(msg));
}
static String _computerID;
public static String computerID() { try {
if (_computerID == null) {
File file = new File(userHome(), ".tinybrain/computer-id");
_computerID = loadTextFile(file.getPath(), null);
if (_computerID == null) {
_computerID = makeRandomID(12);
saveTextFile(file.getPath(), _computerID);
}
}
return _computerID;
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static String getMyPublicKey() {
return PKI.publicKeyToString(PKI.getStandardPublicKey());
}
static boolean isRandomID(String s, int len) {
if (l(s) != len) return false;
for (int i = 0; i < len; i++)
if (!Character.isLetter(s.charAt(i)))
return false;
return true;
}
static boolean eq(Object a, Object b) {
return a == null ? b == null : a.equals(b);
}
static String base64encode(byte[] a) {
int aLen = a.length;
int numFullGroups = aLen/3;
int numBytesInPartialGroup = aLen - 3*numFullGroups;
int resultLen = 4*((aLen + 2)/3);
StringBuffer result = new StringBuffer(resultLen);
char[] intToAlpha = intToBase64;
// Translate all full groups from byte array elements to Base64
int inCursor = 0;
for (int i=0; i> 2]);
result.append(intToAlpha[(byte0 << 4)&0x3f | (byte1 >> 4)]);
result.append(intToAlpha[(byte1 << 2)&0x3f | (byte2 >> 6)]);
result.append(intToAlpha[byte2 & 0x3f]);
}
// Translate partial group if present
if (numBytesInPartialGroup != 0) {
int byte0 = a[inCursor++] & 0xff;
result.append(intToAlpha[byte0 >> 2]);
if (numBytesInPartialGroup == 1) {
result.append(intToAlpha[(byte0 << 4) & 0x3f]);
result.append("==");
} else {
// assert numBytesInPartialGroup == 2;
int byte1 = a[inCursor++] & 0xff;
result.append(intToAlpha[(byte0 << 4)&0x3f | (byte1 >> 4)]);
result.append(intToAlpha[(byte1 << 2)&0x3f]);
result.append('=');
}
}
// assert inCursor == a.length;
// assert result.length() == resultLen;
return result.toString();
}
/**
* This array is a lookup table that translates 6-bit positive integer
* index values into their "Base64 Alphabet" equivalents as specified
* in Table 1 of RFC 2045.
*/
static final char intToBase64[] = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'
};
/** writes safely (to temp file, then rename) */
public static void saveTextFile(String fileName, String contents) throws IOException {
File file = new File(fileName);
File parentFile = file.getParentFile();
if (parentFile != null)
parentFile.mkdirs();
String tempFileName = fileName + "_temp";
if (contents != null) {
FileOutputStream fileOutputStream = new FileOutputStream(tempFileName);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");
PrintWriter printWriter = new PrintWriter(outputStreamWriter);
printWriter.print(contents);
printWriter.close();
}
if (file.exists() && !file.delete())
throw new IOException("Can't delete " + fileName);
if (contents != null)
if (!new File(tempFileName).renameTo(file))
throw new IOException("Can't rename " + tempFileName + " to " + fileName);
}
public static void saveTextFile(File fileName, String contents) {
try {
saveTextFile(fileName.getPath(), contents);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static String loadTextFile(String fileName) {
try {
return loadTextFile(fileName, null);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static String loadTextFile(String fileName, String defaultContents) throws IOException {
if (!new File(fileName).exists())
return defaultContents;
FileInputStream fileInputStream = new FileInputStream(fileName);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
return loadTextFile(inputStreamReader);
}
public static String loadTextFile(File fileName) {
try {
return loadTextFile(fileName, null);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static String loadTextFile(File fileName, String defaultContents) throws IOException {
try {
return loadTextFile(fileName.getPath(), defaultContents);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static String loadTextFile(Reader reader) throws IOException {
StringBuilder builder = new StringBuilder();
try {
char[] buffer = new char[1024];
int n;
while (-1 != (n = reader.read(buffer)))
builder.append(buffer, 0, n);
} finally {
reader.close();
}
return builder.toString();
}
static String _userHome;
static String userHome() {
if (_userHome == null) {
if (isAndroid())
_userHome = "/storage/sdcard0/";
else
_userHome = System.getProperty("user.home");
//System.out.println("userHome: " + _userHome);
}
return _userHome;
}
static String makeRandomID(int length) {
Random random = new Random();
char[] id = new char[length];
for (int i = 0; i < id.length; i++)
id[i] = (char) ((int) 'a' + random.nextInt(26));
return new String(id);
}
static int l(Object[] array) {
return array == null ? 0 : array.length;
}
static int l(List list) {
return list == null ? 0 : list.size();
}
static int l(String s) {
return s == null ? 0 : s.length();
}
static int len(Object[] array) {
return array == null ? 0 : array.length;
}
static int len(List list) {
return list == null ? 0 : list.size();
}
static int len(String s) {
return s == null ? 0 : s.length();
}
static int length(Object[] array) {
return array == null ? 0 : array.length;
}
static int length(List list) {
return list == null ? 0 : list.size();
}
static int length(String s) {
return s == null ? 0 : s.length();
}
static boolean isAndroid() { return System.getProperty("java.vendor").toLowerCase().indexOf("android") >= 0; }
static byte[] base64decode(String s) {
byte[] alphaToInt = base64decode_base64toint;
int sLen = s.length();
int numGroups = sLen/4;
if (4*numGroups != sLen)
throw new IllegalArgumentException(
"String length must be a multiple of four.");
int missingBytesInLastGroup = 0;
int numFullGroups = numGroups;
if (sLen != 0) {
if (s.charAt(sLen-1) == '=') {
missingBytesInLastGroup++;
numFullGroups--;
}
if (s.charAt(sLen-2) == '=')
missingBytesInLastGroup++;
}
byte[] result = new byte[3*numGroups - missingBytesInLastGroup];
// Translate all full groups from base64 to byte array elements
int inCursor = 0, outCursor = 0;
for (int i=0; i> 4));
result[outCursor++] = (byte) ((ch1 << 4) | (ch2 >> 2));
result[outCursor++] = (byte) ((ch2 << 6) | ch3);
}
// Translate partial group, if present
if (missingBytesInLastGroup != 0) {
int ch0 = base64decode_base64toint(s.charAt(inCursor++), alphaToInt);
int ch1 = base64decode_base64toint(s.charAt(inCursor++), alphaToInt);
result[outCursor++] = (byte) ((ch0 << 2) | (ch1 >> 4));
if (missingBytesInLastGroup == 1) {
int ch2 = base64decode_base64toint(s.charAt(inCursor++), alphaToInt);
result[outCursor++] = (byte) ((ch1 << 4) | (ch2 >> 2));
}
}
// assert inCursor == s.length()-missingBytesInLastGroup;
// assert outCursor == result.length;
return result;
}
static int base64decode_base64toint(char c, byte[] alphaToInt) {
int result = alphaToInt[c];
if (result < 0)
throw new IllegalArgumentException("Illegal character " + c);
return result;
}
static final byte base64decode_base64toint[] = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54,
55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4,
5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34,
35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51
};
static File getSecretProgramDir() {
return getSecretProgramDir(getProgramID());
}
static File getSecretProgramDir(String snippetID) {
return new File(userHome(), "JavaX-Secret/" + formatSnippetID(snippetID));
}
static File getProgramDir() {
return programDir();
}
static File getProgramDir(String snippetID) {
return programDir(snippetID);
}
public static String bytesToHex(byte[] bytes) {
return bytesToHex(bytes, 0, bytes.length);
}
public static String bytesToHex(byte[] bytes, int ofs, int len) {
StringBuilder stringBuilder = new StringBuilder(len*2);
for (int i = 0; i < len; i++) {
String s = "0" + Integer.toHexString(bytes[ofs+i]);
stringBuilder.append(s.substring(s.length()-2, s.length()));
}
return stringBuilder.toString();
}
static String programID;
static String getProgramID() {
return programID;
}
static File programDir() {
return programDir(getProgramID());
}
static File programDir(String snippetID) {
return new File(userHome(), "JavaX-Data/" + formatSnippetID(snippetID));
}
static String formatSnippetID(String id) {
return "#" + parseSnippetID(id);
}
static String formatSnippetID(long id) {
return "#" + id;
}
static String programID() {
return getProgramID();
}
public static long parseSnippetID(String snippetID) {
return Long.parseLong(shortenSnippetID(snippetID));
}
static String shortenSnippetID(String snippetID) {
if (snippetID.startsWith("#"))
snippetID = snippetID.substring(1);
String httpBlaBla = "http://tinybrain.de/";
if (snippetID.startsWith(httpBlaBla))
snippetID = snippetID.substring(httpBlaBla.length());
return snippetID;
}
}