项目:Cable-Android
文件:DecryptingPartInputStream.java
public static InputStream createFor(MasterSecret masterSecret,File file)
throws IOException
{
try {
if (file.length() <= IV_LENGTH + MAC_LENGTH) {
throw new IOException("File too short");
}
verifyMac(masterSecret,file);
FileInputStream fileStream = new FileInputStream(file);
byte[] ivBytes = new byte[IV_LENGTH];
readFully(fileStream,ivBytes);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec iv = new IvParameterSpec(ivBytes);
cipher.init(Cipher.DECRYPT_MODE,masterSecret.getEncryptionKey(),iv);
return new CipherInputStreamWrapper(new LimitedInputStream(fileStream,file.length() - MAC_LENGTH - IV_LENGTH),cipher);
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException e) {
throw new AssertionError(e);
}
}
public Transform newTransform(String algorithm,TransformParameterSpec params) throws NoSuchAlgorithmException,InvalidAlgorithmParameterException {
TransformService spi;
if (getProvider() == null) {
spi = TransformService.getInstance(algorithm,"DOM");
} else {
try {
spi = TransformService.getInstance(algorithm,"DOM",getProvider());
} catch (NoSuchAlgorithmException nSAE) {
spi = TransformService.getInstance(algorithm,"DOM");
}
}
spi.init(params);
return new DOMTransform(spi);
}
@Override
protected void engineInit(
AlgorithmParameterSpec genParamSpec,SecureRandom random)
throws InvalidAlgorithmParameterException
{
if (!(genParamSpec instanceof DHGenParameterSpec))
{
throw new InvalidAlgorithmParameterException("DH parameter generator requires a DHGenParameterSpec for initialisation");
}
DHGenParameterSpec spec = (DHGenParameterSpec)genParamSpec;
this.strength = spec.getPrimeSize();
this.l = spec.getExponentSize();
this.random = random;
}
/**
* 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
*/
@Override
protected void engineInit(AlgorithmParameterSpec genParamSpec,SecureRandom random) throws InvalidAlgorithmParameterException {
if (!(genParamSpec instanceof DSAGenParameterSpec)) {
throw new InvalidAlgorithmParameterException("Invalid parameter");
}
DSAGenParameterSpec dsaGenParams = (DSAGenParameterSpec)genParamSpec;
// directly initialize using the already validated values
this.valueL = dsaGenParams.getPrimePLength();
this.valueN = dsaGenParams.getSubprimeQLength();
this.seedLen = dsaGenParams.getSeedLength();
this.random = random;
}
项目:DMS
文件:AES256.java
public static String encrypt(String str) {
if (str == null) return null;
Cipher cipher;
try {
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE,keySpec,new IvParameterSpec(ips.getBytes("UTF-8")));
byte[] encrypted = cipher.doFinal(str.getBytes("UTF-8"));
String Str = new String(Base64.encodeBase64(encrypted));
return Str;
} catch (NoSuchAlgorithmException | NoSuchPaddingException
| InvalidKeyException | InvalidAlgorithmParameterException
| IllegalBlockSizeException | BadPaddingException
| UnsupportedEncodingException e) {
e.printstacktrace();
}
return null;
}
项目:mapbook-android
文件:CredentialCryptographer.java
/**
* Create a new key in the Keystore
*/
private void createNewKey(){
try {
final KeyStore keyStore = KeyStore.getInstance(AndroidKeyStore);
keyStore.load(null);
final KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES,AndroidKeyStore);
// Build one key to be used for encrypting and decrypting the file
keyGenerator.init(
new KeyGenParameterSpec.Builder(ALIAS,KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.build());
keyGenerator.generateKey();
Log.i(TAG,"Key created in Keystore");
}catch (KeyStoreException | InvalidAlgorithmParameterException | NoSuchProviderException | NoSuchAlgorithmException | CertificateException | IOException kS){
Log.e(TAG,kS.getMessage());
}
}
项目:spring-data-mongodb-encrypt
文件:CryptVault.java
public byte[] encrypt(int version,byte[] data) {
CryptVersion cryptVersion = cryptVersion(version);
try {
int cryptedLength = cryptVersion.encryptedLength.apply(data.length);
byte[] result = new byte[cryptedLength + cryptVersion.saltLength + 1];
result[0] = toSignedByte(version);
byte[] random = urandomBytes(cryptVersion.saltLength);
IvParameterSpec iv_spec = new IvParameterSpec(random);
System.arraycopy(random,result,1,cryptVersion.saltLength);
Cipher cipher = cipher(cryptVersion.cipher);
cipher.init(Cipher.ENCRYPT_MODE,cryptVersion.key,iv_spec);
int len = cipher.doFinal(data,data.length,cryptVersion.saltLength + 1);
if (len < cryptedLength) LOG.info("len was " + len + " instead of " + cryptedLength);
return result;
} catch (ShortBufferException | IllegalBlockSizeException | BadPaddingException | InvalidAlgorithmParameterException | InvalidKeyException e) {
throw new RuntimeException("JCE exception caught while encrypting with version " + version,e);
}
}
项目:Daejeon-People
文件:AES256.java
public static String decrypt(String str) {
if (str == null) return null;
Cipher cipher;
try {
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE,new IvParameterSpec(ips.getBytes("UTF-8")));
byte[] byteStr = Base64.decodeBase64(str.getBytes());
return new String(cipher.doFinal(byteStr),"UTF-8");
} catch (NoSuchAlgorithmException | NoSuchPaddingException
| InvalidKeyException | InvalidAlgorithmParameterException
| IllegalBlockSizeException | BadPaddingException
| UnsupportedEncodingException e) {
e.printstacktrace();
}
return null;
}
项目:openjdk-jdk10
文件:PKIX.java
ValidatorParams(PKIXParameters params)
throws InvalidAlgorithmParameterException
{
if (params instanceof PKIXExtendedParameters) {
timestamp = ((PKIXExtendedParameters) params).getTimestamp();
variant = ((PKIXExtendedParameters) params).getvariant();
}
this.anchors = params.getTrustAnchors();
// Make sure that none of the trust anchors include name constraints
// (not supported).
for (TrustAnchor anchor : this.anchors) {
if (anchor.getNameConstraints() != null) {
throw new InvalidAlgorithmParameterException
("name constraints in trust anchor not supported");
}
}
this.params = params;
}
项目:smartcontracts
文件:DSPTest.java
@BeforeClass(enabled = false)
public void registerUser() throws CipherException,InvalidAlgorithmParameterException,NoSuchAlgorithmException,NoSuchProviderException,IOException {
dsp = createNewMember(2,100)
.thenApply(papyrusMember -> {
allTransactionsminedAsync(asList(papyrusMember.refillTransaction,papyrusMember.mintTransaction));
return papyrusMember;
}).join();
dspRegistrar = createNewMember(2,papyrusMember.mintTransaction));
return papyrusMember;
}).join();
dao = loadDaoContract(dsp.transactionManager);
daoRegistrar = loadDaoContract(dspRegistrar.transactionManager);
token = asCf(dao.token()).thenApply(tokenAddress -> loadTokenContract(tokenAddress.toString(),dsp.transactionManager)).join();
tokenRegistrar = asCf(daoRegistrar.token())
.thenApply(tokenAddress -> loadTokenContract(tokenAddress.toString(),dspRegistrar.transactionManager)
).join();
dspRegistry = asCf(daoRegistrar.dspRegistry())
.thenApply(dspRegistryAddress -> loadDspRegistry(dspRegistryAddress.toString(),dsp.transactionManager))
.join();
initDepositContract();
}
项目:encryptedprefs
文件:Vault.java
@TargetApi(Build.VERSION_CODES.M)
public SecretKey getSymmetricKey(String alias)
throws NoSuchProviderException,IOException,CertificateException,KeyStoreException,UnrecoverableEntryException {
ESLog.v("%s=>getSymmetricKey(%s)",getClass().getSimpleName(),alias);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
KeyStore ks = KeyStore.getInstance(KEYSTORE_PROVIDER);
ks.load(null);
Key key = ks.getKey(alias,null);
if (key != null) {
ESLog.i("SecretKey found in KeyStore.");
return (SecretKey) key;
}
ESLog.w("SecretKey not found in KeyStore.");
return null;
}
UnsupportedOperationException unsupportedOperationException = new UnsupportedOperationException();
ESLog.wtf("Unsupported operation. This code should be called only from M onwards.",unsupportedOperationException.getCause());
throw unsupportedOperationException;
}
/**
* Sets the {@code Set} of most-trusted CAs.
* <p>
* Note that the {@code Set} is copied to protect against
* subsequent modifications.
*
* @param trustAnchors a {@code Set} of {@code TrustAnchor}s
* @throws InvalidAlgorithmParameterException if the specified
* {@code Set} is empty {@code (trustAnchors.isEmpty() == true)}
* @throws NullPointerException if the specified {@code Set} is
* {@code null}
* @throws ClassCastException if any of the elements in the set
* are not of type {@code java.security.cert.TrustAnchor}
*
* @see #getTrustAnchors
*/
public void setTrustAnchors(Set<TrustAnchor> trustAnchors)
throws InvalidAlgorithmParameterException
{
if (trustAnchors == null) {
throw new NullPointerException("the trustAnchors parameters must" +
" be non-null");
}
if (trustAnchors.isEmpty()) {
throw new InvalidAlgorithmParameterException("the trustAnchors " +
"parameter must be non-empty");
}
for (Iterator<TrustAnchor> i = trustAnchors.iterator(); i.hasNext(); ) {
if (!(i.next() instanceof TrustAnchor)) {
throw new ClassCastException("all elements of set must be "
+ "of type java.security.cert.TrustAnchor");
}
}
this.unmodTrustAnchors = Collections.unmodifiableSet
(new HashSet<>(trustAnchors));
}
private void checkParams(PKIXBuilderParameters params)
throws InvalidAlgorithmParameterException
{
CertSelector sel = targetCertConstraints();
if (!(sel instanceof X509CertSelector)) {
throw new InvalidAlgorithmParameterException("the "
+ "targetCertConstraints parameter must be an "
+ "X509CertSelector");
}
if (params instanceof SunCertPathBuilderParameters) {
buildForward =
((SunCertPathBuilderParameters)params).getBuildForward();
}
this.params = params;
this.targetSubject = getTargetSubject(
certStores(),(X509CertSelector)targetCertConstraints());
}
项目:smartcontracts
文件:AuditorTest.java
@BeforeClass(enabled = false)
public void registerUser() throws CipherException,IOException {
auditor = createNewMember(2,papyrusMember.mintTransaction));
return papyrusMember;
}).join();
auditorRegistrar = createNewMember(2,papyrusMember.mintTransaction));
return papyrusMember;
}).join();
dao = loadDaoContract(auditor.transactionManager);
daoRegistrar = loadDaoContract(auditorRegistrar.transactionManager);
token = asCf(dao.token()).thenApply(tokenAddress -> loadTokenContract(tokenAddress.toString(),auditor.transactionManager)).join();
tokenRegistrar = asCf(daoRegistrar.token())
.thenApply(tokenAddress -> loadTokenContract(tokenAddress.toString(),auditorRegistrar.transactionManager)
).join();
auditorRegistry = asCf(daoRegistrar.auditorRegistry())
.thenApply(auditorRegistryAddress -> loadAuditorRegistry(auditorRegistryAddress.toString(),auditor.transactionManager))
.join();
initDepositContract();
}
项目:CrashCoin
文件:ClientApplication.java
private void actionMenuNotRegistered(final int choice) throws ClassNotFoundException,FileNotFoundException,InvalidKeyException,InvalidKeySpecException,IllegalBlockSizeException,BadPaddingException,InvalidParameterSpecException {
switch (choice) {
case 1:
signIn();
break;
case 2:
signUp();
break;
case 3: // close with condition in while
break;
default:
System.out.println("UnkNow choice " + choice + "\n");
break;
}
}
private static void testDSAGenParameterSpec(DataTuple dataTuple)
throws NoSuchAlgorithmException,InvalidParameterSpecException,InvalidAlgorithmParameterException {
System.out.printf("Test case: primePLen=%d," + "subprimeQLen=%d%n",dataTuple.primePLen,dataTuple.subprimeQLen);
AlgorithmParameterGenerator apg
= AlgorithmParameterGenerator.getInstance(ALGORITHM_NAME,PROVIDER_NAME);
DSAGenParameterSpec genParamSpec = createGenParameterSpec(dataTuple);
// genParamSpec will be null if IllegalAE is thrown when expected.
if (genParamSpec == null) {
return;
}
try {
apg.init(genParamSpec,null);
AlgorithmParameters param = apg.generateParameters();
checkParam(param,genParamSpec);
System.out.println("Test case passed");
} catch (InvalidParameterException ipe) {
throw new RuntimeException("Test case Failed.",ipe);
}
}
项目:xitk
文件:KeyUtil.java
public static KeyPair generateRSAKeypair(int keysize,BigInteger publicExponent,SecureRandom random) throws NoSuchAlgorithmException,InvalidAlgorithmParameterException {
BigInteger tmpPublicExponent = publicExponent;
if (tmpPublicExponent == null) {
tmpPublicExponent = RSAKeyGenParameterSpec.F4;
}
AlgorithmParameterSpec params = new RSAKeyGenParameterSpec(keysize,tmpPublicExponent);
KeyPairGenerator kpGen = getKeyPairGenerator("RSA");
synchronized (kpGen) {
if (random == null) {
kpGen.initialize(params);
} else {
kpGen.initialize(params,random);
}
return kpGen.generateKeyPair();
}
}
项目:wolfcrypt-jni
文件:WolfCryptKeyPairGeneratorTest.java
@Test
public void testKeyPairGeneratorEccInitializeWithKeySize()
throws NoSuchProviderException,InvalidAlgorithmParameterException {
/* try initializing KPG for all supported key sizes */
for (int i = 0; i < enabledKeySizes.size(); i++) {
KeyPairGenerator kpg =
KeyPairGenerator.getInstance("EC","wolfJCE");
kpg.initialize(enabledKeySizes.get(i));
/* bad key size should fail */
try {
kpg.initialize(9999);
} catch (WolfCryptException e) {}
}
}
项目:ipack
文件:KeyPairGeneratorSpi.java
public void initialize(
int strength,SecureRandom random)
{
this.strength = strength;
this.random = random;
if (ecParams != null)
{
try
{
initialize((ECGenParameterSpec)ecParams,random);
}
catch (InvalidAlgorithmParameterException e)
{
throw new InvalidParameterException("key size not configurable.");
}
}
else
{
throw new InvalidParameterException("unkNown key size.");
}
}
public Transform newTransform(String algorithm,"DOM");
}
}
spi.init(params);
return new DOMTransform(spi);
}
项目:CrashCoin
文件:WalletClient.java
public WalletClient(final File f,final char[] userPassword) throws IOException,ClassNotFoundException,InstantiationException {
super(f,userPassword);
acceptedTransactionsList = new ArrayList<>();
unacceptedTransactionsList = new ArrayList<>();
}
项目:L2jBrasil
文件:GameServerTable.java
public GameServerTable() throws sqlException,InvalidAlgorithmParameterException
{
loadServerNames();
_log.info("Loaded "+_serverNames.size()+" server names");
loadRegisteredGameServers();
_log.info("Loaded "+_gameServerTable.size()+" registered Game Servers");
loadRSAKeys();
_log.info("Cached "+_keyPairs.length+" RSA keys for Game Server communication.");
}
项目:jdk8u-jdk
文件:DOMDigestMethod.java
/**
* Creates a <code>DOMDigestMethod</code> from an element. This constructor
* invokes the abstract {@link #unmarshalParams unmarshalParams} method to
* unmarshal any algorithm-specific input parameters.
*
* @param dmElem a DigestMethod element
*/
DOMDigestMethod(Element dmElem) throws MarshalException {
Element paramsElem = DOMUtils.getFirstChildElement(dmElem);
if (paramsElem != null) {
params = unmarshalParams(paramsElem);
}
try {
checkParams(params);
} catch (InvalidAlgorithmParameterException iape) {
throw new MarshalException(iape);
}
}
@Override
protected void engineInit(
AlgorithmParameterSpec genParamSpec,SecureRandom random)
throws InvalidAlgorithmParameterException
{
if (genParamSpec instanceof RC2ParameterSpec)
{
spec = (RC2ParameterSpec)genParamSpec;
return;
}
throw new InvalidAlgorithmParameterException("No supported AlgorithmParameterSpec for RC2 parameter generation.");
}
项目:jdk8u-jdk
文件:SignatureDSA.java
项目:openjdk-jdk10
文件:DOMDigestMethod.java
/**
* Creates a <code>DOMDigestMethod</code> from an element. This constructor
* invokes the abstract {@link #unmarshalParams unmarshalParams} method to
* unmarshal any algorithm-specific input parameters.
*
* @param dmElem a DigestMethod element
*/
DOMDigestMethod(Element dmElem) throws MarshalException {
Element paramsElem = DOMUtils.getFirstChildElement(dmElem);
if (paramsElem != null) {
params = unmarshalParams(paramsElem);
}
try {
checkParams(params);
} catch (InvalidAlgorithmParameterException iape) {
throw new MarshalException(iape);
}
}
项目:SecureUtils
文件:AES256PKCS5Padding.java
public static String encryptAES256PKCS5Padding(String key,String src)
throws NoSuchPaddingException,UnsupportedEncodingException,InvalidKeyException {
Cipher cipher = Cipher.getInstance(ALGORITHM_ENCODING);
cipher.init(Cipher.ENCRYPT_MODE,generateKeyAES256(key),new IvParameterSpec(new byte[cipher.getBlockSize()]));
return Base64.encodeBytes(cipher.doFinal(src.getBytes()));
}
项目:SecureUtils
文件:AES256PKCS5Padding.java
项目:SecureUtils
文件:AES256PKCS7Padding.java
private static SecretKey generateKeyAES256(String key)
throws InvalidAlgorithmParameterException,UnsupportedEncodingException {
if (key.getBytes().length != 32){
throw new InvalidAlgorithmParameterException("Key length must be 32 bytes");
}
return new SecretKeySpec(key.getBytes(TEXT_ENCODING),KEY_ENCODING);
}
项目:SecureUtils
文件:AES128PKCS5Padding.java
public static String decryptAES128PKCS5Padding(String key,generateKeyAES128(key),new IvParameterSpec(new byte[cipher.getBlockSize()]));
return new String(cipher.doFinal(Base64.decode(src)));
}
项目:SecureUtils
文件:AES128PKCS7Padding.java
public static String encryptAES128PKCS7Padding(String key,new IvParameterSpec(new byte[cipher.getBlockSize()]));
return Base64.encodeBytes(cipher.doFinal(src.getBytes()));
}
private static void checkParam(AlgorithmParameters param,DSAGenParameterSpec genParam) throws InvalidParameterSpecException,InvalidAlgorithmParameterException {
String algorithm = param.getAlgorithm();
if (!algorithm.equalsIgnoreCase(ALGORITHM_NAME)) {
throw new RuntimeException(
"Unexpected type of parameters: " + algorithm);
}
DSAParameterSpec spec = param.getParameterSpec(DSAParameterSpec.class);
int valueL = spec.getP().bitLength();
int strengthP = genParam.getPrimePLength();
if (strengthP != valueL) {
System.out.printf("P: Expected %d but actual %d%n",strengthP,valueL);
throw new RuntimeException("Wrong P strength");
}
int valueN = spec.getQ().bitLength();
int strengthQ = genParam.getSubprimeQLength();
if (strengthQ != valueN) {
System.out.printf("Q: Expected %d but actual %d%n",strengthQ,valueN);
throw new RuntimeException("Wrong Q strength");
}
if (genParam.getSubprimeQLength() != genParam.getSeedLength()) {
System.out.println("Defaut seed length should be the same as Q.");
throw new RuntimeException("Wrong seed length");
}
KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM_NAME,PROVIDER_NAME);
keyGen.initialize(spec);
}
项目:SecureUtils
文件:securestringTest.java
@Test
public void notEqualsIsCorrect()
throws NoSuchPaddingException,InvalidKeyException {
securestring securestring1 = new securestring(KEY,"dummy test");
securestring securestring2 = new securestring(KEY,"different dummy test");
assertFalse(securestring1.isEqualTo(securestring2));
}
项目:SecureUtils
文件:securestringTest.java
@Test
public void isEmptyIsCorrect()
throws NoSuchPaddingException,"");
assertTrue(securestring1.isEmpty());
}
项目:openjdk-jdk10
文件:CICOSkipTest.java
CipherGenerator(String algo) throws NoSuchAlgorithmException,NoSuchPaddingException,InvalidKeySpecException {
// Do initialization
byte[] salt = TestUtilities.generateBytes(IV_LENGTH);
int iterCnt = 6;
SecretKeyFactory skf = SecretKeyFactory.getInstance(algo.split("/")[0]);
SecretKey key = skf
.generateSecret(new PBEKeySpec(PASSWD.tochararray()));
AlgorithmParameterSpec aps = new PBEParameterSpec(salt,iterCnt);
initCiphers(algo,key,aps);
}
项目:dracoon-dropzone
文件:CryptoUtil.java
private byte[] encrypt(byte[] plainText,byte[] key,byte[] initialVector)
throws NoSuchAlgorithmException,BadPaddingException {
Cipher cipher = Cipher.getInstance(cipherTransformation);
SecretKeySpec secretKeySpec = new SecretKeySpec(key,aesEncryptionAlgorithm);
IvParameterSpec ivParameterSpec = new IvParameterSpec(initialVector);
cipher.init(Cipher.ENCRYPT_MODE,secretKeySpec,ivParameterSpec);
plainText = cipher.doFinal(plainText);
return plainText;
}
项目:keepass2android
文件:JCEStreamCipher.java
项目:keepass2android
文件:NativeAESCipherSpi.java
@Override
protected void engineInit(int opmode,Key key,AlgorithmParameters params,SecureRandom random) throws InvalidKeyException,InvalidAlgorithmParameterException {
try {
engineInit(opmode,params.getParameterSpec(AlgorithmParameterSpec.class),random);
} catch (InvalidParameterSpecException e) {
throw new InvalidAlgorithmParameterException(e);
}
}
项目:wolfcrypt-jni
文件:WolfCryptCipher.java
private void wolfCryptSetIV(AlgorithmParameterSpec spec,SecureRandom random) throws InvalidAlgorithmParameterException {
/* store AlgorithmParameterSpec for class reset */
this.storedSpec = spec;
/* RSA doesn't need an IV */
if (this.cipherType == CipherType.WC_RSA)
return;
/* store IV,or generate random IV if not available */
if (spec == null) {
this.iv = new byte[this.blockSize];
if (random != null) {
random.nextBytes(this.iv);
} else {
SecureRandom rand = new SecureRandom();
rand.nextBytes(this.iv);
}
} else {
if (!(spec instanceof IvParameterSpec)) {
throw new InvalidAlgorithmParameterException(
"AlgorithmParameterSpec must be of type IvParameterSpec");
}
IvParameterSpec ivSpec = (IvParameterSpec)spec;
/* IV should be of block size length */
if (ivSpec.getIV().length != this.blockSize) {
throw new InvalidAlgorithmParameterException(
"Bad IV length (" + ivSpec.getIV().length +
"),must be " + blockSize + " bytes long");
}
this.iv = ivSpec.getIV();
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。