use of java.security.PublicKey in project yyl_example by Relucent.
the class Rsa method main.
public static void main(String[] args) throws Exception {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
// 密钥位数
keyPairGen.initialize(1024);
// 密钥对
KeyPair keyPair = keyPairGen.generateKeyPair();
// 公钥
PublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
// 私钥
PrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
String publicKeyString = getKeyString(publicKey);
System.out.println("public:\n" + publicKeyString);
String privateKeyString = getKeyString(privateKey);
System.out.println("private:\n" + privateKeyString);
// 加解密类
// Cipher.getInstance("RSA/ECB/PKCS1Padding");
Cipher cipher = Cipher.getInstance("RSA");
// 明文
byte[] plainText = "我们都很好!邮件:@sina.com".getBytes();
// 加密
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] enBytes = cipher.doFinal(plainText);
// 通过密钥字符串得到密钥
publicKey = getPublicKey(publicKeyString);
privateKey = getPrivateKey(privateKeyString);
// 解密
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] deBytes = cipher.doFinal(enBytes);
publicKeyString = getKeyString(publicKey);
System.out.println("public:\n" + publicKeyString);
privateKeyString = getKeyString(privateKey);
System.out.println("private:\n" + privateKeyString);
String s = new String(deBytes);
System.out.println(s);
}
use of java.security.PublicKey in project yyl_example by Relucent.
the class Rsa method getPublicKey.
/**
* 得到公钥
* @param key 密钥字符串(经过base64编码)
* @throws Exception
*/
public static PublicKey getPublicKey(String key) throws Exception {
byte[] keyBytes;
keyBytes = (new sun.misc.BASE64Decoder()).decodeBuffer(key);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(keySpec);
return publicKey;
}
use of java.security.PublicKey in project azure-sdk-for-java by Azure.
the class RsaValidationTests method validateRsaKey.
private static void validateRsaKey(KeyPair keyPair, JsonWebKey key) throws Exception {
JsonWebKey jsonWebKey = JsonWebKey.fromRSA(keyPair);
boolean includePrivateKey = keyPair.getPrivate() != null;
KeyPair keyPair2 = jsonWebKey.toRSA(includePrivateKey);
Assert.assertTrue(includePrivateKey == jsonWebKey.hasPrivateKey());
PublicKey publicKey = keyPair2.getPublic();
PrivateKey privateKey = keyPair2.getPrivate();
if (includePrivateKey) {
Assert.assertNotNull(privateKey);
// set the missing properties to compare the keys
jsonWebKey.withKeyOps(new ArrayList<JsonWebKeyOperation>(key.keyOps()));
jsonWebKey.withKid(new String(key.kid()));
Assert.assertEquals(jsonWebKey, key);
Assert.assertEquals(key.hashCode(), jsonWebKey.hashCode());
}
encryptDecrypt(publicKey, privateKey);
}
use of java.security.PublicKey in project android_frameworks_base by DirtyUnicorns.
the class PackageParser method parseKeySets.
private boolean parseKeySets(Package owner, Resources res, XmlResourceParser parser, String[] outError) throws XmlPullParserException, IOException {
// we've encountered the 'key-sets' tag
// all the keys and keysets that we want must be defined here
// so we're going to iterate over the parser and pull out the things we want
int outerDepth = parser.getDepth();
int currentKeySetDepth = -1;
int type;
String currentKeySet = null;
ArrayMap<String, PublicKey> publicKeys = new ArrayMap<String, PublicKey>();
ArraySet<String> upgradeKeySets = new ArraySet<String>();
ArrayMap<String, ArraySet<String>> definedKeySets = new ArrayMap<String, ArraySet<String>>();
ArraySet<String> improperKeySets = new ArraySet<String>();
while ((type = parser.next()) != XmlPullParser.END_DOCUMENT && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
if (type == XmlPullParser.END_TAG) {
if (parser.getDepth() == currentKeySetDepth) {
currentKeySet = null;
currentKeySetDepth = -1;
}
continue;
}
String tagName = parser.getName();
if (tagName.equals("key-set")) {
if (currentKeySet != null) {
outError[0] = "Improperly nested 'key-set' tag at " + parser.getPositionDescription();
mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
return false;
}
final TypedArray sa = res.obtainAttributes(parser, com.android.internal.R.styleable.AndroidManifestKeySet);
final String keysetName = sa.getNonResourceString(com.android.internal.R.styleable.AndroidManifestKeySet_name);
definedKeySets.put(keysetName, new ArraySet<String>());
currentKeySet = keysetName;
currentKeySetDepth = parser.getDepth();
sa.recycle();
} else if (tagName.equals("public-key")) {
if (currentKeySet == null) {
outError[0] = "Improperly nested 'key-set' tag at " + parser.getPositionDescription();
mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
return false;
}
final TypedArray sa = res.obtainAttributes(parser, com.android.internal.R.styleable.AndroidManifestPublicKey);
final String publicKeyName = sa.getNonResourceString(com.android.internal.R.styleable.AndroidManifestPublicKey_name);
final String encodedKey = sa.getNonResourceString(com.android.internal.R.styleable.AndroidManifestPublicKey_value);
if (encodedKey == null && publicKeys.get(publicKeyName) == null) {
outError[0] = "'public-key' " + publicKeyName + " must define a public-key value" + " on first use at " + parser.getPositionDescription();
mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
sa.recycle();
return false;
} else if (encodedKey != null) {
PublicKey currentKey = parsePublicKey(encodedKey);
if (currentKey == null) {
Slog.w(TAG, "No recognized valid key in 'public-key' tag at " + parser.getPositionDescription() + " key-set " + currentKeySet + " will not be added to the package's defined key-sets.");
sa.recycle();
improperKeySets.add(currentKeySet);
XmlUtils.skipCurrentTag(parser);
continue;
}
if (publicKeys.get(publicKeyName) == null || publicKeys.get(publicKeyName).equals(currentKey)) {
/* public-key first definition, or matches old definition */
publicKeys.put(publicKeyName, currentKey);
} else {
outError[0] = "Value of 'public-key' " + publicKeyName + " conflicts with previously defined value at " + parser.getPositionDescription();
mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
sa.recycle();
return false;
}
}
definedKeySets.get(currentKeySet).add(publicKeyName);
sa.recycle();
XmlUtils.skipCurrentTag(parser);
} else if (tagName.equals("upgrade-key-set")) {
final TypedArray sa = res.obtainAttributes(parser, com.android.internal.R.styleable.AndroidManifestUpgradeKeySet);
String name = sa.getNonResourceString(com.android.internal.R.styleable.AndroidManifestUpgradeKeySet_name);
upgradeKeySets.add(name);
sa.recycle();
XmlUtils.skipCurrentTag(parser);
} else if (RIGID_PARSER) {
outError[0] = "Bad element under <key-sets>: " + parser.getName() + " at " + mArchiveSourcePath + " " + parser.getPositionDescription();
mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
return false;
} else {
Slog.w(TAG, "Unknown element under <key-sets>: " + parser.getName() + " at " + mArchiveSourcePath + " " + parser.getPositionDescription());
XmlUtils.skipCurrentTag(parser);
continue;
}
}
Set<String> publicKeyNames = publicKeys.keySet();
if (publicKeyNames.removeAll(definedKeySets.keySet())) {
outError[0] = "Package" + owner.packageName + " AndroidManifext.xml " + "'key-set' and 'public-key' names must be distinct.";
mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
return false;
}
owner.mKeySetMapping = new ArrayMap<String, ArraySet<PublicKey>>();
for (ArrayMap.Entry<String, ArraySet<String>> e : definedKeySets.entrySet()) {
final String keySetName = e.getKey();
if (e.getValue().size() == 0) {
Slog.w(TAG, "Package" + owner.packageName + " AndroidManifext.xml " + "'key-set' " + keySetName + " has no valid associated 'public-key'." + " Not including in package's defined key-sets.");
continue;
} else if (improperKeySets.contains(keySetName)) {
Slog.w(TAG, "Package" + owner.packageName + " AndroidManifext.xml " + "'key-set' " + keySetName + " contained improper 'public-key'" + " tags. Not including in package's defined key-sets.");
continue;
}
owner.mKeySetMapping.put(keySetName, new ArraySet<PublicKey>());
for (String s : e.getValue()) {
owner.mKeySetMapping.get(keySetName).add(publicKeys.get(s));
}
}
if (owner.mKeySetMapping.keySet().containsAll(upgradeKeySets)) {
owner.mUpgradeKeySets = upgradeKeySets;
} else {
outError[0] = "Package" + owner.packageName + " AndroidManifext.xml " + "does not define all 'upgrade-key-set's .";
mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
return false;
}
return true;
}
use of java.security.PublicKey in project GNS by MobilityFirst.
the class SimpleClientExample method main.
/**
*
* @param args
* @throws IOException
* @throws InvalidKeySpecException
* @throws NoSuchAlgorithmException
* @throws ClientException
* @throws InvalidKeyException
* @throws SignatureException
* @throws Exception
*/
public static void main(String[] args) throws IOException, InvalidKeySpecException, NoSuchAlgorithmException, ClientException, InvalidKeyException, SignatureException, Exception {
// Create the client. Connects to a default reconfigurator as specified in gigapaxos.properties file.
client = new GNSClientCommands();
try {
// Create an account guid if one doesn't already exists.
// The true makes it verbosely print out what it is doing.
// The password is for future use.
// Note that lookupOrCreateAccountGuid "cheats" by bypassing the account verification
// mechanisms.
accountGuid = GuidUtils.lookupOrCreateAccountGuid(client, ACCOUNT_ALIAS, PASSWORD, true);
} catch (Exception e) {
System.out.println("Exception during accountGuid creation: " + e);
System.exit(1);
}
System.out.println("Client connected to GNS");
// Retrive the GUID using the account id
String guid = client.lookupGuid(ACCOUNT_ALIAS);
System.out.println("Retrieved GUID for " + ACCOUNT_ALIAS + ": " + guid);
// Get the public key from the GNS
PublicKey publicKey = client.publicKeyLookupFromGuid(guid);
System.out.println("Retrieved public key: " + publicKey.toString());
// Use the GuidEntry create an new record in the GNS
client.fieldUpdate(accountGuid, "homestate", "Florida");
System.out.println("Added homestate -> Florida record to the GNS for GUID " + accountGuid.getGuid());
// Retrive that record from the GNS
String result = client.fieldRead(accountGuid.getGuid(), "homestate", accountGuid);
System.out.println("Result of read location: " + result);
System.exit(0);
}
Aggregations