Rename pimstuff -> jpim and move to Maven
[jpim.git] / src / main / java / de / j32 / avmfritz / LoginXML.java
diff --git a/src/main/java/de/j32/avmfritz/LoginXML.java b/src/main/java/de/j32/avmfritz/LoginXML.java
new file mode 100644 (file)
index 0000000..c5ec76b
--- /dev/null
@@ -0,0 +1,75 @@
+package de.j32.avmfritz;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.UnsupportedEncodingException;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+
+import javax.xml.bind.annotation.adapters.HexBinaryAdapter;
+
+import org.w3c.dom.Document;
+import org.xml.sax.SAXException;
+
+import de.j32.util.Util;
+import de.j32.util.XmlUtil;
+
+public class LoginXML
+{
+    Document xml_;
+
+    public LoginXML(InputStream is) throws SAXException, IOException
+    {
+        xml_ = XmlUtil.parse(is);
+    }
+
+    public boolean iswriteaccess() throws SAXException
+    {
+        try {
+            return xml_.getElementsByTagName("iswriteaccess").item(0)
+                    .getTextContent().equals("1");
+        }
+        catch (NullPointerException e) {
+            throw new SAXException();
+        }
+    }
+
+    public String sid() throws SAXException
+    {
+        try {
+            return Util.nonnull(xml_.getElementsByTagName("SID").item(0)
+                    .getTextContent());
+        }
+        catch (NullPointerException e) {
+            throw new SAXException();
+        }
+    }
+
+    public String challenge() throws SAXException
+    {
+        try {
+            return Util.nonnull(xml_.getElementsByTagName("Challenge").item(0)
+                    .getTextContent());
+        }
+        catch (NullPointerException e) {
+            throw new SAXException();
+        }
+    }
+
+    public String response(String password) throws SAXException
+    {
+        try {
+            String c = challenge();
+            MessageDigest md = MessageDigest.getInstance("MD5");
+            md.update((c + "-" + password).getBytes("UTF-16LE"));
+            return c + "-"
+                    + new HexBinaryAdapter().marshal(md.digest()).toLowerCase();
+        }
+        catch (NoSuchAlgorithmException e) {
+            throw new AssertionError("missing MD5 implementation");
+        }
+        catch (UnsupportedEncodingException e) {
+            throw new AssertionError("missing UTF-16LE encoding");
+        }
+    }
+}