abdera-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From jmsn...@apache.org
Subject svn commit: r1175994 - in /abdera/abdera2: common/src/main/java/org/apache/abdera2/common/security/ security/src/main/java/org/apache/abdera2/security/util/
Date Mon, 26 Sep 2011 18:54:22 GMT
Author: jmsnell
Date: Mon Sep 26 18:54:21 2011
New Revision: 1175994

URL: http://svn.apache.org/viewvc?rev=1175994&view=rev
Log: (empty)

Added:
    abdera/abdera2/common/src/main/java/org/apache/abdera2/common/security/DHBase.java   (with
props)
Modified:
    abdera/abdera2/common/src/main/java/org/apache/abdera2/common/security/ApiKey.java
    abdera/abdera2/common/src/main/java/org/apache/abdera2/common/security/KeyBase.java
    abdera/abdera2/common/src/main/java/org/apache/abdera2/common/security/Otp.java
    abdera/abdera2/security/src/main/java/org/apache/abdera2/security/util/DHContext.java

Modified: abdera/abdera2/common/src/main/java/org/apache/abdera2/common/security/ApiKey.java
URL: http://svn.apache.org/viewvc/abdera/abdera2/common/src/main/java/org/apache/abdera2/common/security/ApiKey.java?rev=1175994&r1=1175993&r2=1175994&view=diff
==============================================================================
--- abdera/abdera2/common/src/main/java/org/apache/abdera2/common/security/ApiKey.java (original)
+++ abdera/abdera2/common/src/main/java/org/apache/abdera2/common/security/ApiKey.java Mon
Sep 26 18:54:21 2011
@@ -42,13 +42,24 @@ public class ApiKey extends KeyBase {
     super(key);
   }
 
+  /**
+   * Generates a random string that can be used as an API Key.
+   * The string is generated by creating a random array of 
+   * bytes, generating an hmac, then base64 encoding those. 
+   * All non alphanumeric characters in the base64 encoded
+   * result are then replaced with periods ('.') to simplify
+   * the result a bit more. The resulting API Key can be 
+   * expected to be reasonably random and suitable for use
+   * within a request URI (e.g. key={apikey}).
+   */
   public String generateNext() {
     int len = Math.min(20, size);
     byte[] buf = hmac(randomBytes(len));
     buf = Base64.encodeBase64(buf, false, true);
     StringBuilder sb = new StringBuilder();
     for (byte b : buf)
-      sb.append(Character.isLetterOrDigit(b)?(char)b:'.');
+      sb.append(
+        Character.isLetterOrDigit(b)?(char)b:'.');
     return sb.toString();
   }
  

Added: abdera/abdera2/common/src/main/java/org/apache/abdera2/common/security/DHBase.java
URL: http://svn.apache.org/viewvc/abdera/abdera2/common/src/main/java/org/apache/abdera2/common/security/DHBase.java?rev=1175994&view=auto
==============================================================================
--- abdera/abdera2/common/src/main/java/org/apache/abdera2/common/security/DHBase.java (added)
+++ abdera/abdera2/common/src/main/java/org/apache/abdera2/common/security/DHBase.java Mon
Sep 26 18:54:21 2011
@@ -0,0 +1,182 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  The ASF licenses this file to You
+ * under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.  For additional information regarding
+ * copyright in this work, please see the NOTICE file in the top level
+ * directory of this distribution.
+ */
+package org.apache.abdera2.common.security;
+
+import java.io.Serializable;
+import java.math.BigInteger;
+import java.security.AlgorithmParameterGenerator;
+import java.security.AlgorithmParameters;
+import java.security.InvalidAlgorithmParameterException;
+import java.security.InvalidKeyException;
+import java.security.Key;
+import java.security.KeyFactory;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.NoSuchAlgorithmException;
+import java.security.spec.InvalidKeySpecException;
+import java.security.spec.InvalidParameterSpecException;
+import java.security.spec.X509EncodedKeySpec;
+
+import javax.crypto.KeyAgreement;
+import javax.crypto.spec.DHParameterSpec;
+
+import org.apache.commons.codec.binary.Base64;
+
+/**
+ * Implements the Diffie-Hellman Key Exchange details for both parties Party A: DHContext
context_a = new DHContext();
+ * String req = context_a.getRequestString(); Party B: DHContext context_b = new DHContext(req);
EncryptionOptions
+ * options = context_b.getEncryptionOptions(enc); // encrypt String ret = context_b.getResponseString();
Party A:
+ * context_a.setPublicKey(ret); EncryptionOptions options = context_a.getEncryptionOptions(enc);
// decrypt
+ */
+public class DHBase implements Serializable {
+
+    private static final long serialVersionUID = 9145945368596071015L;
+    BigInteger p = null, g = null;
+    int l = 0;
+    private KeyPair keyPair;
+    private Key publicKey;
+
+    public DHBase() {
+        try {
+            init();
+        } catch (Exception e) {
+        }
+    }
+
+    public DHBase(String dh) {
+        try {
+            init(dh);
+        } catch (Exception e) {
+        }
+    }
+
+    protected DHBase(KeyPair keyPair, BigInteger p, BigInteger g, int l) {
+        this.keyPair = keyPair;
+        this.p = p;
+        this.g = g;
+        this.l = l;
+    }
+
+    public String getRequestString() {
+        StringBuilder buf = new StringBuilder();
+        buf.append(
+          String.format(
+              "DH p=%s, g=%s, k=%s",
+              p.toString(),
+              g.toString(),
+              Base64.encodeBase64String(keyPair.getPublic().getEncoded())));
+        return buf.toString();
+    }
+
+    public String getResponseString() {
+        StringBuilder buf = new StringBuilder();
+        buf.append(
+            String.format(
+                "DH k=%s",
+                Base64.encodeBase64String(keyPair.getPublic().getEncoded())));
+        return buf.toString();
+    }
+
+    private void init() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException,
+        InvalidParameterSpecException, InvalidKeySpecException {
+        AlgorithmParameterGenerator pgen = AlgorithmParameterGenerator.getInstance("DH");
+        pgen.init(512);
+        AlgorithmParameters params = pgen.generateParameters();
+        DHParameterSpec dhspec = (DHParameterSpec)params.getParameterSpec(DHParameterSpec.class);
+        KeyPairGenerator keypairgen = KeyPairGenerator.getInstance("DH");
+        keypairgen.initialize(dhspec);
+        keyPair = keypairgen.generateKeyPair();
+        p = dhspec.getP();
+        g = dhspec.getG();
+        l = dhspec.getL();
+    }
+
+    private void init(String dh) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException,
+        InvalidKeySpecException {
+        String[] segments = dh.split("\\s+", 2);
+        if (!segments[0].equalsIgnoreCase("DH"))
+            throw new IllegalArgumentException();
+        String[] params = segments[1].split("\\s*,\\s*");
+        byte[] key = null;
+        for (String param : params) {
+            String name = param.substring(0, param.indexOf("="));
+            String value = param.substring(param.indexOf("=") + 1);
+            if (name.equalsIgnoreCase("p"))
+                p = new BigInteger(value);
+            else if (name.equalsIgnoreCase("g"))
+                g = new BigInteger(value);
+            else if (name.equalsIgnoreCase("k"))
+                key = Base64.decodeBase64(value);
+        }
+        init(p, g, l, key);
+    }
+
+    private void init(BigInteger p, BigInteger g, int l, byte[] key) throws NoSuchAlgorithmException,
+        InvalidAlgorithmParameterException, InvalidKeySpecException {
+        DHParameterSpec spec = new DHParameterSpec(p, g, l);
+        KeyPairGenerator keypairgen = KeyPairGenerator.getInstance("DH");
+        keypairgen.initialize(spec);
+        keyPair = keypairgen.generateKeyPair();
+        publicKey = decode(key);
+    }
+
+    public KeyPair getKeyPair() {
+        return keyPair;
+    }
+
+    public Key getPublicKey() {
+        return publicKey;
+    }
+
+    private Key decode(byte[] key) throws NoSuchAlgorithmException, InvalidKeySpecException
{
+        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);
+        KeyFactory keyFact = KeyFactory.getInstance("DH");
+        return keyFact.generatePublic(x509KeySpec);
+    }
+
+    public DHBase setPublicKey(String dh) throws NoSuchAlgorithmException, InvalidKeySpecException
{
+        String[] segments = dh.split("\\s+", 2);
+        if (!segments[0].equalsIgnoreCase("DH"))
+            throw new IllegalArgumentException();
+        String[] tokens = segments[1].split("\\s*,\\s*");
+        byte[] key = null;
+        for (String token : tokens) {
+            String name = token.substring(0, token.indexOf("="));
+            String value = token.substring(token.indexOf("=") + 1);
+            if (name.equalsIgnoreCase("k"))
+                key = Base64.decodeBase64(value);
+        }
+        publicKey = decode(key);
+        return this;
+    }
+
+    public Key generateSecret() throws NoSuchAlgorithmException, InvalidKeyException {
+        KeyAgreement ka = KeyAgreement.getInstance("DH");
+        ka.init(keyPair.getPrivate());
+        ka.doPhase(publicKey, true);
+        return ka.generateSecret("DESede");
+    }
+    
+    public Key generateSecret(String alg) throws NoSuchAlgorithmException, InvalidKeyException
{
+      KeyAgreement ka = KeyAgreement.getInstance("DH");
+      ka.init(keyPair.getPrivate());
+      ka.doPhase(publicKey, true);
+      return ka.generateSecret(alg); 
+    }
+
+}

Propchange: abdera/abdera2/common/src/main/java/org/apache/abdera2/common/security/DHBase.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Modified: abdera/abdera2/common/src/main/java/org/apache/abdera2/common/security/KeyBase.java
URL: http://svn.apache.org/viewvc/abdera/abdera2/common/src/main/java/org/apache/abdera2/common/security/KeyBase.java?rev=1175994&r1=1175993&r2=1175994&view=diff
==============================================================================
--- abdera/abdera2/common/src/main/java/org/apache/abdera2/common/security/KeyBase.java (original)
+++ abdera/abdera2/common/src/main/java/org/apache/abdera2/common/security/KeyBase.java Mon
Sep 26 18:54:21 2011
@@ -65,11 +65,13 @@ public abstract class KeyBase {
     }
   }
   
-  protected byte[] hmac(byte[] mat){
+  protected byte[] hmac(byte[]... mat){
     try {
       Mac hmac = Mac.getInstance(alg);
       hmac.init(key);
-      return hmac.doFinal(mat);
+      for (byte[] m : mat)
+        hmac.update(m);
+      return hmac.doFinal();
     } catch (Throwable t) {
       throw new RuntimeException(t);
     }
@@ -81,4 +83,10 @@ public abstract class KeyBase {
     random.nextBytes(buf);
     return buf;
   }
+  
+  protected String pad(String s, int len, char c) {
+    while(s.length()<len)
+      s = c + s;
+    return s;
+  }
 }

Modified: abdera/abdera2/common/src/main/java/org/apache/abdera2/common/security/Otp.java
URL: http://svn.apache.org/viewvc/abdera/abdera2/common/src/main/java/org/apache/abdera2/common/security/Otp.java?rev=1175994&r1=1175993&r2=1175994&view=diff
==============================================================================
--- abdera/abdera2/common/src/main/java/org/apache/abdera2/common/security/Otp.java (original)
+++ abdera/abdera2/common/src/main/java/org/apache/abdera2/common/security/Otp.java Mon Sep
26 18:54:21 2011
@@ -43,32 +43,41 @@ public abstract class Otp extends KeyBas
     super(key,8);
   }
 
-  protected abstract String getMaterial();
+  /**
+   * Return the moving factor for this one-time-password. The
+   * moving factor is the "thing that changes" each time the 
+   * password is generated, resulting in a new password each
+   * time generateNext is called. For most applications, this 
+   * should be a 
+   */
+  protected abstract byte[] getMovingFactor();
   
+  /**
+   * Generates the next One-time-password based on the key and
+   * a moving factor retrieved by calling getMovingFactor(). 
+   * The Otp subclass instance is responsible for maintaining 
+   * the state necessary for retrieving the appropriate moving
+   * factor
+   */
   public String generateNext(){
-    String mat = getMaterial();
     int len = Math.max(1, Math.min(9, size));
-    while (mat.length() < 16 )
-      mat = "0" + mat;
-    byte[] h = hmac(dec(mat));
+    byte[] h = hmac(getMovingFactor());
     int o = h[h.length - 1] & 0xf;
-    int binary =
-        ((h[o] & 0x7f) << 24) |
+    return pad(
+      Integer.toString(
+        (((h[o] & 0x7f) << 24) |
         ((h[o + 1] & 0xff) << 16) |
         ((h[o + 2] & 0xff) << 8) |
-        (h[o + 3] & 0xff);
-    int otp = binary % (int)Math.pow(10, len);
-    String r = Integer.toString(otp);
-    while (r.length() < len)
-        r = "0" + r;
-    return r;
-  }
+        (h[o + 3] & 0xff))
+          % (int)Math.pow(10, len)),
+      len,'0');
+  } 
   
   /**
    * Utility implementation of the Time-based One Time Password (TOTP) 
    * algorithm. 
    */
-  public static final class Totp extends Otp {
+  public static class Totp extends Otp {
 
     private final int step;
     
@@ -118,11 +127,10 @@ public abstract class Otp extends KeyBas
     }
 
     @Override
-    protected String getMaterial() {
+    protected byte[] getMovingFactor() {
       long t = (System.currentTimeMillis() / 1000l) / step;
       String r = Long.toHexString(t);
-      while(r.length()<16) r = "0"+r;
-      return r;
+      return dec(pad(r,16,'0'));
     }
   }
 }

Modified: abdera/abdera2/security/src/main/java/org/apache/abdera2/security/util/DHContext.java
URL: http://svn.apache.org/viewvc/abdera/abdera2/security/src/main/java/org/apache/abdera2/security/util/DHContext.java?rev=1175994&r1=1175993&r2=1175994&view=diff
==============================================================================
--- abdera/abdera2/security/src/main/java/org/apache/abdera2/security/util/DHContext.java
(original)
+++ abdera/abdera2/security/src/main/java/org/apache/abdera2/security/util/DHContext.java
Mon Sep 26 18:54:21 2011
@@ -17,27 +17,11 @@
  */
 package org.apache.abdera2.security.util;
 
-import java.io.Serializable;
-import java.math.BigInteger;
-import java.security.AlgorithmParameterGenerator;
-import java.security.AlgorithmParameters;
-import java.security.InvalidAlgorithmParameterException;
 import java.security.InvalidKeyException;
-import java.security.Key;
-import java.security.KeyFactory;
-import java.security.KeyPair;
-import java.security.KeyPairGenerator;
 import java.security.NoSuchAlgorithmException;
-import java.security.spec.InvalidKeySpecException;
-import java.security.spec.InvalidParameterSpecException;
-import java.security.spec.X509EncodedKeySpec;
-
-import javax.crypto.KeyAgreement;
-import javax.crypto.spec.DHParameterSpec;
-
+import org.apache.abdera2.common.security.DHBase;
 import org.apache.abdera2.security.Encryption;
 import org.apache.abdera2.security.EncryptionOptions;
-import org.apache.axiom.om.util.Base64;
 import org.apache.xml.security.encryption.XMLCipher;
 
 /**
@@ -46,148 +30,29 @@ import org.apache.xml.security.encryptio
  * options = context_b.getEncryptionOptions(enc); // encrypt String ret = context_b.getResponseString();
Party A:
  * context_a.setPublicKey(ret); EncryptionOptions options = context_a.getEncryptionOptions(enc);
// decrypt
  */
-public class DHContext implements Cloneable, Serializable {
+public class DHContext extends DHBase {
 
-    private static final long serialVersionUID = 9145945368596071015L;
-    BigInteger p = null, g = null;
-    int l = 0;
-    private KeyPair keyPair;
-    private Key publicKey;
+    private static final long serialVersionUID = -2717424739180671914L;
 
     public DHContext() {
-        try {
-            init();
-        } catch (Exception e) {
-        }
+      super();
     }
 
     public DHContext(String dh) {
-        try {
-            init(dh);
-        } catch (Exception e) {
-        }
-    }
-
-    private DHContext(KeyPair keyPair, BigInteger p, BigInteger g, int l) {
-        this.keyPair = keyPair;
-        this.p = p;
-        this.g = g;
-        this.l = l;
-    }
-
-    public String getRequestString() {
-        StringBuilder buf = new StringBuilder();
-        buf.append(
-          String.format(
-              "DH p=%s, g=%s, k=%s",
-              p.toString(),
-              g.toString(),
-              Base64.encode(keyPair.getPublic().getEncoded())));
-        return buf.toString();
-    }
-
-    public String getResponseString() {
-        StringBuilder buf = new StringBuilder();
-        buf.append(
-            String.format(
-                "DH k=%s",
-                Base64.encode(keyPair.getPublic().getEncoded())));
-        return buf.toString();
-    }
-
-    private void init() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException,
-        InvalidParameterSpecException, InvalidKeySpecException {
-        AlgorithmParameterGenerator pgen = AlgorithmParameterGenerator.getInstance("DH");
-        pgen.init(512);
-        AlgorithmParameters params = pgen.generateParameters();
-        DHParameterSpec dhspec = (DHParameterSpec)params.getParameterSpec(DHParameterSpec.class);
-        KeyPairGenerator keypairgen = KeyPairGenerator.getInstance("DH");
-        keypairgen.initialize(dhspec);
-        keyPair = keypairgen.generateKeyPair();
-        p = dhspec.getP();
-        g = dhspec.getG();
-        l = dhspec.getL();
-    }
-
-    private void init(String dh) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException,
-        InvalidKeySpecException {
-        String[] segments = dh.split("\\s+", 2);
-        if (!segments[0].equalsIgnoreCase("DH"))
-            throw new IllegalArgumentException();
-        String[] params = segments[1].split("\\s*,\\s*");
-        byte[] key = null;
-        for (String param : params) {
-            String name = param.substring(0, param.indexOf("="));
-            String value = param.substring(param.indexOf("=") + 1);
-            if (name.equalsIgnoreCase("p"))
-                p = new BigInteger(value);
-            else if (name.equalsIgnoreCase("g"))
-                g = new BigInteger(value);
-            else if (name.equalsIgnoreCase("k"))
-                key = Base64.decode(value);
-        }
-        init(p, g, l, key);
-    }
-
-    private void init(BigInteger p, BigInteger g, int l, byte[] key) throws NoSuchAlgorithmException,
-        InvalidAlgorithmParameterException, InvalidKeySpecException {
-        DHParameterSpec spec = new DHParameterSpec(p, g, l);
-        KeyPairGenerator keypairgen = KeyPairGenerator.getInstance("DH");
-        keypairgen.initialize(spec);
-        keyPair = keypairgen.generateKeyPair();
-        publicKey = decode(key);
-    }
-
-    public KeyPair getKeyPair() {
-        return keyPair;
-    }
-
-    public Key getPublicKey() {
-        return publicKey;
-    }
-
-    private Key decode(byte[] key) throws NoSuchAlgorithmException, InvalidKeySpecException
{
-        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);
-        KeyFactory keyFact = KeyFactory.getInstance("DH");
-        return keyFact.generatePublic(x509KeySpec);
+        super(dh);
     }
 
-    public DHContext setPublicKey(String dh) throws NoSuchAlgorithmException, InvalidKeySpecException
{
-        String[] segments = dh.split("\\s+", 2);
-        if (!segments[0].equalsIgnoreCase("DH"))
-            throw new IllegalArgumentException();
-        String[] tokens = segments[1].split("\\s*,\\s*");
-        byte[] key = null;
-        for (String token : tokens) {
-            String name = token.substring(0, token.indexOf("="));
-            String value = token.substring(token.indexOf("=") + 1);
-            if (name.equalsIgnoreCase("k"))
-                key = Base64.decode(value);
-        }
-        publicKey = decode(key);
-        return this;
+    public EncryptionOptions getEncryptionOptions(Encryption enc) 
+      throws InvalidKeyException, NoSuchAlgorithmException {
+        return getEncryptionOptions(enc, XMLCipher.TRIPLEDES);
     }
-
-    public Key generateSecret() throws NoSuchAlgorithmException, InvalidKeyException {
-        KeyAgreement ka = KeyAgreement.getInstance("DH");
-        ka.init(keyPair.getPrivate());
-        ka.doPhase(publicKey, true);
-        return ka.generateSecret("DESede");
-    }
-
-    public EncryptionOptions getEncryptionOptions(Encryption enc) throws InvalidKeyException,
NoSuchAlgorithmException {
+    
+    public EncryptionOptions getEncryptionOptions(Encryption enc, String alg) 
+      throws InvalidKeyException, NoSuchAlgorithmException {
         EncryptionOptions options = enc.getDefaultEncryptionOptions();
         options.setDataEncryptionKey(generateSecret());
-        options.setDataCipherAlgorithm(XMLCipher.TRIPLEDES);
+        options.setDataCipherAlgorithm(alg);
         return options;
-    }
-
-    @Override
-    public Object clone() throws CloneNotSupportedException {
-        if (publicKey != null)
-            throw new CloneNotSupportedException();
-        // create a copy, not an actual clone
-        return new DHContext(keyPair, p, g, l);
-    }
+  }
 
 }



Mime
View raw message