package com.sun.identity.saml.common;

import com.sun.identity.common.SystemConfigurationUtil;
import com.sun.identity.saml.xmlsig.PasswordDecoder;
import com.sun.identity.shared.debug.Debug;
import java.security.SecureRandom;

public class SAMLUtilsCommon {
   private static final String PASSWORD_DECODER = "com.sun.identity.saml.xmlsig.passwordDecoder";
   private static final SecureRandom RANDOM = new SecureRandom();
   public static final Debug DEBUG = Debug.getInstance("libSAML");
   private static final String SAMLID_PREFIX = "s";

   public static String generateID() {
      byte[] bytes = new byte[20];
      RANDOM.nextBytes(bytes);
      String encodedID = "s" + byteArrayToHexString(bytes);
      if (DEBUG.messageEnabled()) {
         DEBUG.message("SAMLUtils.generated ID is: " + encodedID);
      }

      return encodedID;
   }

   private static String byteArrayToHexString(byte[] byteArray) {
      StringBuilder hexData = new StringBuilder();

      for (byte b : byteArray) {
         int onebyte = 255 & b | -256;
         hexData.append(Integer.toHexString(onebyte).substring(6));
      }

      return hexData.toString();
   }

   public static String decodePassword(String password) {
      String decodePwdSpi = SystemConfigurationUtil.getProperty("com.sun.identity.saml.xmlsig.passwordDecoder");

      try {
         PasswordDecoder pwdDecoder = (PasswordDecoder)Class.forName(decodePwdSpi).getDeclaredConstructor().newInstance();
         return pwdDecoder.getDecodedPassword(password);
      } catch (Throwable t) {
         return password;
      }
   }
}
