下面列出了java.security.CryptoPrimitive#java.security.AlgorithmParameters 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void runGCMWithSameArray(int mode, byte[] array, int txtOffset,
int length, AlgorithmParameters params) throws Exception {
// first, generate cipher text at an allocated buffer
Cipher cipher = createCipher(mode, params);
cipher.updateAAD(array, 0, AADLength);
byte[] outputText = cipher.doFinal(array, txtOffset, length);
// new cipher for encrypt operation
Cipher anotherCipher = createCipher(mode, params);
anotherCipher.updateAAD(array, 0, AADLength);
// next, generate cipher text again at the same buffer of plain text
int off = anotherCipher.update(array, txtOffset, length,
array, txtOffset);
anotherCipher.doFinal(array, txtOffset + off);
// check if two results are equal or not
if (!isEqual(array, txtOffset, outputText, 0,
outputText.length)) {
throw new RuntimeException(
"Two results are not equal, mode:" + mode);
}
}
private Cipher createCipher(int mode, AlgorithmParameters params)
throws Exception {
Cipher cipher = Cipher.getInstance(transformation, provider);
if (Cipher.ENCRYPT_MODE == mode) {
// initiate it with the saved parameters
if (params != null) {
cipher.init(Cipher.ENCRYPT_MODE, key, params);
} else {
// intiate the cipher and save parameters
cipher.init(Cipher.ENCRYPT_MODE, key);
}
} else if (cipher != null) {
cipher.init(Cipher.DECRYPT_MODE, key, params);
} else {
throw new RuntimeException("Can't create cipher");
}
return cipher;
}
private static boolean isAvailableCurve(int curveId) {
String oid = idToOidMap.get(curveId);
if (oid != null) {
AlgorithmParameters params = null;
try {
params = JsseJce.getAlgorithmParameters("EC");
params.init(new ECGenParameterSpec(oid));
} catch (Exception e) {
return false;
}
// cache the parameters
idToParams.put(curveId, params);
return true;
}
return false;
}
private static boolean isAvailableCurve(int curveId) {
String oid = idToOidMap.get(curveId);
if (oid != null) {
AlgorithmParameters params = null;
try {
params = JsseJce.getAlgorithmParameters("EC");
params.init(new ECGenParameterSpec(oid));
} catch (Exception e) {
return false;
}
// cache the parameters
idToParams.put(curveId, params);
return true;
}
return false;
}
/**
* Returns the DSA parameters associated with this key, or null if the
* parameters could not be parsed.
*/
public DSAParams getParams() {
try {
if (algid instanceof DSAParams) {
return (DSAParams)algid;
} else {
DSAParameterSpec paramSpec;
AlgorithmParameters algParams = algid.getParameters();
if (algParams == null) {
return null;
}
paramSpec = algParams.getParameterSpec(DSAParameterSpec.class);
return (DSAParams)paramSpec;
}
} catch (InvalidParameterSpecException e) {
return null;
}
}
private void combination_9(List<byte[]> results, int mode, byte[] AAD,
byte[] plainText, AlgorithmParameters params) throws Exception {
// prepare ByteBuffer to test
ByteBuffer buf = ByteBuffer.allocate(AAD.length);
buf.put(AAD);
buf.position(0);
buf.limit(AAD.length);
// Get Cipher object and do the combination
Cipher c = createCipher(mode, params);
c.updateAAD(buf);
byte[] part91 = c.update(plainText, 0, plainText.length);
int part91_length = part91 == null ? 0 : part91.length;
byte[] part92 = c.doFinal();
byte[] outputText9 = new byte[part91_length + part92.length];
// form result of the combination
if (part91 != null) {
System.arraycopy(part91, 0, outputText9, 0, part91_length);
}
System.arraycopy(part92, 0, outputText9, part91_length, part92.length);
results.add(outputText9);
}
private void runGCMWithSameArray(int mode, byte[] array, int txtOffset,
int length, AlgorithmParameters params) throws Exception {
// first, generate cipher text at an allocated buffer
Cipher cipher = createCipher(mode, params);
cipher.updateAAD(array, 0, AADLength);
byte[] outputText = cipher.doFinal(array, txtOffset, length);
// new cipher for encrypt operation
Cipher anotherCipher = createCipher(mode, params);
anotherCipher.updateAAD(array, 0, AADLength);
// next, generate cipher text again at the same buffer of plain text
int off = anotherCipher.update(array, txtOffset, length,
array, txtOffset);
anotherCipher.doFinal(array, txtOffset + off);
// check if two results are equal or not
if (!isEqual(array, txtOffset, outputText, 0,
outputText.length)) {
throw new RuntimeException(
"Two results are not equal, mode:" + mode);
}
}
/**
* Returns the DSA parameters associated with this key, or null if the
* parameters could not be parsed.
*/
public DSAParams getParams() {
try {
if (algid instanceof DSAParams) {
return (DSAParams)algid;
} else {
DSAParameterSpec paramSpec;
AlgorithmParameters algParams = algid.getParameters();
if (algParams == null) {
return null;
}
paramSpec = algParams.getParameterSpec(DSAParameterSpec.class);
return (DSAParams)paramSpec;
}
} catch (InvalidParameterSpecException e) {
return null;
}
}
/**
* Method to decrypt the data
*
* @param input Data to be decrypted
* @return Decrypted data (returns <code>null</code> if password is invalid)
* @throws OpenStegoException
*/
public byte[] decrypt(byte[] input) throws OpenStegoException {
try {
// First byte is algo params length
byte paramLen = input[0];
// Copy algorithm params
byte[] algoParamData = new byte[paramLen];
System.arraycopy(input, 1, algoParamData, 0, paramLen);
// Copy encrypted message
byte[] msg = new byte[input.length - paramLen - 1];
System.arraycopy(input, paramLen + 1, msg, 0, msg.length);
AlgorithmParameters algoParams = AlgorithmParameters.getInstance(this.secretKey.getAlgorithm());
algoParams.init(algoParamData);
Cipher decryptCipher = Cipher.getInstance(this.secretKey.getAlgorithm());
decryptCipher.init(Cipher.DECRYPT_MODE, this.secretKey, algoParams);
return decryptCipher.doFinal(msg);
} catch (BadPaddingException bpEx) {
throw new OpenStegoException(bpEx, OpenStego.NAMESPACE, OpenStegoException.INVALID_PASSWORD);
} catch (Exception ex) {
throw new OpenStegoException(ex);
}
}
public void engineInit(
int opmode,
Key key,
AlgorithmParameters params,
SecureRandom random)
throws InvalidKeyException, InvalidAlgorithmParameterException
{
AlgorithmParameterSpec paramSpec = null;
if (params != null)
{
try
{
paramSpec = params.getParameterSpec(IESParameterSpec.class);
}
catch (Exception e)
{
throw new InvalidAlgorithmParameterException("cannot recognise parameters: " + e.toString());
}
}
engineParam = params;
engineInit(opmode, key, paramSpec, random);
}
public boolean permits(String algorithm, AlgorithmParameters aps) {
List<Constraint> list = getConstraints(algorithm);
if (list == null) {
return true;
}
for (Constraint constraint : list) {
if (!constraint.permits(aps)) {
if (debug != null) {
debug.println("Constraints: failed algorithm " +
"parameters constraint check " + aps);
}
return false;
}
}
return true;
}
private AlgorithmParameters getAlgorithmParameters(String algorithm)
throws IOException
{
AlgorithmParameters algParams = null;
// create PBE parameters from salt and iteration count
PBEParameterSpec paramSpec =
new PBEParameterSpec(getSalt(), iterationCount);
try {
algParams = AlgorithmParameters.getInstance(algorithm);
algParams.init(paramSpec);
} catch (Exception e) {
throw new IOException("getAlgorithmParameters failed: " +
e.getMessage(), e);
}
return algParams;
}
protected AlgorithmParameters engineGetParameters()
{
if (engineParam == null)
{
if (engineParams != null)
{
String name = "IES";
try
{
engineParam = helper.createAlgorithmParameters(name);
engineParam.init(engineParams);
}
catch (Exception e)
{
throw new RuntimeException(e.toString());
}
}
}
return engineParam;
}
private Cipher createCipher(int mode, AlgorithmParameters params)
throws Exception {
Cipher cipher = Cipher.getInstance(transformation, provider);
if (Cipher.ENCRYPT_MODE == mode) {
// initiate it with the saved parameters
if (params != null) {
cipher.init(Cipher.ENCRYPT_MODE, key, params);
} else {
// intiate the cipher and save parameters
cipher.init(Cipher.ENCRYPT_MODE, key);
}
} else if (cipher != null) {
cipher.init(Cipher.DECRYPT_MODE, key, params);
} else {
throw new RuntimeException("Can't create cipher");
}
return cipher;
}
/**
* {@inheritDoc}
*/
@Override
public InputStream decrypt(String keyAlias, AlgorithmParameters params, InputStream input)
{
Cipher cipher = getCipher(keyAlias, params, Cipher.DECRYPT_MODE);
if (cipher == null)
{
return input;
}
try
{
return new CipherInputStream(input, cipher);
}
catch (Throwable e)
{
throw new AlfrescoRuntimeException("Decryption failed for key alias: " + keyAlias, e);
}
}
public AlgorithmParameters engineGetParameters()
{
if (engineParam == null && engineSpec != null)
{
try
{
engineParam = helper.createAlgorithmParameters("IES");
engineParam.init(engineSpec);
}
catch (Exception e)
{
throw new RuntimeException(e.toString());
}
}
return engineParam;
}
private void combination_12(List<byte[]> results, int mode, byte[] AAD,
byte[] plainText, AlgorithmParameters params) throws Exception {
// prepare ByteBuffer to test
ByteBuffer buf = ByteBuffer.allocate(AAD.length);
buf.put(AAD);
buf.position(0);
buf.limit(AAD.length);
Cipher ci = createCipher(mode, params);
ci.updateAAD(buf);
// prepare an empty ByteBuffer
ByteBuffer emptyBuf = ByteBuffer.allocate(0);
emptyBuf.put(new byte[0]);
ci.updateAAD(emptyBuf);
byte[] part12_1 = new byte[ci.getOutputSize(plainText.length)];
int offset = plainText.length > ARRAY_OFFSET ? ARRAY_OFFSET : 0;
int len12 = ci.update(plainText, 0, plainText.length - offset,
part12_1, 0);
int rest12 = ci.doFinal(plainText, plainText.length - offset, offset,
part12_1, len12);
byte[] outputText12 = new byte[len12 + rest12];
System.arraycopy(part12_1, 0, outputText12, 0, outputText12.length);
results.add(outputText12);
}
/**
* Returns the DSA parameters associated with this key, or null if the
* parameters could not be parsed.
*/
public DSAParams getParams() {
try {
if (algid instanceof DSAParams) {
return (DSAParams)algid;
} else {
DSAParameterSpec paramSpec;
AlgorithmParameters algParams = algid.getParameters();
if (algParams == null) {
return null;
}
paramSpec = algParams.getParameterSpec(DSAParameterSpec.class);
return (DSAParams)paramSpec;
}
} catch (InvalidParameterSpecException e) {
return null;
}
}
private void combination_6(List<byte[]> results, int mode, byte[] AAD,
byte[] plainText, AlgorithmParameters params) throws Exception {
Cipher c = createCipher(mode, params);
c.updateAAD(AAD, 0, AAD.length / 2);
c.updateAAD(AAD, AAD.length / 2, AAD.length - AAD.length / 2);
int t = 0;
int offset = 0;
if (plainText.length > ARRAY_OFFSET) {
t = plainText.length - ARRAY_OFFSET;
offset = ARRAY_OFFSET;
}
byte[] part61 = c.update(plainText, 0, t);
byte[] part62 = new byte[c.getOutputSize(plainText.length)];
int len = c.doFinal(plainText, t, offset, part62, 0);
int part61Length = part61 != null ? part61.length : 0;
byte[] outputText6 = new byte[part61Length + len];
if (part61 != null) {
System.arraycopy(part61, 0, outputText6, 0, part61Length);
}
System.arraycopy(part62, 0, outputText6, part61Length, len);
results.add(outputText6);
}
private void doTestWithSeparateArrays(int offset,
AlgorithmParameters params) throws Exception {
// prepare buffers to test
Cipher c = createCipher(Cipher.ENCRYPT_MODE, params);
int outputLength = c.getOutputSize(textLength);
int outputBufSize = outputLength + offset * 2;
byte[] inputText = Helper.generateBytes(outputBufSize);
byte[] AAD = Helper.generateBytes(AADLength);
// do the test
runGCMWithSeparateArray(Cipher.ENCRYPT_MODE, AAD, inputText, offset * 2,
textLength, offset, params);
int tagLength = c.getParameters()
.getParameterSpec(GCMParameterSpec.class).getTLen() / 8;
runGCMWithSeparateArray(Cipher.DECRYPT_MODE, AAD, inputText, offset,
textLength + tagLength, offset, params);
}
/**
* Decode cipher algorithm parameters from the HTTP method
*
* @param req
* @return decoded algorithm parameters
* @throws IOException
*/
protected AlgorithmParameters decodeAlgorithmParameters(HttpServletRequest req) throws IOException
{
String header = req.getHeader(HEADER_ALGORITHM_PARAMETERS);
if(header != null)
{
byte[] algorithmParams = Base64.decode(header);
AlgorithmParameters algorithmParameters = encryptor.decodeAlgorithmParameters(algorithmParams);
return algorithmParameters;
}
else
{
return null;
}
}
@Override
public Cipher getCipher(String keyAlias, AlgorithmParameters params, int mode)
{
Cipher cipher = null;
// Get the encryption key
Key key = keyProvider.getKey(keyAlias);
if(key == null)
{
// No encryption possible
return null;
}
try
{
if(cacheCiphers)
{
cipher = getCachedCipher(keyAlias, mode, params, key);
}
else
{
cipher = createCipher(mode, cipherAlgorithm, cipherProvider, key, params);
}
}
catch (Exception e)
{
throw new AlfrescoRuntimeException(
"Failed to construct cipher: alias=" + keyAlias + "; mode=" + mode,
e);
}
return cipher;
}
public static void main(String[] args) throws Exception {
Provider provider = Security.getProvider("SunJCE");
if (provider == null) {
throw new RuntimeException("SunJCE provider not exist");
}
// generate no-padding cipher with secret key
Cipher c = Cipher.getInstance("DES/CBC/NoPadding", provider);
KeyGenerator kgen = KeyGenerator.getInstance("DES", provider);
SecretKey skey = kgen.generateKey();
// this is the improperly padded plaintext
c.init(Cipher.ENCRYPT_MODE, skey);
// encrypt plaintext
byte[] cipher = c.doFinal(PLAIN_TEXT);
AlgorithmParameters params = c.getParameters();
// generate cipher that enforces PKCS5 padding
c = Cipher.getInstance("DES/CBC/PKCS5Padding", provider);
c.init(Cipher.DECRYPT_MODE, skey, params);
try {
c.doFinal(cipher);
throw new RuntimeException(
"ERROR: Expected BadPaddingException not thrown");
} catch (BadPaddingException expected) {
out.println("Expected BadPaddingException thrown");
}
}
@Override
public boolean permits(Set<CryptoPrimitive> primitives,
String algorithm, AlgorithmParameters parameters) {
if (algorithm == null || algorithm.length() == 0) {
throw new IllegalArgumentException(
"No algorithm name specified");
}
if (primitives == null || primitives.isEmpty()) {
throw new IllegalArgumentException(
"No cryptographic primitive specified");
}
if (supportedAlgorithms == null ||
supportedAlgorithms.length == 0) {
return false;
}
// trim the MGF part: <digest>with<encryption>and<mgf>
int position = algorithm.indexOf("and");
if (position > 0) {
algorithm = algorithm.substring(0, position);
}
for (String supportedAlgorithm : supportedAlgorithms) {
if (algorithm.equalsIgnoreCase(supportedAlgorithm)) {
return true;
}
}
return false;
}
/**
* Check the signature algorithm with the specified public key.
*
* @param key the public key to verify the CRL signature
* @param algorithmId signature algorithm Algorithm ID
* @param variant is the Validator variants of the operation. A null value
* passed will set it to Validator.GENERIC.
*/
static void check(PublicKey key, AlgorithmId algorithmId, String variant)
throws CertPathValidatorException {
String sigAlgName = algorithmId.getName();
AlgorithmParameters sigAlgParams = algorithmId.getParameters();
certPathDefaultConstraints.permits(new ConstraintsParameters(
sigAlgName, sigAlgParams, key, variant));
}
private void combination_4(List<byte[]> results, int mode, byte[] AAD,
byte[] plainText, AlgorithmParameters params) throws Exception {
Cipher ci = createCipher(mode, params);
ci.updateAAD(AAD);
byte[] part41 = new byte[ci.getOutputSize(plainText.length)];
int offset = plainText.length > ARRAY_OFFSET ? ARRAY_OFFSET : 0;
int len = ci.update(plainText, 0, plainText.length - offset, part41, 0);
int rest4 = ci.doFinal(plainText, plainText.length - offset, offset,
part41, len);
byte[] outputText4 = new byte[len + rest4];
System.arraycopy(part41, 0, outputText4, 0, outputText4.length);
results.add(outputText4);
}
@Override
public boolean permits(Set<CryptoPrimitive> primitives,
String algorithm, AlgorithmParameters parameters) {
boolean permitted = true;
if (peerAlgConstraints != null) {
permitted = peerAlgConstraints.permits(
primitives, algorithm, parameters);
}
if (permitted && userAlgConstraints != null) {
permitted = userAlgConstraints.permits(
primitives, algorithm, parameters);
}
if (permitted) {
permitted = tlsDisabledAlgConstraints.permits(
primitives, algorithm, parameters);
}
if (permitted && enabledX509DisabledAlgConstraints) {
permitted = x509DisabledAlgConstraints.permits(
primitives, algorithm, parameters);
}
return permitted;
}
private static byte[] testParams(AlgorithmParameters rc2Params,
RC2ParameterSpec rc2Spec) throws Exception {
// test getParameterSpec returns object equal to input
rc2Params.init(rc2Spec);
RC2ParameterSpec rc2OtherSpec = (RC2ParameterSpec)
rc2Params.getParameterSpec(RC2ParameterSpec.class);
if (!rc2Spec.equals(rc2OtherSpec)) {
throw new Exception("AlgorithmParameterSpecs should be equal");
}
// test RC2ParameterSpec with RC2 Cipher
Cipher rc2Cipher = Cipher.getInstance("RC2/CBC/PKCS5PADDING", "SunJCE");
rc2Cipher.init(Cipher.ENCRYPT_MODE,
new SecretKeySpec("secret".getBytes("ASCII"), "RC2"), rc2Spec);
// get IV
byte[] iv = rc2Cipher.getIV();
if (!Arrays.equals(iv, rc2Spec.getIV())) {
throw new Exception("ivs should be equal");
}
// test encoding and decoding
byte[] encoded = rc2Params.getEncoded();
AlgorithmParameters params = AlgorithmParameters.getInstance("RC2");
params.init(encoded);
// test RC2 AlgorithmParameters with RC2 Cipher
rc2Cipher.init(Cipher.ENCRYPT_MODE,
new SecretKeySpec("secret".getBytes("ASCII"), "RC2"), params);
// get IV
iv = rc2Cipher.getIV();
if (!Arrays.equals(iv, rc2Spec.getIV())) {
throw new Exception("ivs should be equal");
}
return encoded;
}
@Override
final public boolean permits(Set<CryptoPrimitive> primitives,
String algorithm, Key key, AlgorithmParameters parameters) {
if (algorithm == null || algorithm.length() == 0) {
throw new IllegalArgumentException("No algorithm name specified");
}
return checkConstraints(primitives, algorithm, key, parameters);
}
private ASN1Primitive createDERForRecipient(byte[] in, X509Certificate cert)
throws IOException,
GeneralSecurityException
{
String s = "1.2.840.113549.3.2";
AlgorithmParameterGenerator algorithmparametergenerator = AlgorithmParameterGenerator.getInstance(s);
AlgorithmParameters algorithmparameters = algorithmparametergenerator.generateParameters();
ByteArrayInputStream bytearrayinputstream = new ByteArrayInputStream(algorithmparameters.getEncoded("ASN.1"));
ASN1InputStream asn1inputstream = new ASN1InputStream(bytearrayinputstream);
ASN1Primitive derobject = asn1inputstream.readObject();
KeyGenerator keygenerator = KeyGenerator.getInstance(s);
keygenerator.init(128);
SecretKey secretkey = keygenerator.generateKey();
Cipher cipher = Cipher.getInstance(s);
cipher.init(1, secretkey, algorithmparameters);
byte[] abyte1 = cipher.doFinal(in);
DEROctetString deroctetstring = new DEROctetString(abyte1);
KeyTransRecipientInfo keytransrecipientinfo = computeRecipientInfo(cert, secretkey.getEncoded());
DERSet derset = new DERSet(new RecipientInfo(keytransrecipientinfo));
AlgorithmIdentifier algorithmidentifier = new AlgorithmIdentifier(new ASN1ObjectIdentifier(s), derobject);
EncryptedContentInfo encryptedcontentinfo =
new EncryptedContentInfo(PKCSObjectIdentifiers.data, algorithmidentifier, deroctetstring);
EnvelopedData env = new EnvelopedData(null, derset, encryptedcontentinfo, (org.bouncycastle.asn1.ASN1Set) null);
ContentInfo contentinfo =
new ContentInfo(PKCSObjectIdentifiers.envelopedData, env);
return contentinfo.toASN1Primitive();
}