下面列出了怎么用java.security.spec.AlgorithmParameterSpec的API类实例代码及写法,或者点击链接到github查看源代码。
protected void engineInit(AlgorithmParameterSpec params,
SecureRandom random) throws InvalidAlgorithmParameterException {
if (params instanceof TlsKeyMaterialParameterSpec == false) {
throw new InvalidAlgorithmParameterException(MSG);
}
this.spec = (TlsKeyMaterialParameterSpec)params;
try {
p11Key = P11SecretKeyFactory.convertKey
(token, spec.getMasterSecret(), "TlsMasterSecret");
} catch (InvalidKeyException e) {
throw new InvalidAlgorithmParameterException("init() failed", e);
}
version = (spec.getMajorVersion() << 8) | spec.getMinorVersion();
if ((version < 0x0300) && (version > 0x0302)) {
throw new InvalidAlgorithmParameterException
("Only SSL 3.0, TLS 1.0, and TLS 1.1 are supported");
}
// we assume the token supports both the CKM_SSL3_* and the CKM_TLS_*
// mechanisms
}
/**
* Constructs a parameter set for OAEP padding as defined in
* the PKCS #1 standard using the specified message digest
* algorithm <code>mdName</code>, mask generation function
* algorithm <code>mgfName</code>, parameters for the mask
* generation function <code>mgfSpec</code>, and source of
* the encoding input P <code>pSrc</code>.
*
* @param mdName the algorithm name for the message digest.
* @param mgfName the algorithm name for the mask generation
* function.
* @param mgfSpec the parameters for the mask generation function.
* If null is specified, null will be returned by getMGFParameters().
* @param pSrc the source of the encoding input P.
* @exception NullPointerException if <code>mdName</code>,
* <code>mgfName</code>, or <code>pSrc</code> is null.
*/
public OAEPParameterSpec(String mdName, String mgfName,
AlgorithmParameterSpec mgfSpec,
PSource pSrc) {
if (mdName == null) {
throw new NullPointerException("digest algorithm is null");
}
if (mgfName == null) {
throw new NullPointerException("mask generation function " +
"algorithm is null");
}
if (pSrc == null) {
throw new NullPointerException("source of the encoding input " +
"is null");
}
this.mdName = mdName;
this.mgfName = mgfName;
this.mgfSpec = mgfSpec;
this.pSrc = pSrc;
}
protected void engineInit(
int opmode,
Key key,
AlgorithmParameters params,
SecureRandom random)
throws InvalidKeyException, InvalidAlgorithmParameterException
{
AlgorithmParameterSpec paramSpec = null;
if (params != null)
{
try
{
paramSpec = params.getParameterSpec(OAEPParameterSpec.class);
}
catch (InvalidParameterSpecException e)
{
throw new InvalidAlgorithmParameterException("cannot recognise parameters: " + e.toString(), e);
}
}
engineParams = params;
engineInit(opmode, key, paramSpec, random);
}
protected <T extends AlgorithmParameterSpec>
T engineGetParameterSpec(Class<T> paramSpec)
throws InvalidParameterSpecException
{
try {
Class<?> dsaParamSpec = Class.forName
("java.security.spec.DSAParameterSpec");
if (dsaParamSpec.isAssignableFrom(paramSpec)) {
return paramSpec.cast(
new DSAParameterSpec(this.p, this.q, this.g));
} else {
throw new InvalidParameterSpecException
("Inappropriate parameter Specification");
}
} catch (ClassNotFoundException e) {
throw new InvalidParameterSpecException
("Unsupported parameter specification: " + e.getMessage());
}
}
/**
* Initializes this parameter generator with a set of
* algorithm-specific parameter generation values.
*
* @param genParamSpec the set of algorithm-specific parameter generation values
* @param random the source of randomness
*
* @exception InvalidAlgorithmParameterException if the given parameter
* generation values are inappropriate for this parameter generator
*/
protected void engineInit(AlgorithmParameterSpec genParamSpec,
SecureRandom random)
throws InvalidAlgorithmParameterException {
if (!(genParamSpec instanceof DSAGenParameterSpec)) {
throw new InvalidAlgorithmParameterException("Invalid parameter");
}
DSAGenParameterSpec dsaGenParams = (DSAGenParameterSpec) genParamSpec;
int primePLen = dsaGenParams.getPrimePLength();
if (primePLen > 2048) {
throw new InvalidParameterException
("No support for prime size " + primePLen);
}
// directly initialize using the already validated values
this.valueL = primePLen;
this.valueN = dsaGenParams.getSubprimeQLength();
this.seedLen = dsaGenParams.getSeedLength();
this.random = random;
}
@Override
protected void engineInit(
Key key,
AlgorithmParameterSpec params,
SecureRandom random)
throws InvalidKeyException, InvalidAlgorithmParameterException
{
if (!(key instanceof ECPrivateKey))
{
throw new InvalidKeyException("ECKeyAgreement requires ECPrivateKey for initialisation");
}
privKey = ECUtil.generatePrivateKeyParameter((PrivateKey)key);
agreement.init(privKey);
}
/**
* Initializes this parameter generator with a set of
* algorithm-specific parameter generation values.
*
* @param genParamSpec the set of algorithm-specific parameter generation values
* @param random the source of randomness
*
* @exception InvalidAlgorithmParameterException if the given parameter
* generation values are inappropriate for this parameter generator
*/
protected void engineInit(AlgorithmParameterSpec genParamSpec,
SecureRandom random)
throws InvalidAlgorithmParameterException {
if (!(genParamSpec instanceof DSAGenParameterSpec)) {
throw new InvalidAlgorithmParameterException("Invalid parameter");
}
DSAGenParameterSpec dsaGenParams = (DSAGenParameterSpec) genParamSpec;
int primePLen = dsaGenParams.getPrimePLength();
if (primePLen > 2048) {
throw new InvalidParameterException
("No support for prime size " + primePLen);
}
// directly initialize using the already validated values
this.valueL = primePLen;
this.valueN = dsaGenParams.getSubprimeQLength();
this.seedLen = dsaGenParams.getSeedLength();
this.random = random;
}
/**
* DES算法,加密
*
* @param data 待加密字符串
* @param key 加密私钥,长度不能够小于8位
* @return 加密后的字节数组,一般结合Base64编码使用
* @throws InvalidAlgorithmParameterException
* @throws Exception
*/
public static String encrypt(String key,String data) {
if(data == null)
return null;
try{
DESKeySpec dks = new DESKeySpec(key.getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
//key的长度不能够小于8位字节
Key secretKey = keyFactory.generateSecret(dks);
Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
AlgorithmParameterSpec paramSpec = new IvParameterSpec(IV_PARAMS_BYTES);;
cipher.init(Cipher.ENCRYPT_MODE, secretKey,paramSpec);
byte[] bytes = cipher.doFinal(data.getBytes());
return byte2hex(bytes);
}catch(Exception e){
throw new RuntimeException(e);
}
}
public void initialize(AlgorithmParameterSpec params, SecureRandom random)
throws InvalidAlgorithmParameterException {
if (params instanceof RSAKeyGenParameterSpec == false) {
throw new InvalidAlgorithmParameterException
("Params must be instance of RSAKeyGenParameterSpec");
}
RSAKeyGenParameterSpec rsaSpec = (RSAKeyGenParameterSpec)params;
int tmpKeySize = rsaSpec.getKeysize();
BigInteger tmpPublicExponent = rsaSpec.getPublicExponent();
if (tmpPublicExponent == null) {
tmpPublicExponent = RSAKeyGenParameterSpec.F4;
} else {
if (tmpPublicExponent.compareTo(RSAKeyGenParameterSpec.F0) < 0) {
throw new InvalidAlgorithmParameterException
("Public exponent must be 3 or larger");
}
if (tmpPublicExponent.bitLength() > tmpKeySize) {
throw new InvalidAlgorithmParameterException
("Public exponent must be smaller than key size");
}
}
// do not allow unreasonably large key sizes, probably user error
try {
RSAKeyFactory.checkKeyLengths(tmpKeySize, tmpPublicExponent,
512, 64 * 1024);
} catch (InvalidKeyException e) {
throw new InvalidAlgorithmParameterException(
"Invalid key sizes", e);
}
this.keySize = tmpKeySize;
this.publicExponent = tmpPublicExponent;
this.random = random;
}
private InputStream getCypherStream(InputStream in, byte[] key, byte[] iv) throws Exception {
Cipher cipher;
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
Key cipherKey = new SecretKeySpec(key, "AES");
AlgorithmParameterSpec cipherIV = new IvParameterSpec(iv);
cipher.init(Cipher.DECRYPT_MODE, cipherKey, cipherIV);
return new CipherInputStream(in, cipher);
}
/**
* getDigestAlgorithm() method testing.
*/
public void testGetDigestAlgorithm() {
String mdName = "SHA-1";
String mgfName = "MGF1";
AlgorithmParameterSpec mgfSpec = MGF1ParameterSpec.SHA1;
PSource pSrc = PSource.PSpecified.DEFAULT;
OAEPParameterSpec ps = new OAEPParameterSpec(mdName, mgfName,
mgfSpec, pSrc);
assertTrue("The returned value does not equal to the "
+ "value specified in the constructor.",
ps.getDigestAlgorithm().equals(mdName));
}
public TransportCipher createTransportCipher(String algorithm, int mode, SecretKeySpec key_spec, AlgorithmParameterSpec params) throws TransportException {
try {
controller.networkmanager.TransportCipher cipher = new controller.networkmanager.TransportCipher(algorithm, mode, key_spec, params);
return new TransportCipherImpl(cipher);
}
catch (Exception e) {
throw new TransportException(e);
}
}
protected void engineInit(AlgorithmParameterSpec paramSpec)
throws InvalidParameterSpecException
{
if (!(paramSpec instanceof PBEParameterSpec)) {
throw new InvalidParameterSpecException
("Inappropriate parameter specification");
}
this.salt = ((PBEParameterSpec)paramSpec).getSalt().clone();
this.iCount = ((PBEParameterSpec)paramSpec).getIterationCount();
this.cipherParam = ((PBEParameterSpec)paramSpec).getParameterSpec();
}
/**
* @inheritDoc
*/
protected void engineSetParameter(AlgorithmParameterSpec params)
throws XMLSignatureException {
try {
this.signatureAlgorithm.setParameter(params);
} catch (InvalidAlgorithmParameterException ex) {
throw new XMLSignatureException("empty", ex);
}
}
@Override
public int hashCode() {
int result = 17;
result = 31 * result + getAlgorithm().hashCode();
AlgorithmParameterSpec spec = getParameterSpec();
if (spec != null) {
result = 31 * result + spec.hashCode();
}
return result;
}
@Override
public void initialize(AlgorithmParameterSpec params, SecureRandom random)
throws InvalidAlgorithmParameterException {
ECParameterSpec ecSpec = null;
if (params instanceof ECParameterSpec) {
ECParameterSpec ecParams = (ECParameterSpec) params;
ecSpec = ECUtil.getECParameterSpec(null, ecParams);
if (ecSpec == null) {
throw new InvalidAlgorithmParameterException(
"Unsupported curve: " + params);
}
} else if (params instanceof ECGenParameterSpec) {
String name = ((ECGenParameterSpec) params).getName();
ecSpec = ECUtil.getECParameterSpec(null, name);
if (ecSpec == null) {
throw new InvalidAlgorithmParameterException(
"Unknown curve name: " + name);
}
} else {
throw new InvalidAlgorithmParameterException(
"ECParameterSpec or ECGenParameterSpec required for EC");
}
// Not all known curves are supported by the native implementation
ensureCurveIsSupported(ecSpec);
this.params = ecSpec;
this.keySize = ecSpec.getCurve().getField().getFieldSize();
this.random = random;
}
protected void engineInit(
AlgorithmParameterSpec genParamSpec,
SecureRandom random)
throws InvalidAlgorithmParameterException
{
throw new InvalidAlgorithmParameterException("No supported AlgorithmParameterSpec for DES parameter generation.");
}
@Override
public void initVerify(Signature s, PublicKey publicKey,
AlgorithmParameterSpec params)
throws InvalidKeyException,
InvalidAlgorithmParameterException {
s.initVerify(publicKey, params);
}
GcmReadCipher(Authenticator authenticator,
ProtocolVersion protocolVersion,
SSLCipher sslCipher, String algorithm,
Key key, AlgorithmParameterSpec params,
SecureRandom random) throws GeneralSecurityException {
super(authenticator, protocolVersion);
this.cipher = Cipher.getInstance(algorithm);
this.tagSize = sslCipher.tagSize;
this.key = key;
this.fixedIv = ((IvParameterSpec)params).getIV();
this.recordIvSize = sslCipher.ivSize - sslCipher.fixedIvSize;
this.random = random;
// DON'T initialize the cipher for AEAD!
}
/**
* Creates a <code>DOMDigestMethod</code>.
*
* @param params the algorithm-specific params (may be <code>null</code>)
* @throws InvalidAlgorithmParameterException if the parameters are not
* appropriate for this digest method
*/
DOMDigestMethod(AlgorithmParameterSpec params)
throws InvalidAlgorithmParameterException
{
if (params != null && !(params instanceof DigestMethodParameterSpec)) {
throw new InvalidAlgorithmParameterException
("params must be of type DigestMethodParameterSpec");
}
checkParams((DigestMethodParameterSpec)params);
this.params = (DigestMethodParameterSpec)params;
}
/**
* @inheritDoc
*/
protected void engineSetParameter(AlgorithmParameterSpec params)
throws XMLSignatureException {
try {
this.signatureAlgorithm.setParameter(params);
} catch (InvalidAlgorithmParameterException ex) {
throw new XMLSignatureException("empty", ex);
}
}
protected void engineInit(AlgorithmParameterSpec paramSpec)
throws InvalidParameterSpecException {
if (!(paramSpec instanceof OAEPParameterSpec)) {
throw new InvalidParameterSpecException
("Inappropriate parameter specification");
}
OAEPParameterSpec spec = (OAEPParameterSpec) paramSpec;
mdName = spec.getDigestAlgorithm();
String mgfName = spec.getMGFAlgorithm();
if (!mgfName.equalsIgnoreCase("MGF1")) {
throw new InvalidParameterSpecException("Unsupported mgf " +
mgfName + "; MGF1 only");
}
AlgorithmParameterSpec mgfSpec = spec.getMGFParameters();
if (!(mgfSpec instanceof MGF1ParameterSpec)) {
throw new InvalidParameterSpecException("Inappropriate mgf " +
"parameters; non-null MGF1ParameterSpec only");
}
this.mgfSpec = (MGF1ParameterSpec) mgfSpec;
PSource pSrc = spec.getPSource();
if (pSrc.getAlgorithm().equals("PSpecified")) {
p = ((PSource.PSpecified) pSrc).getValue();
} else {
throw new InvalidParameterSpecException("Unsupported pSource " +
pSrc.getAlgorithm() + "; PSpecified only");
}
}
protected void engineInit(AlgorithmParameterSpec paramSpec)
throws InvalidParameterSpecException
{
if (!(paramSpec instanceof PBEParameterSpec)) {
throw new InvalidParameterSpecException
("Inappropriate parameter specification");
}
this.salt = ((PBEParameterSpec)paramSpec).getSalt().clone();
this.iCount = ((PBEParameterSpec)paramSpec).getIterationCount();
this.cipherParam = ((PBEParameterSpec)paramSpec).getParameterSpec();
}
protected void engineInit(
AlgorithmParameterSpec paramSpec)
throws InvalidParameterSpecException
{
if (!(paramSpec instanceof PBEParameterSpec))
{
throw new InvalidParameterSpecException("PBEParameterSpec required to initialise a PBKDF2 PBE parameters algorithm parameters object");
}
PBEParameterSpec pbeSpec = (PBEParameterSpec)paramSpec;
this.params = new PBKDF2Params(pbeSpec.getSalt(),
pbeSpec.getIterationCount());
}
public void marshalParams(XMLStructure parent, XMLCryptoContext context)
throws MarshalException
{
super.marshalParams(parent, context);
AlgorithmParameterSpec spec = getParameterSpec();
if (spec == null) {
return;
}
String prefix = DOMUtils.getNSPrefix(context,
CanonicalizationMethod.EXCLUSIVE);
Element eElem = DOMUtils.createElement(ownerDoc,
"InclusiveNamespaces",
CanonicalizationMethod.EXCLUSIVE,
prefix);
if (prefix == null || prefix.length() == 0) {
eElem.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns",
CanonicalizationMethod.EXCLUSIVE);
} else {
eElem.setAttributeNS("http://www.w3.org/2000/xmlns/",
"xmlns:" + prefix,
CanonicalizationMethod.EXCLUSIVE);
}
ExcC14NParameterSpec params = (ExcC14NParameterSpec)spec;
StringBuffer prefixListAttr = new StringBuffer("");
@SuppressWarnings("unchecked")
List<String> prefixList = params.getPrefixList();
for (int i = 0, size = prefixList.size(); i < size; i++) {
prefixListAttr.append(prefixList.get(i));
if (i < size - 1) {
prefixListAttr.append(" ");
}
}
DOMUtils.setAttribute(eElem, "PrefixList", prefixListAttr.toString());
this.inclusiveNamespaces = prefixListAttr.toString();
transformElem.appendChild(eElem);
}
private void initCiphers(String algo, SecretKey key,
AlgorithmParameterSpec aps) throws NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException,
InvalidAlgorithmParameterException {
Provider provider = Security.getProvider("SunJCE");
if (provider == null) {
throw new RuntimeException("SunJCE provider does not exist.");
}
Cipher ci1 = Cipher.getInstance(algo, provider);
ci1.init(Cipher.ENCRYPT_MODE, key, aps);
pair[0] = ci1;
Cipher ci2 = Cipher.getInstance(algo, provider);
ci2.init(Cipher.DECRYPT_MODE, key, aps);
pair[1] = ci2;
}
@Override
public int hashCode() {
int result = 17;
result = 31 * result + getAlgorithm().hashCode();
AlgorithmParameterSpec spec = getParameterSpec();
if (spec != null) {
result = 31 * result + spec.hashCode();
}
return result;
}
protected void engineInit(Key key, AlgorithmParameterSpec params,
SecureRandom random) throws InvalidKeyException,
InvalidAlgorithmParameterException {
if (params != null) {
throw new InvalidAlgorithmParameterException
("Parameters not supported");
}
engineInit(key, random);
}
protected void engineInit(AlgorithmParameterSpec paramSpec)
throws InvalidParameterSpecException {
core.init(paramSpec);
}
@Override
native KeyPair generate(AlgorithmParameterSpec params, SecureRandom random);