2012-11-14 36 views
1

我们可以做任何我们需要使用密钥工具与java.security API,如KeyPairGenerator的等我们可以做任何我们需要使用密钥工具与java.security API,如KeyPairGenerator的等

我感兴趣的证书与特定的延伸有效性。

例如可以下面的命令运行使用Java安全API

密钥工具-genkeypair {-alias别名} {-keyalg keyalg} {-keysize密钥大小} {-sigalg sigalg} [-dname DNAME来完成] [-keypass keypass的] {-validity valDays} {-storetype的storetype}

我希望只使用Java核心安全API和第三方API的

回答

0

不感兴趣,大多数操作是keytool(在至少那些tha T I知道),可以使用java.security.*类的一些aditional的公用事业类重新创建,例如,创建一个新的密钥对,您可以使用:

private static final String ALGORITHM = "RSA"; 
private static final String PROVIDER = "BC"; 

private PrivateKey privateKey; 
private PublicKey publicKey; 

... 

public void generateNewKeyPair() { 
    try { 
     KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM, PROVIDER); 
     keyGen.initialize(2048, new SecureRandom()); 
     KeyPair keypair = keyGen.genKeyPair(); 
     privateKey = keypair.getPrivate(); 
     publicKey = keypair.getPublic(); 
    } catch (Exception e) { 
     LOG.error("Error creating keyPair", e); 
    } 
} 

这里是一个KeyStore

example of retrieving一个KeyPair下面是一个(更详细说明)example,不仅创造了KeyPair,也将其存储在一个文件

还可以序列的KeyPair旁边一个到期时间戳记为SealedObject模拟无论是validity参数和所提供的存储keytool

编辑:SealedObject不会单独给你validity参数仿真,与密钥对(在SealedObject)一起存储的时间戳,将“模拟”过期日期(可以看作是密钥的有效性)。例如:

class KeyWithExpiration { 
    private PublicKey publicKey; 
    private Date expirationDate; 
} 

public static void serializeEncrypted(File file, Serializable instance) { 
    // With these lines, I hope to expose some of the craft that is needed to work with the API 
    PBEKeySpec keySpecObj = new PBEKeySpec(PASSWORD, SALT, ITERATIONS); 
    Cipher ecipherObj = Cipher.getInstance(keyObj.getAlgorithm()); 
    SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(ALGORITHM); 
    SecretKey keyObj = secretKeyFactory.generateSecret(keySpecObj); 

    SealedObject sealedObject = new SealedObject(instance, ecipherObj); 

    ObjectOutputStream objOutputStream = new ObjectOutputStream(new FileOutputStream(file)); 
    objOutputStream.writeObject(sealedObject); 
    objOutputStream.close(); 
} 

// Generate a new KeyWithExpiration 
KeyWithExpiration key = new KeyWithExpiration(keyPair, DateUtil.future().days(365)); 
serializeEncrypted(new File(".key"), key); 

这就是为什么需要这些API加上一些实用工具类,实现一些由keytool

+0

提供的功能能否请您澄清使用SealedObject的有效性。我没有在SealeObject中看到任何设置有效期限/过期的API。谢谢 –

相关问题