一、前言
关于apache的hadoop-gateway-spi源码包定义org.apache.hadoop.gateway.services.security.impl.X509CertificateUtil证书工具类,生成获取java.security.cert.X509Certificate认证证书对象,详情参见代码示例说明。
二、代码示例
1.X509CertificateUtil类
package org.apache.hadoop.gateway.services.security.impl;@b@@b@import java.io.IOException;@b@import java.lang.reflect.Constructor;@b@import java.lang.reflect.Field;@b@import java.lang.reflect.Method;@b@import java.math.BigInteger;@b@import java.security.GeneralSecurityException;@b@import java.security.KeyPair;@b@import java.security.PrivateKey;@b@import java.security.PublicKey;@b@import java.security.SecureRandom;@b@import java.security.cert.X509Certificate;@b@import java.util.Date;@b@import org.apache.hadoop.gateway.i18n.GatewaySpiMessages;@b@import org.apache.hadoop.gateway.i18n.messages.MessagesFactory;@b@@b@public class X509CertificateUtil@b@{@b@ private static GatewaySpiMessages LOG = (GatewaySpiMessages)MessagesFactory.get(GatewaySpiMessages.class);@b@@b@ public static X509Certificate generateCertificate(String dn, KeyPair pair, int days, String algorithm)@b@ throws GeneralSecurityException, IOException@b@ {@b@ PrivateKey privkey = pair.getPrivate();@b@ Object x509CertImplObject = null;@b@ try {@b@ Date from = new Date();@b@ Date to = new Date(from.getTime() + days * 86400000L);@b@@b@ Class certInfoClass = Class.forName(getX509CertInfoModuleName());@b@ Constructor certInfoConstr = certInfoClass.getConstructor(new Class[0]);@b@ Object certInfoObject = certInfoConstr.newInstance(new Object[0]);@b@@b@ Class certValidityClass = Class.forName(getX509CertifValidityModuleName());@b@ Constructor certValidityConstr = certValidityClass.getConstructor(new Class[] { Date.class, Date.class });@b@@b@ Object certValidityObject = certValidityConstr.newInstance(new Object[] { from, to });@b@@b@ BigInteger sn = new BigInteger(64, new SecureRandom());@b@@b@ Class x500NameClass = Class.forName(getX509X500NameModuleName());@b@ Constructor x500NameConstr = x500NameClass.getConstructor(new Class[] { String.class });@b@@b@ Object x500NameObject = x500NameConstr.newInstance(new Object[] { dn });@b@@b@ Method methodSET = certInfoObject.getClass().getMethod("set", new Class[] { String.class, Object.class });@b@@b@ methodSET.invoke(certInfoObject, new Object[] { getSetField(certInfoObject, "VALIDITY"), certValidityObject });@b@@b@ Class certificateSerialNumberClass = Class.forName(getCertificateSerialNumberModuleName());@b@ Constructor certificateSerialNumberConstr = certificateSerialNumberClass.getConstructor(new Class[] { BigInteger.class });@b@@b@ Object certificateSerialNumberObject = certificateSerialNumberConstr.newInstance(new Object[] { sn });@b@@b@ methodSET.invoke(certInfoObject, new Object[] { getSetField(certInfoObject, "SERIAL_NUMBER"), certificateSerialNumberObject });@b@@b@ Class certificateSubjectNameClass = Class.forName(getCertificateSubjectNameModuleName());@b@ Constructor certificateSubjectNameConstr = certificateSubjectNameClass.getConstructor(new Class[] { x500NameClass });@b@@b@ Object certificateSubjectNameObject = certificateSubjectNameConstr.newInstance(new Object[] { x500NameObject });@b@@b@ methodSET.invoke(certInfoObject, new Object[] { getSetField(certInfoObject, "SUBJECT"), certificateSubjectNameObject });@b@@b@ Class certificateIssuerNameClass = Class.forName(getCertificateIssuerNameModuleName());@b@ Constructor certificateIssuerNameConstr = certificateIssuerNameClass.getConstructor(new Class[] { x500NameClass });@b@@b@ Object certificateIssuerNameObject = certificateIssuerNameConstr.newInstance(new Object[] { x500NameObject });@b@@b@ methodSET.invoke(certInfoObject, new Object[] { getSetField(certInfoObject, "ISSUER"), certificateIssuerNameObject });@b@@b@ Class certificateX509KeyClass = Class.forName(getCertificateX509KeyModuleName());@b@ Constructor certificateX509KeyConstr = certificateX509KeyClass.getConstructor(new Class[] { PublicKey.class });@b@@b@ Object certificateX509KeyObject = certificateX509KeyConstr.newInstance(new Object[] { pair.getPublic() });@b@@b@ methodSET.invoke(certInfoObject, new Object[] { getSetField(certInfoObject, "KEY"), certificateX509KeyObject });@b@@b@ Class certificateVersionClass = Class.forName(getCertificateVersionModuleName());@b@ Constructor certificateVersionConstr = certificateVersionClass.getConstructor(new Class[] { Integer.TYPE });@b@@b@ Constructor certificateVersionConstr0 = certificateVersionClass.getConstructor(new Class[0]);@b@@b@ Object certInfoObject0 = certificateVersionConstr0.newInstance(new Object[0]);@b@ Field v3IntField = certInfoObject0.getClass().getDeclaredField("V3");@b@@b@ v3IntField.setAccessible(true);@b@ int fValue = v3IntField.getInt(certInfoObject0);@b@ Object certificateVersionObject = certificateVersionConstr.newInstance(new Object[] { Integer.valueOf(fValue) });@b@@b@ methodSET.invoke(certInfoObject, new Object[] { getSetField(certInfoObject, "VERSION"), certificateVersionObject });@b@@b@ Class algorithmIdClass = Class.forName(getAlgorithmIdModuleName());@b@ Field md5WithRSAField = algorithmIdClass.getDeclaredField("md5WithRSAEncryption_oid");@b@@b@ md5WithRSAField.setAccessible(true);@b@ Class objectIdentifierClass = Class.forName(getObjectIdentifierModuleName());@b@@b@ Object md5WithRSAValue = md5WithRSAField.get(algorithmIdClass);@b@@b@ Constructor algorithmIdConstr = algorithmIdClass.getConstructor(new Class[] { objectIdentifierClass });@b@@b@ Object algorithmIdObject = algorithmIdConstr.newInstance(new Object[] { md5WithRSAValue });@b@@b@ Class certificateAlgorithmIdClass = Class.forName(getCertificateAlgorithmIdModuleName());@b@ Constructor certificateAlgorithmIdConstr = certificateAlgorithmIdClass.getConstructor(new Class[] { algorithmIdClass });@b@@b@ Object certificateAlgorithmIdObject = certificateAlgorithmIdConstr.newInstance(new Object[] { algorithmIdObject });@b@@b@ methodSET.invoke(certInfoObject, new Object[] { getSetField(certInfoObject, "ALGORITHM_ID"), certificateAlgorithmIdObject });@b@@b@ Class x509CertImplClass = Class.forName(getX509CertImplModuleName());@b@ Constructor x509CertImplConstr = x509CertImplClass.getConstructor(new Class[] { certInfoClass });@b@@b@ x509CertImplObject = x509CertImplConstr.newInstance(new Object[] { certInfoObject });@b@@b@ Method methoSIGN = x509CertImplObject.getClass().getMethod("sign", new Class[] { PrivateKey.class, String.class });@b@@b@ methoSIGN.invoke(x509CertImplObject, new Object[] { privkey, algorithm });@b@@b@ Method methoGET = x509CertImplObject.getClass().getMethod("get", new Class[] { String.class });@b@ String sig_alg = getSetField(x509CertImplObject, "SIG_ALG");@b@@b@ String certAlgoIdNameValue = getSetField(certificateAlgorithmIdObject, "NAME");@b@ String certAlgoIdAlgoValue = getSetField(certificateAlgorithmIdObject, "ALGORITHM");@b@@b@ methodSET.invoke(certInfoObject, new Object[] { certAlgoIdNameValue + "." + certAlgoIdAlgoValue, methoGET.invoke(x509CertImplObject, new Object[] { sig_alg }) });@b@@b@ x509CertImplObject = x509CertImplConstr.newInstance(new Object[] { certInfoObject });@b@@b@ methoSIGN.invoke(x509CertImplObject, new Object[] { privkey, algorithm });@b@ } catch (Exception e) {@b@ LOG.failedToGenerateCertificate(e);@b@ }@b@ return ((X509Certificate)x509CertImplObject);@b@ }@b@@b@ private static String getX509CertInfoModuleName() {@b@ return ((java.lang.System.getProperty("java.vendor").contains("IBM")) ? "com.ibm.security.x509.X509CertInfo" : "sun.security.x509.X509CertInfo");@b@ }@b@@b@ private static String getX509CertifValidityModuleName()@b@ {@b@ return ((java.lang.System.getProperty("java.vendor").contains("IBM")) ? "com.ibm.security.x509.CertificateValidity" : "sun.security.x509.CertificateValidity");@b@ }@b@@b@ private static String getX509X500NameModuleName()@b@ {@b@ return ((java.lang.System.getProperty("java.vendor").contains("IBM")) ? "com.ibm.security.x509.X500Name" : "sun.security.x509.X500Name");@b@ }@b@@b@ private static String getCertificateSerialNumberModuleName()@b@ {@b@ return ((java.lang.System.getProperty("java.vendor").contains("IBM")) ? "com.ibm.security.x509.CertificateSerialNumber" : "sun.security.x509.CertificateSerialNumber");@b@ }@b@@b@ private static String getCertificateSubjectNameModuleName()@b@ {@b@ return ((java.lang.System.getProperty("java.vendor").contains("IBM")) ? "com.ibm.security.x509.CertificateSubjectName" : "sun.security.x509.CertificateSubjectName");@b@ }@b@@b@ private static String getCertificateIssuerNameModuleName()@b@ {@b@ return ((java.lang.System.getProperty("java.vendor").contains("IBM")) ? "com.ibm.security.x509.CertificateIssuerName" : "sun.security.x509.CertificateIssuerName");@b@ }@b@@b@ private static String getCertificateX509KeyModuleName()@b@ {@b@ return ((java.lang.System.getProperty("java.vendor").contains("IBM")) ? "com.ibm.security.x509.CertificateX509Key" : "sun.security.x509.CertificateX509Key");@b@ }@b@@b@ private static String getCertificateVersionModuleName()@b@ {@b@ return ((java.lang.System.getProperty("java.vendor").contains("IBM")) ? "com.ibm.security.x509.CertificateVersion" : "sun.security.x509.CertificateVersion");@b@ }@b@@b@ private static String getAlgorithmIdModuleName()@b@ {@b@ return ((java.lang.System.getProperty("java.vendor").contains("IBM")) ? "com.ibm.security.x509.AlgorithmId" : "sun.security.x509.AlgorithmId");@b@ }@b@@b@ private static String getObjectIdentifierModuleName()@b@ {@b@ return ((java.lang.System.getProperty("java.vendor").contains("IBM")) ? "com.ibm.security.util.ObjectIdentifier" : "sun.security.util.ObjectIdentifier");@b@ }@b@@b@ private static String getCertificateAlgorithmIdModuleName()@b@ {@b@ return ((java.lang.System.getProperty("java.vendor").contains("IBM")) ? "com.ibm.security.x509.CertificateAlgorithmId" : "sun.security.x509.CertificateAlgorithmId");@b@ }@b@@b@ private static String getX509CertImplModuleName()@b@ {@b@ return ((java.lang.System.getProperty("java.vendor").contains("IBM")) ? "com.ibm.security.x509.X509CertImpl" : "sun.security.x509.X509CertImpl");@b@ }@b@@b@ private static String getSetField(Object obj, String setString)@b@ throws Exception@b@ {@b@ Field privateStringField = obj.getClass().getDeclaredField(setString);@b@ privateStringField.setAccessible(true);@b@ String fieldValue = (String)privateStringField.get(obj);@b@ return fieldValue;@b@ }@b@}
2.GatewaySpiMessages接口
package org.apache.hadoop.gateway.i18n;@b@@b@import org.apache.hadoop.gateway.i18n.messages.Message;@b@import org.apache.hadoop.gateway.i18n.messages.MessageLevel;@b@import org.apache.hadoop.gateway.i18n.messages.Messages;@b@import org.apache.hadoop.gateway.i18n.messages.StackTrace;@b@@b@@Messages(logger="org.apache.hadoop.gateway")@b@public abstract interface GatewaySpiMessages@b@{@b@ @Message(level=MessageLevel.ERROR, text="Failed to load the internal principal mapping table: {0}")@b@ public abstract void failedToLoadPrincipalMappingTable(@StackTrace(level=MessageLevel.DEBUG) Exception paramException);@b@@b@ @Message(level=MessageLevel.ERROR, text="Failed to execute filter: {0}")@b@ public abstract void failedToExecuteFilter(@StackTrace(level=MessageLevel.DEBUG) Throwable paramThrowable);@b@@b@ @Message(level=MessageLevel.ERROR, text="Failed to encrypt passphrase: {0}")@b@ public abstract void failedToEncryptPassphrase(@StackTrace(level=MessageLevel.DEBUG) Exception paramException);@b@@b@ @Message(level=MessageLevel.ERROR, text="Failed to generate secret key from password: {0}")@b@ public abstract void failedToGenerateKeyFromPassword(@StackTrace(level=MessageLevel.DEBUG) Exception paramException);@b@@b@ @Message(level=MessageLevel.ERROR, text="Failed to create keystore [filename={0}, type={1}]: {2}")@b@ public abstract void failedToCreateKeystore(String paramString1, String paramString2, @StackTrace(level=MessageLevel.DEBUG) Exception paramException);@b@@b@ @Message(level=MessageLevel.ERROR, text="Failed to load keystore [filename={0}, type={1}]: {2}")@b@ public abstract void failedToLoadKeystore(String paramString1, String paramString2, @StackTrace(level=MessageLevel.DEBUG) Exception paramException);@b@@b@ @Message(level=MessageLevel.ERROR, text="Failed to add credential: {1}")@b@ public abstract void failedToAddCredential(@StackTrace(level=MessageLevel.DEBUG) Exception paramException);@b@@b@ @Message(level=MessageLevel.ERROR, text="Failed to get credential: {1}")@b@ public abstract void failedToGetCredential(@StackTrace(level=MessageLevel.DEBUG) Exception paramException);@b@@b@ @Message(level=MessageLevel.ERROR, text="Failed to persist master secret: {0}")@b@ public abstract void failedToPersistMasterSecret(@StackTrace(level=MessageLevel.DEBUG) Exception paramException);@b@@b@ @Message(level=MessageLevel.ERROR, text="Failed to encrypt master secret: {0}")@b@ public abstract void failedToEncryptMasterSecret(@StackTrace(level=MessageLevel.DEBUG) Exception paramException);@b@@b@ @Message(level=MessageLevel.ERROR, text="Failed to initialize master service from persistent master {0}: {1}")@b@ public abstract void failedToInitializeFromPersistentMaster(String paramString, @StackTrace(level=MessageLevel.DEBUG) Exception paramException);@b@@b@ @Message(level=MessageLevel.ERROR, text="Failed to add self signed certificate for Gateway {0}: {1}")@b@ public abstract void failedToAddSeflSignedCertForGateway(String paramString, @StackTrace(level=MessageLevel.DEBUG) Exception paramException);@b@@b@ @Message(level=MessageLevel.ERROR, text="Failed to get key {0}: {1}")@b@ public abstract void failedToGetKey(String paramString, @StackTrace(level=MessageLevel.DEBUG) Exception paramException);@b@@b@ @Message(level=MessageLevel.DEBUG, text="Loading from persistent master: {0}")@b@ public abstract void loadingFromPersistentMaster(String paramString);@b@@b@ @Message(level=MessageLevel.DEBUG, text="ALIAS: {0}")@b@ public abstract void printClusterAlias(String paramString);@b@@b@ @Message(level=MessageLevel.DEBUG, text="MASTER SERVICE == NULL: {0}")@b@ public abstract void printMasterServiceIsNull(boolean paramBoolean);@b@@b@ @Message(level=MessageLevel.ERROR, text="Gateway has failed to start. Unable to prompt user for master secret setup. Please consider using knoxcli.sh create-master")@b@ public abstract void unableToPromptForMasterUseKnoxCLI();@b@@b@ @Message(level=MessageLevel.ERROR, text="Error in generating certificate: {0}")@b@ public abstract void failedToGenerateCertificate(@StackTrace(level=MessageLevel.ERROR) Exception paramException);@b@}