SHARE
TWEET

Mike Nerone

a guest Nov 20th, 2008 129 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/env bash
  2. #
  3. # Author: Mike Nerone <mike.nerone@rackspace.com>
  4. #
  5. # Usage: pem2jks domain [password]
  6. #
  7. #   Read standard input and puts first key and all
  8. #   certificates into domain.jks. Note that due to openssl
  9. #   requirements, the key must come before the matching
  10. #   certificate.
  11. #
  12. # Arguments:
  13. #
  14. #   domain:   intended to be the domain name. Technically,
  15. #             it just becomes the JKS filename and alias.
  16. #
  17. #   password: used as the keystore and key password for
  18. #             the JKS file. Default is "changeit".
  19. #
  20.  
  21. prog="$(basename $0)"
  22. path_of_this_script=`dirname "${0}"`
  23. path_of_this_script=${path_of_this_script/".\/"/"$(pwd)\/"}
  24. p12temp="$(mktemp -t pem2jks.XXXXXX)"
  25. p12="${p12temp}"
  26. jar=${path_of_this_script}/../share/concert/pkcs12import.jar
  27. class=com.sun.xml.wss.tools.PKCS12Import
  28. dn="CN=dummy, OU=dummy, O=dummy, L=dummy, ST=dummy, C=dummy"
  29.  
  30. die () {
  31.     echo "$prog: $1";
  32.     exit 1;
  33. }
  34.  
  35. usage () {
  36.     echo "Usage: ${prog} <keystore> [password]"
  37.     exit 1;
  38. }
  39.  
  40. [[ $# == 0 || $# > 2 ]] && usage;
  41.  
  42. keystore="${1}.jks"
  43. password="${2}"
  44. shift; shift
  45.  
  46. [[ -z "${password}" ]] && password="changeit"
  47. [[ -e "${keystore}" ]] && die "JKS keystore $keystore already exists"
  48.  
  49. convert () {
  50.    openssl_args="-export -name \"${domain}\" -passout pass:${password} -out ${p12}"
  51.    
  52.    openssl pkcs12 $openssl_args || die "Unable to convert to PKCS12"
  53.    
  54.    # If one does not already exist, create the JKS
  55.    # keystore with a dummy entry. Remove it the
  56.    # dummy entry immediately.
  57.    keytool_args="-alias dummy \
  58. -keystore ${keystore} \
  59. -storepass ${password} \
  60. -keypass ${password}"
  61.    
  62.    if [[ ! -f ${keystore} ]]; then  
  63.        keytool -genkey $keytool_args -dname "${dn}" || die 'Unable to create JKS keystore'
  64.        keytool -delete $keytool_args || die 'Unable to clear JKS keystore'
  65.    fi
  66.    
  67.    # Use PKCS12Import to convert PKCS12 to JKS
  68.    java_args="-file ${p12} \
  69. -pass ${password} \
  70. -alias \"root\" \
  71. -keypass ${password} \
  72. -storepass ${password} \
  73. -keystore ${keystore}"
  74.    
  75.    java -classpath $jar $class $java_args || die 'Unable to convert PKCS12 to JKS'
  76.    
  77.    # Remove the temporary file
  78.    rm -f "${p12temp}";
  79. }
  80.  
  81. convert;
  82.  
  83. exit 0;
RAW Paste Data
Top